From 37485901aede7de5daa625f407b470b77e0126b1 Mon Sep 17 00:00:00 2001 From: Ilya Barbashov Date: Sat, 27 Mar 2021 15:47:48 +0300 Subject: [PATCH] BytesIterator: NextBytesNoCopy added (#9) * BytesIterator: NextBytesFast added * renamed to NextBytesNoCopy Co-authored-by: Ilya Barbashov --- bytes.go | 14 ++++++++++++++ bytes_test.go | 8 ++++++++ 2 files changed, 22 insertions(+) diff --git a/bytes.go b/bytes.go index 0a23f65..155e2f0 100644 --- a/bytes.go +++ b/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 diff --git a/bytes_test.go b/bytes_test.go index c694cbb..2a88c9c 100644 --- a/bytes_test.go +++ b/bytes_test.go @@ -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 {