Skip to content

Commit

Permalink
Writer: fix #170
Browse files Browse the repository at this point in the history
  • Loading branch information
pierrec committed Feb 12, 2022
1 parent 6873886 commit f9f4ce2
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 5 deletions.
18 changes: 13 additions & 5 deletions writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,9 +144,8 @@ func (w *Writer) write(data []byte, safe bool) error {
return nil
}

// Close closes the Writer, flushing any unwritten data to the underlying io.Writer,
// but does not close the underlying io.Writer.
func (w *Writer) Close() (err error) {
// Flush any buffered data to the underlying writer immediately.
func (w *Writer) Flush() (err error) {
switch w.state.state {
case writeState:
case errorState:
Expand All @@ -162,13 +161,22 @@ func (w *Writer) Close() (err error) {
}
w.idx = 0
}
err = w.frame.CloseW(w.src, w.num)
return nil
}

// Close closes the Writer, flushing any unwritten data to the underlying writer
// without closing it.
func (w *Writer) Close() error {
if err := w.Flush(); err != nil {
return err
}
err := w.frame.CloseW(w.src, w.num)
// It is now safe to free the buffer.
if w.data != nil {
lz4block.Put(w.data)
w.data = nil
}
return
return err
}

// Reset clears the state of the Writer w such that it is equivalent to its
Expand Down
23 changes: 23 additions & 0 deletions writer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,29 @@ func TestIssue71(t *testing.T) {
}
}

func TestWriterFlush(t *testing.T) {
out := new(bytes.Buffer)
zw := lz4.NewWriter(out)
if err := zw.Apply(); err != nil {
t.Fatal(err)
}
data := strings.Repeat("0123456789", 100)
if _, err := zw.Write([]byte(data)); err != nil {
t.Fatal(err)
}
// header only
if got, want := out.Len(), 7; got != want {
t.Fatalf("got %d, want %d", got, want)
}
if err := zw.Flush(); err != nil {
t.Fatal(err)
}
// header + data
if got, want := out.Len(), 7; got == want {
t.Fatalf("got %d, want %d", got, want)
}
}

func TestWriterLegacy(t *testing.T) {
goldenFiles := []string{
"testdata/vmlinux_LZ4_19377",
Expand Down

0 comments on commit f9f4ce2

Please sign in to comment.