frame.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. // Package lz4stream provides the types that support reading and writing LZ4 data streams.
  2. package lz4stream
  3. import (
  4. "encoding/binary"
  5. "fmt"
  6. "io"
  7. "io/ioutil"
  8. "github.com/pierrec/lz4/internal/lz4block"
  9. "github.com/pierrec/lz4/internal/lz4errors"
  10. "github.com/pierrec/lz4/internal/xxh32"
  11. )
  12. //go:generate go run gen.go
  13. const (
  14. frameMagic uint32 = 0x184D2204
  15. frameSkipMagic uint32 = 0x184D2A50
  16. )
  17. func NewFrame() *Frame {
  18. return &Frame{}
  19. }
  20. type Frame struct {
  21. buf [15]byte // frame descriptor needs at most 4(magic)+4+8+1=11 bytes
  22. Magic uint32
  23. Descriptor FrameDescriptor
  24. Blocks Blocks
  25. Checksum uint32
  26. checksum xxh32.XXHZero
  27. }
  28. // Reset allows reusing the Frame.
  29. // The Descriptor configuration is not modified.
  30. func (f *Frame) Reset(num int) {
  31. f.Magic = 0
  32. f.Descriptor.Checksum = 0
  33. f.Descriptor.ContentSize = 0
  34. _ = f.Blocks.closeW(f, num)
  35. f.Checksum = 0
  36. }
  37. func (f *Frame) InitW(dst io.Writer, num int) {
  38. f.Magic = frameMagic
  39. f.Descriptor.initW()
  40. f.Blocks.initW(f, dst, num)
  41. f.checksum.Reset()
  42. }
  43. func (f *Frame) CloseW(dst io.Writer, num int) error {
  44. if err := f.Blocks.closeW(f, num); err != nil {
  45. return err
  46. }
  47. buf := f.buf[:0]
  48. // End mark (data block size of uint32(0)).
  49. buf = append(buf, 0, 0, 0, 0)
  50. if f.Descriptor.Flags.ContentChecksum() {
  51. buf = f.checksum.Sum(buf)
  52. }
  53. _, err := dst.Write(buf)
  54. return err
  55. }
  56. func (f *Frame) InitR(src io.Reader) error {
  57. if f.Magic > 0 {
  58. // Header already read.
  59. return nil
  60. }
  61. newFrame:
  62. if err := readUint32(src, f.buf[:], &f.Magic); err != nil {
  63. return err
  64. }
  65. switch m := f.Magic; {
  66. case m == frameMagic:
  67. // All 16 values of frameSkipMagic are valid.
  68. case m>>8 == frameSkipMagic>>8:
  69. var skip uint32
  70. if err := binary.Read(src, binary.LittleEndian, &skip); err != nil {
  71. return err
  72. }
  73. if _, err := io.CopyN(ioutil.Discard, src, int64(skip)); err != nil {
  74. return err
  75. }
  76. goto newFrame
  77. default:
  78. return lz4errors.ErrInvalidFrame
  79. }
  80. if err := f.Descriptor.initR(f, src); err != nil {
  81. return err
  82. }
  83. f.Blocks.initR(f)
  84. f.checksum.Reset()
  85. return nil
  86. }
  87. func (f *Frame) CloseR(src io.Reader) error {
  88. if !f.Descriptor.Flags.ContentChecksum() {
  89. return nil
  90. }
  91. if err := readUint32(src, f.buf[:], &f.Checksum); err != nil {
  92. return err
  93. }
  94. if c := f.checksum.Sum32(); c != f.Checksum {
  95. return fmt.Errorf("%w: got %x; expected %x", lz4errors.ErrInvalidFrameChecksum, c, f.Checksum)
  96. }
  97. return nil
  98. }
  99. type FrameDescriptor struct {
  100. Flags DescriptorFlags
  101. ContentSize uint64
  102. Checksum uint8
  103. }
  104. func (fd *FrameDescriptor) initW() {
  105. fd.Flags.VersionSet(1)
  106. fd.Flags.BlockIndependenceSet(true)
  107. }
  108. func (fd *FrameDescriptor) Write(f *Frame, dst io.Writer) error {
  109. if fd.Checksum > 0 {
  110. // Header already written.
  111. return nil
  112. }
  113. buf := f.buf[:4+2]
  114. // Write the magic number here even though it belongs to the Frame.
  115. binary.LittleEndian.PutUint32(buf, f.Magic)
  116. binary.LittleEndian.PutUint16(buf[4:], uint16(fd.Flags))
  117. if fd.Flags.Size() {
  118. buf = buf[:4+2+8]
  119. binary.LittleEndian.PutUint64(buf[4+2:], fd.ContentSize)
  120. }
  121. fd.Checksum = descriptorChecksum(buf[4:])
  122. buf = append(buf, fd.Checksum)
  123. _, err := dst.Write(buf)
  124. return err
  125. }
  126. func (fd *FrameDescriptor) initR(f *Frame, src io.Reader) error {
  127. // Read the flags and the checksum, hoping that there is not content size.
  128. buf := f.buf[:3]
  129. if _, err := io.ReadFull(src, buf); err != nil {
  130. return err
  131. }
  132. descr := binary.LittleEndian.Uint16(buf)
  133. fd.Flags = DescriptorFlags(descr)
  134. if fd.Flags.Size() {
  135. // Append the 8 missing bytes.
  136. buf = buf[:3+8]
  137. if _, err := io.ReadFull(src, buf[3:]); err != nil {
  138. return err
  139. }
  140. fd.ContentSize = binary.LittleEndian.Uint64(buf[2:])
  141. }
  142. fd.Checksum = buf[len(buf)-1] // the checksum is the last byte
  143. buf = buf[:len(buf)-1] // all descriptor fields except checksum
  144. if c := descriptorChecksum(buf); fd.Checksum != c {
  145. return fmt.Errorf("%w: got %x; expected %x", lz4errors.ErrInvalidHeaderChecksum, c, fd.Checksum)
  146. }
  147. // Validate the elements that can be.
  148. if idx := fd.Flags.BlockSizeIndex(); !idx.IsValid() {
  149. return lz4errors.ErrOptionInvalidBlockSize
  150. }
  151. return nil
  152. }
  153. func descriptorChecksum(buf []byte) byte {
  154. return byte(xxh32.ChecksumZero(buf) >> 8)
  155. }
  156. type Blocks struct {
  157. Block *FrameDataBlock
  158. Blocks chan chan *FrameDataBlock
  159. err error
  160. }
  161. func (b *Blocks) initW(f *Frame, dst io.Writer, num int) {
  162. size := f.Descriptor.Flags.BlockSizeIndex()
  163. if num == 1 {
  164. b.Blocks = nil
  165. b.Block = NewFrameDataBlock(size)
  166. return
  167. }
  168. b.Block = nil
  169. if cap(b.Blocks) != num {
  170. b.Blocks = make(chan chan *FrameDataBlock, num)
  171. }
  172. // goroutine managing concurrent block compression goroutines.
  173. go func() {
  174. // Process next block compression item.
  175. for c := range b.Blocks {
  176. // Read the next compressed block result.
  177. // Waiting here ensures that the blocks are output in the order they were sent.
  178. // The incoming channel is always closed as it indicates to the caller that
  179. // the block has been processed.
  180. block := <-c
  181. if block == nil {
  182. // Notify the block compression routine that we are done with its result.
  183. // This is used when a sentinel block is sent to terminate the compression.
  184. close(c)
  185. return
  186. }
  187. // Do not attempt to write the block upon any previous failure.
  188. if b.err == nil {
  189. // Write the block.
  190. if err := block.Write(f, dst); err != nil && b.err == nil {
  191. // Keep the first error.
  192. b.err = err
  193. // All pending compression goroutines need to shut down, so we need to keep going.
  194. }
  195. }
  196. close(c)
  197. }
  198. }()
  199. }
  200. func (b *Blocks) closeW(f *Frame, num int) error {
  201. if num == 1 {
  202. if b.Block == nil {
  203. // Not initialized yet.
  204. return nil
  205. }
  206. b.Block.CloseW(f)
  207. return nil
  208. }
  209. if b.Blocks == nil {
  210. // Not initialized yet.
  211. return nil
  212. }
  213. c := make(chan *FrameDataBlock)
  214. b.Blocks <- c
  215. c <- nil
  216. <-c
  217. err := b.err
  218. b.err = nil
  219. return err
  220. }
  221. func (b *Blocks) initR(f *Frame) {
  222. size := f.Descriptor.Flags.BlockSizeIndex()
  223. b.Block = NewFrameDataBlock(size)
  224. }
  225. func NewFrameDataBlock(size lz4block.BlockSizeIndex) *FrameDataBlock {
  226. buf := size.Get()
  227. return &FrameDataBlock{Data: buf, data: buf}
  228. }
  229. type FrameDataBlock struct {
  230. Size DataBlockSize
  231. Data []byte // compressed or uncompressed data (.data or .src)
  232. Checksum uint32
  233. data []byte // buffer for compressed data
  234. src []byte // uncompressed data
  235. }
  236. func (b *FrameDataBlock) CloseW(f *Frame) {
  237. if b.data != nil {
  238. // Block was not already closed.
  239. size := f.Descriptor.Flags.BlockSizeIndex()
  240. size.Put(b.data)
  241. b.Data = nil
  242. b.data = nil
  243. b.src = nil
  244. }
  245. }
  246. // Block compression errors are ignored since the buffer is sized appropriately.
  247. func (b *FrameDataBlock) Compress(f *Frame, src []byte, level lz4block.CompressionLevel) *FrameDataBlock {
  248. data := b.data[:len(src)] // trigger the incompressible flag in CompressBlock
  249. var n int
  250. switch level {
  251. case lz4block.Fast:
  252. n, _ = lz4block.CompressBlock(src, data, nil)
  253. default:
  254. n, _ = lz4block.CompressBlockHC(src, data, level, nil, nil)
  255. }
  256. if n == 0 {
  257. b.Size.UncompressedSet(true)
  258. b.Data = src
  259. } else {
  260. b.Size.UncompressedSet(false)
  261. b.Data = data[:n]
  262. }
  263. b.Size.sizeSet(len(b.Data))
  264. b.src = src // keep track of the source for content checksum
  265. if f.Descriptor.Flags.BlockChecksum() {
  266. b.Checksum = xxh32.ChecksumZero(src)
  267. }
  268. return b
  269. }
  270. func (b *FrameDataBlock) Write(f *Frame, dst io.Writer) error {
  271. if f.Descriptor.Flags.ContentChecksum() {
  272. _, _ = f.checksum.Write(b.src)
  273. }
  274. buf := f.buf[:]
  275. binary.LittleEndian.PutUint32(buf, uint32(b.Size))
  276. if _, err := dst.Write(buf[:4]); err != nil {
  277. return err
  278. }
  279. if _, err := dst.Write(b.Data); err != nil {
  280. return err
  281. }
  282. if b.Checksum == 0 {
  283. return nil
  284. }
  285. binary.LittleEndian.PutUint32(buf, b.Checksum)
  286. _, err := dst.Write(buf[:4])
  287. return err
  288. }
  289. func (b *FrameDataBlock) Uncompress(f *Frame, src io.Reader, dst []byte) (int, error) {
  290. buf := f.buf[:]
  291. var x uint32
  292. if err := readUint32(src, buf, &x); err != nil {
  293. return 0, err
  294. }
  295. b.Size = DataBlockSize(x)
  296. if b.Size == 0 {
  297. // End of frame reached.
  298. return 0, io.EOF
  299. }
  300. isCompressed := !b.Size.Uncompressed()
  301. size := b.Size.size()
  302. var data []byte
  303. if isCompressed {
  304. // Data is first copied into b.Data and then it will get uncompressed into dst.
  305. data = b.Data
  306. } else {
  307. // Data is directly copied into dst as it is not compressed.
  308. data = dst
  309. }
  310. data = data[:size]
  311. if _, err := io.ReadFull(src, data); err != nil {
  312. return 0, err
  313. }
  314. if isCompressed {
  315. n, err := lz4block.UncompressBlock(data, dst)
  316. if err != nil {
  317. return 0, err
  318. }
  319. data = dst[:n]
  320. }
  321. if f.Descriptor.Flags.BlockChecksum() {
  322. if err := readUint32(src, buf, &b.Checksum); err != nil {
  323. return 0, err
  324. }
  325. if c := xxh32.ChecksumZero(data); c != b.Checksum {
  326. return 0, fmt.Errorf("%w: got %x; expected %x", lz4errors.ErrInvalidBlockChecksum, c, b.Checksum)
  327. }
  328. }
  329. if f.Descriptor.Flags.ContentChecksum() {
  330. _, _ = f.checksum.Write(data)
  331. }
  332. return len(data), nil
  333. }
  334. func readUint32(r io.Reader, buf []byte, x *uint32) error {
  335. if _, err := io.ReadFull(r, buf[:4]); err != nil {
  336. return err
  337. }
  338. *x = binary.LittleEndian.Uint32(buf)
  339. return nil
  340. }