Reuse ringbuffer in Reader.

Fixes #33
This commit is contained in:
Andy Balholm 2022-05-18 12:05:34 -07:00
parent f001d275a3
commit 786ec621f6
3 changed files with 22 additions and 12 deletions

View File

@ -345,6 +345,22 @@ func TestReader(t *testing.T) {
"<%d bytes>", "<%d bytes>",
got, len(content)) 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) { func TestDecode(t *testing.T) {

View File

@ -1304,26 +1304,21 @@ func wrapRingBuffer(s *Reader) {
Last two bytes of ring-buffer are initialized to 0, so context calculation 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. */ could be done uniformly for the first two and all other positions. */
func ensureRingBuffer(s *Reader) bool { func ensureRingBuffer(s *Reader) bool {
var old_ringbuffer []byte = s.ringbuffer var old_ringbuffer []byte
if s.ringbuffer_size == s.new_ringbuffer_size { if s.ringbuffer_size == s.new_ringbuffer_size {
return true return true
} }
spaceNeeded := int(s.new_ringbuffer_size) + int(kRingBufferWriteAheadSlack)
s.ringbuffer = make([]byte, uint(s.new_ringbuffer_size)+uint(kRingBufferWriteAheadSlack)) if len(s.ringbuffer) < spaceNeeded {
if s.ringbuffer == nil { old_ringbuffer = s.ringbuffer
/* Restore previous value. */ s.ringbuffer = make([]byte, spaceNeeded)
s.ringbuffer = old_ringbuffer
return false
} }
s.ringbuffer[s.new_ringbuffer_size-2] = 0 s.ringbuffer[s.new_ringbuffer_size-2] = 0
s.ringbuffer[s.new_ringbuffer_size-1] = 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)]) copy(s.ringbuffer, old_ringbuffer[:uint(s.pos)])
old_ringbuffer = nil
} }
s.ringbuffer_size = s.new_ringbuffer_size s.ringbuffer_size = s.new_ringbuffer_size

View File

@ -200,7 +200,6 @@ func decoderStateInit(s *Reader) bool {
s.block_type_trees = nil s.block_type_trees = nil
s.block_len_trees = nil s.block_len_trees = nil
s.ringbuffer = nil
s.ringbuffer_size = 0 s.ringbuffer_size = 0
s.new_ringbuffer_size = 0 s.new_ringbuffer_size = 0
s.ringbuffer_mask = 0 s.ringbuffer_mask = 0