writer.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. package lz4
  2. import (
  3. "encoding/binary"
  4. "fmt"
  5. "io"
  6. "runtime"
  7. "github.com/pierrec/lz4/internal/xxh32"
  8. )
  9. // zResult contains the results of compressing a block.
  10. type zResult struct {
  11. size uint32 // Block header
  12. data []byte // Compressed data
  13. checksum uint32 // Data checksum
  14. }
  15. // Writer implements the LZ4 frame encoder.
  16. type Writer struct {
  17. Header
  18. // Handler called when a block has been successfully written out.
  19. // It provides the number of bytes written.
  20. OnBlockDone func(size int)
  21. buf [19]byte // magic number(4) + header(flags(2)+[Size(8)+DictID(4)]+checksum(1)) does not exceed 19 bytes
  22. dst io.Writer // Destination.
  23. checksum xxh32.XXHZero // Frame checksum.
  24. data []byte // Data to be compressed + buffer for compressed data.
  25. idx int // Index into data.
  26. hashtable [winSize]int // Hash table used in CompressBlock().
  27. // For concurrency.
  28. c chan chan zResult // Channel for block compression goroutines and writer goroutine.
  29. err error // Any error encountered while writing to the underlying destination.
  30. }
  31. // NewWriter returns a new LZ4 frame encoder.
  32. // No access to the underlying io.Writer is performed.
  33. // The supplied Header is checked at the first Write.
  34. // It is ok to change it before the first Write but then not until a Reset() is performed.
  35. func NewWriter(dst io.Writer) *Writer {
  36. z := new(Writer)
  37. z.Reset(dst)
  38. return z
  39. }
  40. // WithConcurrency sets the number of concurrent go routines used for compression.
  41. // A negative value sets the concurrency to GOMAXPROCS.
  42. func (z *Writer) WithConcurrency(n int) *Writer {
  43. switch {
  44. case n == 0 || n == 1:
  45. z.c = nil
  46. return z
  47. case n < 0:
  48. n = runtime.GOMAXPROCS(0)
  49. }
  50. z.c = make(chan chan zResult, n)
  51. // Writer goroutine managing concurrent block compression goroutines.
  52. go func() {
  53. // Process next block compression item.
  54. for c := range z.c {
  55. // Read the next compressed block result.
  56. // Waiting here ensures that the blocks are output in the order they were sent.
  57. // The incoming channel is always closed as it indicates to the caller that
  58. // the block has been processed.
  59. res := <-c
  60. n := len(res.data)
  61. if n == 0 {
  62. // Notify the block compression routine that we are done with its result.
  63. // This is used when a sentinel block is sent to terminate the compression.
  64. close(c)
  65. return
  66. }
  67. // Write the block.
  68. if err := z.writeUint32(res.size); err != nil && z.err == nil {
  69. z.err = err
  70. }
  71. if _, err := z.dst.Write(res.data); err != nil && z.err == nil {
  72. z.err = err
  73. }
  74. if z.BlockChecksum {
  75. if err := z.writeUint32(res.checksum); err != nil && z.err == nil {
  76. z.err = err
  77. }
  78. }
  79. if isCompressed := res.size&compressedBlockFlag == 0; isCompressed {
  80. // It is now safe to release the buffer as no longer in use by any goroutine.
  81. putBuffer(cap(res.data), res.data)
  82. }
  83. if h := z.OnBlockDone; h != nil {
  84. h(n)
  85. }
  86. close(c)
  87. }
  88. }()
  89. return z
  90. }
  91. // newBuffers instantiates new buffers which size matches the one in Header.
  92. // The returned buffers are for decompression and compression respectively.
  93. func (z *Writer) newBuffers() {
  94. bSize := z.Header.BlockMaxSize
  95. buf := getBuffer(bSize)
  96. z.data = buf[:bSize] // Uncompressed buffer is the first half.
  97. }
  98. // freeBuffers puts the writer's buffers back to the pool.
  99. func (z *Writer) freeBuffers() {
  100. // Put the buffer back into the pool, if any.
  101. putBuffer(z.Header.BlockMaxSize, z.data)
  102. z.data = nil
  103. }
  104. // writeHeader builds and writes the header (magic+header) to the underlying io.Writer.
  105. func (z *Writer) writeHeader() error {
  106. // Default to 4Mb if BlockMaxSize is not set.
  107. if z.Header.BlockMaxSize == 0 {
  108. z.Header.BlockMaxSize = blockSize4M
  109. }
  110. // The only option that needs to be validated.
  111. bSize := z.Header.BlockMaxSize
  112. if !isValidBlockSize(z.Header.BlockMaxSize) {
  113. return fmt.Errorf("lz4: invalid block max size: %d", bSize)
  114. }
  115. // Allocate the compressed/uncompressed buffers.
  116. // The compressed buffer cannot exceed the uncompressed one.
  117. z.newBuffers()
  118. z.idx = 0
  119. // Size is optional.
  120. buf := z.buf[:]
  121. // Set the fixed size data: magic number, block max size and flags.
  122. binary.LittleEndian.PutUint32(buf[0:], frameMagic)
  123. flg := byte(Version << 6)
  124. flg |= 1 << 5 // No block dependency.
  125. if z.Header.BlockChecksum {
  126. flg |= 1 << 4
  127. }
  128. if z.Header.Size > 0 {
  129. flg |= 1 << 3
  130. }
  131. if !z.Header.NoChecksum {
  132. flg |= 1 << 2
  133. }
  134. buf[4] = flg
  135. buf[5] = blockSizeValueToIndex(z.Header.BlockMaxSize) << 4
  136. // Current buffer size: magic(4) + flags(1) + block max size (1).
  137. n := 6
  138. // Optional items.
  139. if z.Header.Size > 0 {
  140. binary.LittleEndian.PutUint64(buf[n:], z.Header.Size)
  141. n += 8
  142. }
  143. // The header checksum includes the flags, block max size and optional Size.
  144. buf[n] = byte(xxh32.ChecksumZero(buf[4:n]) >> 8 & 0xFF)
  145. z.checksum.Reset()
  146. // Header ready, write it out.
  147. if _, err := z.dst.Write(buf[0 : n+1]); err != nil {
  148. return err
  149. }
  150. z.Header.done = true
  151. if debugFlag {
  152. debug("wrote header %v", z.Header)
  153. }
  154. return nil
  155. }
  156. // Write compresses data from the supplied buffer into the underlying io.Writer.
  157. // Write does not return until the data has been written.
  158. func (z *Writer) Write(buf []byte) (int, error) {
  159. if !z.Header.done {
  160. if err := z.writeHeader(); err != nil {
  161. return 0, err
  162. }
  163. }
  164. if debugFlag {
  165. debug("input buffer len=%d index=%d", len(buf), z.idx)
  166. }
  167. zn := len(z.data)
  168. var n int
  169. for len(buf) > 0 {
  170. if z.idx == 0 && len(buf) >= zn {
  171. // Avoid a copy as there is enough data for a block.
  172. if err := z.compressBlock(buf[:zn]); err != nil {
  173. return n, err
  174. }
  175. n += zn
  176. buf = buf[zn:]
  177. continue
  178. }
  179. // Accumulate the data to be compressed.
  180. m := copy(z.data[z.idx:], buf)
  181. n += m
  182. z.idx += m
  183. buf = buf[m:]
  184. if debugFlag {
  185. debug("%d bytes copied to buf, current index %d", n, z.idx)
  186. }
  187. if z.idx < len(z.data) {
  188. // Buffer not filled.
  189. if debugFlag {
  190. debug("need more data for compression")
  191. }
  192. return n, nil
  193. }
  194. // Buffer full.
  195. if err := z.compressBlock(z.data); err != nil {
  196. return n, err
  197. }
  198. z.idx = 0
  199. }
  200. return n, nil
  201. }
  202. // compressBlock compresses a block.
  203. func (z *Writer) compressBlock(data []byte) error {
  204. if !z.NoChecksum {
  205. _, _ = z.checksum.Write(data)
  206. }
  207. if z.c != nil {
  208. c := make(chan zResult)
  209. z.c <- c // Send now to guarantee order
  210. go writerCompressBlock(c, z.Header, data)
  211. return nil
  212. }
  213. zdata := z.data[z.Header.BlockMaxSize:cap(z.data)]
  214. // The compressed block size cannot exceed the input's.
  215. var zn int
  216. if level := z.Header.CompressionLevel; level != 0 {
  217. zn, _ = CompressBlockHC(data, zdata, level)
  218. } else {
  219. zn, _ = CompressBlock(data, zdata, z.hashtable[:])
  220. }
  221. var bLen uint32
  222. if debugFlag {
  223. debug("block compression %d => %d", len(data), zn)
  224. }
  225. if zn > 0 && zn < len(data) {
  226. // Compressible and compressed size smaller than uncompressed: ok!
  227. bLen = uint32(zn)
  228. zdata = zdata[:zn]
  229. } else {
  230. // Uncompressed block.
  231. bLen = uint32(len(data)) | compressedBlockFlag
  232. zdata = data
  233. }
  234. if debugFlag {
  235. debug("block compression to be written len=%d data len=%d", bLen, len(zdata))
  236. }
  237. // Write the block.
  238. if err := z.writeUint32(bLen); err != nil {
  239. return err
  240. }
  241. written, err := z.dst.Write(zdata)
  242. if err != nil {
  243. return err
  244. }
  245. if h := z.OnBlockDone; h != nil {
  246. h(written)
  247. }
  248. if !z.BlockChecksum {
  249. if debugFlag {
  250. debug("current frame checksum %x", z.checksum.Sum32())
  251. }
  252. return nil
  253. }
  254. checksum := xxh32.ChecksumZero(zdata)
  255. if debugFlag {
  256. debug("block checksum %x", checksum)
  257. defer func() { debug("current frame checksum %x", z.checksum.Sum32()) }()
  258. }
  259. return z.writeUint32(checksum)
  260. }
  261. // Flush flushes any pending compressed data to the underlying writer.
  262. // Flush does not return until the data has been written.
  263. // If the underlying writer returns an error, Flush returns that error.
  264. func (z *Writer) Flush() error {
  265. if debugFlag {
  266. debug("flush with index %d", z.idx)
  267. }
  268. if z.idx == 0 {
  269. return nil
  270. }
  271. data := z.data[:z.idx]
  272. z.idx = 0
  273. if z.c == nil {
  274. return z.compressBlock(data)
  275. }
  276. if !z.NoChecksum {
  277. _, _ = z.checksum.Write(data)
  278. }
  279. c := make(chan zResult)
  280. z.c <- c
  281. writerCompressBlock(c, z.Header, data)
  282. return nil
  283. }
  284. func (z *Writer) close() error {
  285. if z.c == nil {
  286. return nil
  287. }
  288. // Send a sentinel block (no data to compress) to terminate the writer main goroutine.
  289. c := make(chan zResult)
  290. z.c <- c
  291. c <- zResult{}
  292. // Wait for the main goroutine to complete.
  293. <-c
  294. // At this point the main goroutine has shut down or is about to return.
  295. z.c = nil
  296. return z.err
  297. }
  298. // Close closes the Writer, flushing any unwritten data to the underlying io.Writer, but does not close the underlying io.Writer.
  299. func (z *Writer) Close() error {
  300. if !z.Header.done {
  301. if err := z.writeHeader(); err != nil {
  302. return err
  303. }
  304. }
  305. if err := z.Flush(); err != nil {
  306. return err
  307. }
  308. if err := z.close(); err != nil {
  309. return err
  310. }
  311. z.freeBuffers()
  312. if debugFlag {
  313. debug("writing last empty block")
  314. }
  315. if err := z.writeUint32(0); err != nil {
  316. return err
  317. }
  318. if z.NoChecksum {
  319. return nil
  320. }
  321. checksum := z.checksum.Sum32()
  322. if debugFlag {
  323. debug("stream checksum %x", checksum)
  324. }
  325. return z.writeUint32(checksum)
  326. }
  327. // Reset clears the state of the Writer z such that it is equivalent to its
  328. // initial state from NewWriter, but instead writing to w.
  329. // No access to the underlying io.Writer is performed.
  330. func (z *Writer) Reset(w io.Writer) {
  331. n := cap(z.c)
  332. _ = z.close()
  333. z.freeBuffers()
  334. z.Header.Reset()
  335. z.dst = w
  336. z.checksum.Reset()
  337. z.idx = 0
  338. z.err = nil
  339. // reset hashtable to ensure deterministic output.
  340. for i := range z.hashtable {
  341. z.hashtable[i] = 0
  342. }
  343. z.WithConcurrency(n)
  344. }
  345. // writeUint32 writes a uint32 to the underlying writer.
  346. func (z *Writer) writeUint32(x uint32) error {
  347. buf := z.buf[:4]
  348. binary.LittleEndian.PutUint32(buf, x)
  349. _, err := z.dst.Write(buf)
  350. return err
  351. }
  352. // writerCompressBlock compresses data into a pooled buffer and writes its result
  353. // out to the input channel.
  354. func writerCompressBlock(c chan zResult, header Header, data []byte) {
  355. zdata := getBuffer(header.BlockMaxSize)
  356. // The compressed block size cannot exceed the input's.
  357. var zn int
  358. if level := header.CompressionLevel; level != 0 {
  359. zn, _ = CompressBlockHC(data, zdata, level)
  360. } else {
  361. var hashTable [winSize]int
  362. zn, _ = CompressBlock(data, zdata, hashTable[:])
  363. }
  364. var res zResult
  365. if zn > 0 && zn < len(data) {
  366. res.size = uint32(zn)
  367. res.data = zdata[:zn]
  368. } else {
  369. res.size = uint32(len(data)) | compressedBlockFlag
  370. res.data = data
  371. }
  372. if header.BlockChecksum {
  373. res.checksum = xxh32.ChecksumZero(res.data)
  374. }
  375. c <- res
  376. }