Skip to content

Commit

Permalink
s2: Fix incorrect seek for io.SeekEnd (#575)
Browse files Browse the repository at this point in the history
Offset sign was flipped

Fixes #574
  • Loading branch information
klauspost committed Apr 29, 2022
1 parent 75b1f22 commit f31f904
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 7 deletions.
2 changes: 1 addition & 1 deletion s2/cmd/s2d/main.go
Expand Up @@ -278,7 +278,7 @@ Options:`)
rs, err := r.ReadSeeker(tailBytes > 0, nil)
exitErr(err)
if tailBytes > 0 {
_, err = rs.Seek(int64(tailBytes), io.SeekEnd)
_, err = rs.Seek(-int64(tailBytes), io.SeekEnd)
} else {
_, err = rs.Seek(int64(offset), io.SeekStart)
}
Expand Down
14 changes: 9 additions & 5 deletions s2/decode.go
Expand Up @@ -699,8 +699,16 @@ func (r *ReadSeeker) Seek(offset int64, whence int) (int64, error) {
case io.SeekCurrent:
offset += r.blockStart + int64(r.i)
case io.SeekEnd:
offset = -offset
if offset > 0 {
return 0, errors.New("seek after end of file")
}
offset = r.index.TotalUncompressed + offset
}

if offset < 0 {
return 0, errors.New("seek before start of file")
}

c, u, err := r.index.Find(offset)
if err != nil {
return r.blockStart + int64(r.i), err
Expand All @@ -712,10 +720,6 @@ func (r *ReadSeeker) Seek(offset int64, whence int) (int64, error) {
return 0, err
}

if offset < 0 {
offset = r.index.TotalUncompressed + offset
}

r.i = r.j // Remove rest of current block.
if u < offset {
// Forward inside block
Expand Down
2 changes: 1 addition & 1 deletion s2/encode_test.go
Expand Up @@ -333,7 +333,7 @@ func TestIndex(t *testing.T) {
case io.SeekCurrent:
toSkip = wantOffset - int64(len(input)/2)
case io.SeekEnd:
toSkip = int64(len(input)) - wantOffset
toSkip = -(int64(len(input)) - wantOffset)
}
gotOffset, err := rs.Seek(toSkip, i)
if gotOffset != wantOffset {
Expand Down

0 comments on commit f31f904

Please sign in to comment.