Skip to content

Commit

Permalink
Return nil as Index reader when reading indexless CARv2
Browse files Browse the repository at this point in the history
Fix an issue where if a  `v2.Reader` is given an indexless CARv2, an
invalid section reader is returned.

Add tests to assert fix using CARv1 and indexless CARv2 sample files.


This commit was moved from ipld/go-car@1bac13d
  • Loading branch information
masih committed Aug 27, 2021
1 parent 5f33f8c commit 13be827
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 3 deletions.
6 changes: 3 additions & 3 deletions ipld/car/v2/reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,10 @@ func (r *Reader) DataReader() SectionReader {
// present. Otherwise, returns nil.
// Note, this function will always return nil if the backing payload represents a CARv1.
func (r *Reader) IndexReader() io.Reader {
if r.Version == 2 {
return internalio.NewOffsetReadSeeker(r.r, int64(r.Header.IndexOffset))
if r.Version == 1 || !r.Header.HasIndex() {
return nil
}
return nil
return internalio.NewOffsetReadSeeker(r.r, int64(r.Header.IndexOffset))
}

// Close closes the underlying reader if it was opened by OpenReader.
Expand Down
24 changes: 24 additions & 0 deletions ipld/car/v2/reader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,30 @@ func TestOpenReader_DoesNotPanicForReadersCreatedAfterClosure(t *testing.T) {
require.NotPanics(t, func() { panicTest(iReaderAfterClosure) })
}

func TestReader_ReturnsNilWhenThereIsNoIndex(t *testing.T) {
tests := []struct {
name string
path string
}{
{
name: "IndexlessCarV2",
path: "testdata/sample-v2-indexless.car",
},
{
name: "CarV1",
path: "testdata/sample-v1.car",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
subject, err := carv2.OpenReader(tt.path)
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, subject.Close()) })
require.Nil(t, subject.IndexReader())
})
}
}

func requireNewCarV1ReaderFromV2File(t *testing.T, carV12Path string, zerLenAsEOF bool) *carv1.CarReader {
f, err := os.Open(carV12Path)
require.NoError(t, err)
Expand Down
Binary file added ipld/car/v2/testdata/sample-v2-indexless.car
Binary file not shown.

0 comments on commit 13be827

Please sign in to comment.