Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add io.SeekEnd support #16

Merged
merged 5 commits into from
May 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions aws_s3_reader_seeker.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,14 @@ func (s *S3ReadSeeker) Seek(offset int64, whence int) (int64, error) {
}
discardBytes = int(offset - s.offset)
s.offset = offset
case io.SeekEnd:
if offset > 0 {
return 0, errors.New("cannot seek beyond end")
}
size := s.getSize()
noffset := int64(size) + offset
discardBytes = int(noffset - s.offset)
s.offset = noffset
default:
return 0, errors.New("unsupported whence")
}
Expand Down
71 changes: 71 additions & 0 deletions aws_s3_reader_seeker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,3 +238,74 @@ func ExampleS3ReadSeeker() {
panic(err)
}
}
func TestS3ReadSeeker_Seek(t *testing.T) {
mySession := session.Must(session.NewSession(
aws.NewConfig().
WithRegion("ap-southeast-1").
WithCredentials(credentials.AnonymousCredentials),
))
s3client := s3.New(mySession)

bucket := "nikolaydubina-blog-public"
key := "photos/2021-12-20-4.jpeg"

r := awss3reader.NewS3ReadSeeker(
s3client,
bucket,
key,
awss3reader.FixedChunkSizePolicy{Size: 1 << 10 * 100}, // 100 KB
)
defer r.Close()

// Seek to offset 100 from current position
offset, err := r.Seek(100, io.SeekCurrent)
if err != nil {
t.Fatal(err)
}
if offset != 100 {
t.Errorf("expected offset 100, got %d", offset)
}

// Seek to offset 200 from start
offset, err = r.Seek(200, io.SeekStart)
if err != nil {
t.Fatal(err)
}
if offset != 200 {
t.Errorf("expected offset 200, got %d", offset)
}

// Seek to current position (0 offset)
offset, err = r.Seek(0, io.SeekCurrent)
if err != nil {
t.Fatal(err)
}
if offset != 200 {
t.Errorf("expected offset 200, got %d", offset)
}

// Seek beyond end of file
_, err = r.Seek(1000, io.SeekEnd)
if err == nil {
t.Errorf("expected error, got nil when seeking beyond end of file")
}

// seek 0 from end
offset, err = r.Seek(0, io.SeekEnd)
if err != nil {
t.Errorf("expected nil, got %v when seeking 0 from end", err)
}
if offset != 11356322 {
t.Errorf("expected offset 11356322, got %d", offset)
}

// seek -100 from end
offset, err = r.Seek(-100, io.SeekEnd)
if err != nil {
t.Errorf("expected nil, got %v when seeking -100 from end", err)
}

if offset != 11356222 {
t.Errorf("expected offset 11356222, got %d", offset)
}
}
Loading