From 786ec621f618ab5545dfea6e29880962bed23644 Mon Sep 17 00:00:00 2001 From: Andy Balholm Date: Wed, 18 May 2022 12:05:34 -0700 Subject: [PATCH] Reuse ringbuffer in Reader. Fixes #33 --- brotli_test.go | 16 ++++++++++++++++ decode.go | 17 ++++++----------- state.go | 1 - 3 files changed, 22 insertions(+), 12 deletions(-) diff --git a/brotli_test.go b/brotli_test.go index 3392a94..8f761bb 100644 --- a/brotli_test.go +++ b/brotli_test.go @@ -345,6 +345,22 @@ func TestReader(t *testing.T) { "<%d bytes>", got, len(content)) } + + r.Reset(bytes.NewReader(encoded)) + decodedOutput.Reset() + n, err = io.Copy(&decodedOutput, r) + if err != nil { + t.Fatalf("After Reset: Copy(): n=%v, err=%v", n, err) + } + if got := decodedOutput.Bytes(); !bytes.Equal(got, content) { + t.Errorf("After Reset: "+ + "Reader output:\n"+ + "%q\n"+ + "want:\n"+ + "<%d bytes>", + got, len(content)) + } + } func TestDecode(t *testing.T) { diff --git a/decode.go b/decode.go index 6a73b88..9d9513b 100644 --- a/decode.go +++ b/decode.go @@ -1304,26 +1304,21 @@ func wrapRingBuffer(s *Reader) { Last two bytes of ring-buffer are initialized to 0, so context calculation could be done uniformly for the first two and all other positions. */ func ensureRingBuffer(s *Reader) bool { - var old_ringbuffer []byte = s.ringbuffer + var old_ringbuffer []byte if s.ringbuffer_size == s.new_ringbuffer_size { return true } - - s.ringbuffer = make([]byte, uint(s.new_ringbuffer_size)+uint(kRingBufferWriteAheadSlack)) - if s.ringbuffer == nil { - /* Restore previous value. */ - s.ringbuffer = old_ringbuffer - - return false + spaceNeeded := int(s.new_ringbuffer_size) + int(kRingBufferWriteAheadSlack) + if len(s.ringbuffer) < spaceNeeded { + old_ringbuffer = s.ringbuffer + s.ringbuffer = make([]byte, spaceNeeded) } s.ringbuffer[s.new_ringbuffer_size-2] = 0 s.ringbuffer[s.new_ringbuffer_size-1] = 0 - if !(old_ringbuffer == nil) { + if old_ringbuffer != nil { copy(s.ringbuffer, old_ringbuffer[:uint(s.pos)]) - - old_ringbuffer = nil } s.ringbuffer_size = s.new_ringbuffer_size diff --git a/state.go b/state.go index d03348f..38d753e 100644 --- a/state.go +++ b/state.go @@ -200,7 +200,6 @@ func decoderStateInit(s *Reader) bool { s.block_type_trees = nil s.block_len_trees = nil - s.ringbuffer = nil s.ringbuffer_size = 0 s.new_ringbuffer_size = 0 s.ringbuffer_mask = 0