Skip to content

Commit

Permalink
Merge pull request #365 from teo-tsirpanis/vfsfh-readat
Browse files Browse the repository at this point in the history
Add `VFSfh.ReadAt`.
  • Loading branch information
teo-tsirpanis authored Jan 22, 2025
2 parents 1ed8dab + eb12a3d commit a3a0a4c
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
41 changes: 41 additions & 0 deletions vfs.go
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,47 @@ func (v *VFSfh) Read(p []byte) (int, error) {
return int(nbytes), nil
}

// ReadAt reads part of a file at a given offset, without updating the object's internal offset.
func (v *VFSfh) ReadAt(p []byte, off int64) (int, error) {
if off < 0 {
return 0, errors.New("offset cannot be negative")
}

nbytes := uint64(len(p))

// If the size is empty, fetch it
if v.size == nil {
err := v.fetchAndSetSize()
if err != nil {
return 0, err
}
}

// If the requested read size is beyond the limit, truncate the read size.
// In this case we need to return io.EOF.
var err error = nil
if uint64(off)+nbytes >= *v.size {
if uint64(off) > *v.size {
return 0, io.EOF
}
nbytes = *v.size - uint64(off)
err = io.EOF
}

if nbytes == 0 {
return 0, err
}

cbuffer := slicePtr(p)
ret := C.tiledb_vfs_read(v.context.tiledbContext, v.tiledbVFSfh, C.uint64_t(off), cbuffer, C.uint64_t(nbytes))

if ret != C.TILEDB_OK {
return 0, fmt.Errorf("unknown error in VFS.Read: %w", v.context.LastError())
}

return int(nbytes), err
}

// Write writes the contents of a buffer into a file. Note that this function only
// appends data at the end of the file. If the file does not exist,
// it will be created.
Expand Down
22 changes: 22 additions & 0 deletions vfs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,28 @@ func TestVFSFH(t *testing.T) {
assert.Equal(t, 3, n)
require.NoError(t, err)
assert.ElementsMatch(t, b, bRead)
// Check value of offset.
noffset, err = r.Seek(0, io.SeekCurrent)
require.NoError(t, err)
assert.EqualValues(t, 3, noffset)

n, err = r.ReadAt(bRead, 0)
require.Equal(t, io.EOF, err)
assert.EqualValues(t, 3, n)
assert.ElementsMatch(t, b, bRead)
// Check that offset was not changed.
noffset, err = r.Seek(0, io.SeekCurrent)
require.NoError(t, err)
assert.EqualValues(t, 3, noffset)

n, err = r.ReadAt(bRead[:1], 0)
require.NoError(t, err)
assert.EqualValues(t, 1, n)
assert.Equal(t, b[0], bRead[0])
// Check that offset was not changed.
noffset, err = r.Seek(0, io.SeekCurrent)
require.NoError(t, err)
assert.EqualValues(t, 3, noffset)

n, err = r.Read(bRead)
assert.Error(t, err)
Expand Down

0 comments on commit a3a0a4c

Please sign in to comment.