mirror of
https://github.com/asticode/go-astikit.git
synced 2025-12-24 11:50:53 +08:00
BytesIterator: NextBytesNoCopy added (#9)
* BytesIterator: NextBytesFast added * renamed to NextBytesNoCopy Co-authored-by: Ilya Barbashov <barbashov.ilya@me.com>
This commit is contained in:
14
bytes.go
14
bytes.go
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user