BytesIterator: NextBytesNoCopy added (#9)

* BytesIterator: NextBytesFast added

* renamed to NextBytesNoCopy

Co-authored-by: Ilya Barbashov <barbashov.ilya@me.com>
This commit is contained in:
Ilya Barbashov
2021-03-27 15:47:48 +03:00
committed by GitHub
parent 0d8b6f5e22
commit 37485901ae
2 changed files with 22 additions and 0 deletions

View File

@@ -39,6 +39,20 @@ func (i *BytesIterator) NextBytes(n int) (bs []byte, err error) {
return
}
// NextBytesNoCopy returns the n next bytes
// Be careful with this function as it doesn't make a copy of returned data.
// bs will point to internal BytesIterator buffer.
// If you need to modify returned bytes or store it for some time, use NextBytes instead
func (i *BytesIterator) NextBytesNoCopy(n int) (bs []byte, err error) {
if len(i.bs) < i.offset+n {
err = fmt.Errorf("astikit: slice length is %d, offset %d is invalid", len(i.bs), i.offset+n)
return
}
bs = i.bs[i.offset : i.offset+n]
i.offset += n
return
}
// Seek seeks to the nth byte
func (i *BytesIterator) Seek(n int) {
i.offset = n

View File

@@ -24,6 +24,14 @@ func TestBytesIterator(t *testing.T) {
if e := []byte("23"); !bytes.Equal(e, bs) {
t.Errorf("expected %+v, got %+v", e, bs)
}
i.Seek(1)
bs, err = i.NextBytesNoCopy(2)
if err != nil {
t.Errorf("expected no error, got %+v", err)
}
if e := []byte("23"); !bytes.Equal(e, bs) {
t.Errorf("expected %+v, got %+v", e, bs)
}
i.Seek(4)
b, err = i.NextByte()
if err != nil {