Browse Source

Added OnBlockDone handlers to the Reader and Writer.
Especially useful for progress bar integration.

Pierre Curto 6 years ago
parent
commit
b69316ffb4
2 changed files with 14 additions and 1 deletions
  1. 6 0
      reader.go
  2. 8 1
      writer.go

+ 6 - 0
reader.go

@@ -14,6 +14,9 @@ import (
 // The Header may change between Read() calls in case of concatenated frames.
 type Reader struct {
 	Header
+	// Handler called when a block has been successfully read.
+	// It provides the number of bytes read.
+	OnBlockDone func(size int)
 
 	buf      [8]byte       // Scrap buffer.
 	pos      int64         // Current position in src.
@@ -255,6 +258,9 @@ func (z *Reader) Read(buf []byte) (int, error) {
 				return 0, err
 			}
 			z.data = z.data[:n]
+			if z.OnBlockDone != nil {
+				z.OnBlockDone(n)
+			}
 		}
 
 		if !z.NoChecksum {

+ 8 - 1
writer.go

@@ -11,6 +11,9 @@ import (
 // Writer implements the LZ4 frame encoder.
 type Writer struct {
 	Header
+	// Handler called when a block has been successfully written out.
+	// It provides the number of bytes written.
+	OnBlockDone func(size int)
 
 	buf       [19]byte      // magic number(4) + header(flags(2)+[Size(8)+DictID(4)]+checksum(1)) does not exceed 19 bytes
 	dst       io.Writer     // Destination.
@@ -182,9 +185,13 @@ func (z *Writer) compressBlock(data []byte) error {
 	if err := z.writeUint32(bLen); err != nil {
 		return err
 	}
-	if _, err := z.dst.Write(zdata); err != nil {
+	written, err := z.dst.Write(zdata)
+	if err != nil {
 		return err
 	}
+	if h := z.OnBlockDone; h != nil {
+		h(written)
+	}
 
 	if z.BlockChecksum {
 		checksum := xxh32.ChecksumZero(zdata)