Skip to content

Commit

Permalink
Fix: matchfinder Encode method bug
Browse files Browse the repository at this point in the history
When the close method of WriterV2 is called and there is no data in inBuf, it writes additional data beyond the ending.
  • Loading branch information
newacorn committed Jul 28, 2024
1 parent 17e5901 commit c8cd8fd
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
9 changes: 9 additions & 0 deletions encoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,15 @@ func (e *Encoder) Encode(dst []byte, src []byte, matches []matchfinder.Match, la
e.bw.writeBits(4, 15)
e.wroteHeader = true
}
//
if len(src) == 0 {
if lastBlock {
e.bw.writeBits(2, 3) // islast + isempty
e.bw.jumpToByteBoundary()
return e.bw.dst
}
return nil
}

var literalHisto [256]uint32
var commandHisto [704]uint32
Expand Down
12 changes: 10 additions & 2 deletions matchfinder/matchfinder.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
// representation to allow mixing and matching compression components.
package matchfinder

import "io"
import (
"io"
)

// A Match is the basic unit of LZ77 compression.
type Match struct {
Expand Down Expand Up @@ -79,8 +81,14 @@ func (w *Writer) Write(p []byte) (n int, err error) {
}

func (w *Writer) writeBlock(p []byte, lastBlock bool) (n int, err error) {
if len(p) == 0 {
if !lastBlock {
return
}
} else {
w.matches = w.MatchFinder.FindMatches(w.matches[:0], p)
}
w.outBuf = w.outBuf[:0]
w.matches = w.MatchFinder.FindMatches(w.matches[:0], p)
w.outBuf = w.Encoder.Encode(w.outBuf, p, w.matches, lastBlock)
_, w.err = w.Dest.Write(w.outBuf)
return len(p), w.err
Expand Down
3 changes: 3 additions & 0 deletions matchfinder/textencoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ type TextEncoder struct{}
func (t TextEncoder) Reset() {}

func (t TextEncoder) Encode(dst []byte, src []byte, matches []Match, lastBlock bool) []byte {
if len(src) == 0 {
return nil
}
pos := 0
for _, m := range matches {
if m.Unmatched > 0 {
Expand Down

0 comments on commit c8cd8fd

Please sign in to comment.