blockdec.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  1. // Copyright 2019+ Klaus Post. All rights reserved.
  2. // License information can be found in the LICENSE file.
  3. // Based on work by Yann Collet, released under BSD License.
  4. package zstd
  5. import (
  6. "errors"
  7. "fmt"
  8. "hash/crc32"
  9. "io"
  10. "sync"
  11. "github.com/klauspost/compress/huff0"
  12. "github.com/klauspost/compress/zstd/internal/xxhash"
  13. )
  14. type blockType uint8
  15. //go:generate stringer -type=blockType,literalsBlockType,seqCompMode,tableIndex
  16. const (
  17. blockTypeRaw blockType = iota
  18. blockTypeRLE
  19. blockTypeCompressed
  20. blockTypeReserved
  21. )
  22. type literalsBlockType uint8
  23. const (
  24. literalsBlockRaw literalsBlockType = iota
  25. literalsBlockRLE
  26. literalsBlockCompressed
  27. literalsBlockTreeless
  28. )
  29. const (
  30. // maxCompressedBlockSize is the biggest allowed compressed block size (128KB)
  31. maxCompressedBlockSize = 128 << 10
  32. compressedBlockOverAlloc = 16
  33. maxCompressedBlockSizeAlloc = 128<<10 + compressedBlockOverAlloc
  34. // Maximum possible block size (all Raw+Uncompressed).
  35. maxBlockSize = (1 << 21) - 1
  36. maxMatchLen = 131074
  37. maxSequences = 0x7f00 + 0xffff
  38. // We support slightly less than the reference decoder to be able to
  39. // use ints on 32 bit archs.
  40. maxOffsetBits = 30
  41. )
  42. var (
  43. huffDecoderPool = sync.Pool{New: func() interface{} {
  44. return &huff0.Scratch{}
  45. }}
  46. fseDecoderPool = sync.Pool{New: func() interface{} {
  47. return &fseDecoder{}
  48. }}
  49. )
  50. type blockDec struct {
  51. // Raw source data of the block.
  52. data []byte
  53. dataStorage []byte
  54. // Destination of the decoded data.
  55. dst []byte
  56. // Buffer for literals data.
  57. literalBuf []byte
  58. // Window size of the block.
  59. WindowSize uint64
  60. err error
  61. // Check against this crc, if hasCRC is true.
  62. checkCRC uint32
  63. hasCRC bool
  64. // Frame to use for singlethreaded decoding.
  65. // Should not be used by the decoder itself since parent may be another frame.
  66. localFrame *frameDec
  67. sequence []seqVals
  68. async struct {
  69. newHist *history
  70. literals []byte
  71. seqData []byte
  72. seqSize int // Size of uncompressed sequences
  73. fcs uint64
  74. }
  75. // Block is RLE, this is the size.
  76. RLESize uint32
  77. Type blockType
  78. // Is this the last block of a frame?
  79. Last bool
  80. // Use less memory
  81. lowMem bool
  82. }
  83. func (b *blockDec) String() string {
  84. if b == nil {
  85. return "<nil>"
  86. }
  87. return fmt.Sprintf("Steam Size: %d, Type: %v, Last: %t, Window: %d", len(b.data), b.Type, b.Last, b.WindowSize)
  88. }
  89. func newBlockDec(lowMem bool) *blockDec {
  90. b := blockDec{
  91. lowMem: lowMem,
  92. }
  93. return &b
  94. }
  95. // reset will reset the block.
  96. // Input must be a start of a block and will be at the end of the block when returned.
  97. func (b *blockDec) reset(br byteBuffer, windowSize uint64) error {
  98. b.WindowSize = windowSize
  99. tmp, err := br.readSmall(3)
  100. if err != nil {
  101. println("Reading block header:", err)
  102. return err
  103. }
  104. bh := uint32(tmp[0]) | (uint32(tmp[1]) << 8) | (uint32(tmp[2]) << 16)
  105. b.Last = bh&1 != 0
  106. b.Type = blockType((bh >> 1) & 3)
  107. // find size.
  108. cSize := int(bh >> 3)
  109. maxSize := maxCompressedBlockSizeAlloc
  110. switch b.Type {
  111. case blockTypeReserved:
  112. return ErrReservedBlockType
  113. case blockTypeRLE:
  114. if cSize > maxCompressedBlockSize || cSize > int(b.WindowSize) {
  115. if debugDecoder {
  116. printf("rle block too big: csize:%d block: %+v\n", uint64(cSize), b)
  117. }
  118. return ErrWindowSizeExceeded
  119. }
  120. b.RLESize = uint32(cSize)
  121. if b.lowMem {
  122. maxSize = cSize
  123. }
  124. cSize = 1
  125. case blockTypeCompressed:
  126. if debugDecoder {
  127. println("Data size on stream:", cSize)
  128. }
  129. b.RLESize = 0
  130. maxSize = maxCompressedBlockSizeAlloc
  131. if windowSize < maxCompressedBlockSize && b.lowMem {
  132. maxSize = int(windowSize) + compressedBlockOverAlloc
  133. }
  134. if cSize > maxCompressedBlockSize || uint64(cSize) > b.WindowSize {
  135. if debugDecoder {
  136. printf("compressed block too big: csize:%d block: %+v\n", uint64(cSize), b)
  137. }
  138. return ErrCompressedSizeTooBig
  139. }
  140. // Empty compressed blocks must at least be 2 bytes
  141. // for Literals_Block_Type and one for Sequences_Section_Header.
  142. if cSize < 2 {
  143. return ErrBlockTooSmall
  144. }
  145. case blockTypeRaw:
  146. if cSize > maxCompressedBlockSize || cSize > int(b.WindowSize) {
  147. if debugDecoder {
  148. printf("rle block too big: csize:%d block: %+v\n", uint64(cSize), b)
  149. }
  150. return ErrWindowSizeExceeded
  151. }
  152. b.RLESize = 0
  153. // We do not need a destination for raw blocks.
  154. maxSize = -1
  155. default:
  156. panic("Invalid block type")
  157. }
  158. // Read block data.
  159. if _, ok := br.(*byteBuf); !ok && cap(b.dataStorage) < cSize {
  160. // byteBuf doesn't need a destination buffer.
  161. if b.lowMem || cSize > maxCompressedBlockSize {
  162. b.dataStorage = make([]byte, 0, cSize+compressedBlockOverAlloc)
  163. } else {
  164. b.dataStorage = make([]byte, 0, maxCompressedBlockSizeAlloc)
  165. }
  166. }
  167. b.data, err = br.readBig(cSize, b.dataStorage)
  168. if err != nil {
  169. if debugDecoder {
  170. println("Reading block:", err, "(", cSize, ")", len(b.data))
  171. printf("%T", br)
  172. }
  173. return err
  174. }
  175. if cap(b.dst) <= maxSize {
  176. b.dst = make([]byte, 0, maxSize+1)
  177. }
  178. return nil
  179. }
  180. // sendEOF will make the decoder send EOF on this frame.
  181. func (b *blockDec) sendErr(err error) {
  182. b.Last = true
  183. b.Type = blockTypeReserved
  184. b.err = err
  185. }
  186. // Close will release resources.
  187. // Closed blockDec cannot be reset.
  188. func (b *blockDec) Close() {
  189. }
  190. // decodeBuf
  191. func (b *blockDec) decodeBuf(hist *history) error {
  192. switch b.Type {
  193. case blockTypeRLE:
  194. if cap(b.dst) < int(b.RLESize) {
  195. if b.lowMem {
  196. b.dst = make([]byte, b.RLESize)
  197. } else {
  198. b.dst = make([]byte, maxCompressedBlockSize)
  199. }
  200. }
  201. b.dst = b.dst[:b.RLESize]
  202. v := b.data[0]
  203. for i := range b.dst {
  204. b.dst[i] = v
  205. }
  206. hist.appendKeep(b.dst)
  207. return nil
  208. case blockTypeRaw:
  209. hist.appendKeep(b.data)
  210. return nil
  211. case blockTypeCompressed:
  212. saved := b.dst
  213. // Append directly to history
  214. if hist.ignoreBuffer == 0 {
  215. b.dst = hist.b
  216. hist.b = nil
  217. } else {
  218. b.dst = b.dst[:0]
  219. }
  220. err := b.decodeCompressed(hist)
  221. if debugDecoder {
  222. println("Decompressed to total", len(b.dst), "bytes, hash:", xxhash.Sum64(b.dst), "error:", err)
  223. }
  224. if hist.ignoreBuffer == 0 {
  225. hist.b = b.dst
  226. b.dst = saved
  227. } else {
  228. hist.appendKeep(b.dst)
  229. }
  230. return err
  231. case blockTypeReserved:
  232. // Used for returning errors.
  233. return b.err
  234. default:
  235. panic("Invalid block type")
  236. }
  237. }
  238. func (b *blockDec) decodeLiterals(in []byte, hist *history) (remain []byte, err error) {
  239. // There must be at least one byte for Literals_Block_Type and one for Sequences_Section_Header
  240. if len(in) < 2 {
  241. return in, ErrBlockTooSmall
  242. }
  243. litType := literalsBlockType(in[0] & 3)
  244. var litRegenSize int
  245. var litCompSize int
  246. sizeFormat := (in[0] >> 2) & 3
  247. var fourStreams bool
  248. var literals []byte
  249. switch litType {
  250. case literalsBlockRaw, literalsBlockRLE:
  251. switch sizeFormat {
  252. case 0, 2:
  253. // Regenerated_Size uses 5 bits (0-31). Literals_Section_Header uses 1 byte.
  254. litRegenSize = int(in[0] >> 3)
  255. in = in[1:]
  256. case 1:
  257. // Regenerated_Size uses 12 bits (0-4095). Literals_Section_Header uses 2 bytes.
  258. litRegenSize = int(in[0]>>4) + (int(in[1]) << 4)
  259. in = in[2:]
  260. case 3:
  261. // Regenerated_Size uses 20 bits (0-1048575). Literals_Section_Header uses 3 bytes.
  262. if len(in) < 3 {
  263. println("too small: litType:", litType, " sizeFormat", sizeFormat, len(in))
  264. return in, ErrBlockTooSmall
  265. }
  266. litRegenSize = int(in[0]>>4) + (int(in[1]) << 4) + (int(in[2]) << 12)
  267. in = in[3:]
  268. }
  269. case literalsBlockCompressed, literalsBlockTreeless:
  270. switch sizeFormat {
  271. case 0, 1:
  272. // Both Regenerated_Size and Compressed_Size use 10 bits (0-1023).
  273. if len(in) < 3 {
  274. println("too small: litType:", litType, " sizeFormat", sizeFormat, len(in))
  275. return in, ErrBlockTooSmall
  276. }
  277. n := uint64(in[0]>>4) + (uint64(in[1]) << 4) + (uint64(in[2]) << 12)
  278. litRegenSize = int(n & 1023)
  279. litCompSize = int(n >> 10)
  280. fourStreams = sizeFormat == 1
  281. in = in[3:]
  282. case 2:
  283. fourStreams = true
  284. if len(in) < 4 {
  285. println("too small: litType:", litType, " sizeFormat", sizeFormat, len(in))
  286. return in, ErrBlockTooSmall
  287. }
  288. n := uint64(in[0]>>4) + (uint64(in[1]) << 4) + (uint64(in[2]) << 12) + (uint64(in[3]) << 20)
  289. litRegenSize = int(n & 16383)
  290. litCompSize = int(n >> 14)
  291. in = in[4:]
  292. case 3:
  293. fourStreams = true
  294. if len(in) < 5 {
  295. println("too small: litType:", litType, " sizeFormat", sizeFormat, len(in))
  296. return in, ErrBlockTooSmall
  297. }
  298. n := uint64(in[0]>>4) + (uint64(in[1]) << 4) + (uint64(in[2]) << 12) + (uint64(in[3]) << 20) + (uint64(in[4]) << 28)
  299. litRegenSize = int(n & 262143)
  300. litCompSize = int(n >> 18)
  301. in = in[5:]
  302. }
  303. }
  304. if debugDecoder {
  305. println("literals type:", litType, "litRegenSize:", litRegenSize, "litCompSize:", litCompSize, "sizeFormat:", sizeFormat, "4X:", fourStreams)
  306. }
  307. if litRegenSize > int(b.WindowSize) || litRegenSize > maxCompressedBlockSize {
  308. return in, ErrWindowSizeExceeded
  309. }
  310. switch litType {
  311. case literalsBlockRaw:
  312. if len(in) < litRegenSize {
  313. println("too small: litType:", litType, " sizeFormat", sizeFormat, "remain:", len(in), "want:", litRegenSize)
  314. return in, ErrBlockTooSmall
  315. }
  316. literals = in[:litRegenSize]
  317. in = in[litRegenSize:]
  318. //printf("Found %d uncompressed literals\n", litRegenSize)
  319. case literalsBlockRLE:
  320. if len(in) < 1 {
  321. println("too small: litType:", litType, " sizeFormat", sizeFormat, "remain:", len(in), "want:", 1)
  322. return in, ErrBlockTooSmall
  323. }
  324. if cap(b.literalBuf) < litRegenSize {
  325. if b.lowMem {
  326. b.literalBuf = make([]byte, litRegenSize, litRegenSize+compressedBlockOverAlloc)
  327. } else {
  328. b.literalBuf = make([]byte, litRegenSize, maxCompressedBlockSize+compressedBlockOverAlloc)
  329. }
  330. }
  331. literals = b.literalBuf[:litRegenSize]
  332. v := in[0]
  333. for i := range literals {
  334. literals[i] = v
  335. }
  336. in = in[1:]
  337. if debugDecoder {
  338. printf("Found %d RLE compressed literals\n", litRegenSize)
  339. }
  340. case literalsBlockTreeless:
  341. if len(in) < litCompSize {
  342. println("too small: litType:", litType, " sizeFormat", sizeFormat, "remain:", len(in), "want:", litCompSize)
  343. return in, ErrBlockTooSmall
  344. }
  345. // Store compressed literals, so we defer decoding until we get history.
  346. literals = in[:litCompSize]
  347. in = in[litCompSize:]
  348. if debugDecoder {
  349. printf("Found %d compressed literals\n", litCompSize)
  350. }
  351. huff := hist.huffTree
  352. if huff == nil {
  353. return in, errors.New("literal block was treeless, but no history was defined")
  354. }
  355. // Ensure we have space to store it.
  356. if cap(b.literalBuf) < litRegenSize {
  357. if b.lowMem {
  358. b.literalBuf = make([]byte, 0, litRegenSize+compressedBlockOverAlloc)
  359. } else {
  360. b.literalBuf = make([]byte, 0, maxCompressedBlockSize+compressedBlockOverAlloc)
  361. }
  362. }
  363. var err error
  364. // Use our out buffer.
  365. huff.MaxDecodedSize = litRegenSize
  366. if fourStreams {
  367. literals, err = huff.Decoder().Decompress4X(b.literalBuf[:0:litRegenSize], literals)
  368. } else {
  369. literals, err = huff.Decoder().Decompress1X(b.literalBuf[:0:litRegenSize], literals)
  370. }
  371. // Make sure we don't leak our literals buffer
  372. if err != nil {
  373. println("decompressing literals:", err)
  374. return in, err
  375. }
  376. if len(literals) != litRegenSize {
  377. return in, fmt.Errorf("literal output size mismatch want %d, got %d", litRegenSize, len(literals))
  378. }
  379. case literalsBlockCompressed:
  380. if len(in) < litCompSize {
  381. println("too small: litType:", litType, " sizeFormat", sizeFormat, "remain:", len(in), "want:", litCompSize)
  382. return in, ErrBlockTooSmall
  383. }
  384. literals = in[:litCompSize]
  385. in = in[litCompSize:]
  386. // Ensure we have space to store it.
  387. if cap(b.literalBuf) < litRegenSize {
  388. if b.lowMem {
  389. b.literalBuf = make([]byte, 0, litRegenSize+compressedBlockOverAlloc)
  390. } else {
  391. b.literalBuf = make([]byte, 0, maxCompressedBlockSize+compressedBlockOverAlloc)
  392. }
  393. }
  394. huff := hist.huffTree
  395. if huff == nil || (hist.dict != nil && huff == hist.dict.litEnc) {
  396. huff = huffDecoderPool.Get().(*huff0.Scratch)
  397. if huff == nil {
  398. huff = &huff0.Scratch{}
  399. }
  400. }
  401. var err error
  402. if debugDecoder {
  403. println("huff table input:", len(literals), "CRC:", crc32.ChecksumIEEE(literals))
  404. }
  405. huff, literals, err = huff0.ReadTable(literals, huff)
  406. if err != nil {
  407. println("reading huffman table:", err)
  408. return in, err
  409. }
  410. hist.huffTree = huff
  411. huff.MaxDecodedSize = litRegenSize
  412. // Use our out buffer.
  413. if fourStreams {
  414. literals, err = huff.Decoder().Decompress4X(b.literalBuf[:0:litRegenSize], literals)
  415. } else {
  416. literals, err = huff.Decoder().Decompress1X(b.literalBuf[:0:litRegenSize], literals)
  417. }
  418. if err != nil {
  419. println("decoding compressed literals:", err)
  420. return in, err
  421. }
  422. // Make sure we don't leak our literals buffer
  423. if len(literals) != litRegenSize {
  424. return in, fmt.Errorf("literal output size mismatch want %d, got %d", litRegenSize, len(literals))
  425. }
  426. // Re-cap to get extra size.
  427. literals = b.literalBuf[:len(literals)]
  428. if debugDecoder {
  429. printf("Decompressed %d literals into %d bytes\n", litCompSize, litRegenSize)
  430. }
  431. }
  432. hist.decoders.literals = literals
  433. return in, nil
  434. }
  435. // decodeCompressed will start decompressing a block.
  436. func (b *blockDec) decodeCompressed(hist *history) error {
  437. in := b.data
  438. in, err := b.decodeLiterals(in, hist)
  439. if err != nil {
  440. return err
  441. }
  442. err = b.prepareSequences(in, hist)
  443. if err != nil {
  444. return err
  445. }
  446. if hist.decoders.nSeqs == 0 {
  447. b.dst = append(b.dst, hist.decoders.literals...)
  448. return nil
  449. }
  450. before := len(hist.decoders.out)
  451. err = hist.decoders.decodeSync(hist.b[hist.ignoreBuffer:])
  452. if err != nil {
  453. return err
  454. }
  455. if hist.decoders.maxSyncLen > 0 {
  456. hist.decoders.maxSyncLen += uint64(before)
  457. hist.decoders.maxSyncLen -= uint64(len(hist.decoders.out))
  458. }
  459. b.dst = hist.decoders.out
  460. hist.recentOffsets = hist.decoders.prevOffset
  461. return nil
  462. }
  463. func (b *blockDec) prepareSequences(in []byte, hist *history) (err error) {
  464. if debugDecoder {
  465. printf("prepareSequences: %d byte(s) input\n", len(in))
  466. }
  467. // Decode Sequences
  468. // https://github.com/facebook/zstd/blob/dev/doc/zstd_compression_format.md#sequences-section
  469. if len(in) < 1 {
  470. return ErrBlockTooSmall
  471. }
  472. var nSeqs int
  473. seqHeader := in[0]
  474. switch {
  475. case seqHeader < 128:
  476. nSeqs = int(seqHeader)
  477. in = in[1:]
  478. case seqHeader < 255:
  479. if len(in) < 2 {
  480. return ErrBlockTooSmall
  481. }
  482. nSeqs = int(seqHeader-128)<<8 | int(in[1])
  483. in = in[2:]
  484. case seqHeader == 255:
  485. if len(in) < 3 {
  486. return ErrBlockTooSmall
  487. }
  488. nSeqs = 0x7f00 + int(in[1]) + (int(in[2]) << 8)
  489. in = in[3:]
  490. }
  491. if nSeqs == 0 && len(in) != 0 {
  492. // When no sequences, there should not be any more data...
  493. if debugDecoder {
  494. printf("prepareSequences: 0 sequences, but %d byte(s) left on stream\n", len(in))
  495. }
  496. return ErrUnexpectedBlockSize
  497. }
  498. var seqs = &hist.decoders
  499. seqs.nSeqs = nSeqs
  500. if nSeqs > 0 {
  501. if len(in) < 1 {
  502. return ErrBlockTooSmall
  503. }
  504. br := byteReader{b: in, off: 0}
  505. compMode := br.Uint8()
  506. br.advance(1)
  507. if debugDecoder {
  508. printf("Compression modes: 0b%b", compMode)
  509. }
  510. if compMode&3 != 0 {
  511. return errors.New("corrupt block: reserved bits not zero")
  512. }
  513. for i := uint(0); i < 3; i++ {
  514. mode := seqCompMode((compMode >> (6 - i*2)) & 3)
  515. if debugDecoder {
  516. println("Table", tableIndex(i), "is", mode)
  517. }
  518. var seq *sequenceDec
  519. switch tableIndex(i) {
  520. case tableLiteralLengths:
  521. seq = &seqs.litLengths
  522. case tableOffsets:
  523. seq = &seqs.offsets
  524. case tableMatchLengths:
  525. seq = &seqs.matchLengths
  526. default:
  527. panic("unknown table")
  528. }
  529. switch mode {
  530. case compModePredefined:
  531. if seq.fse != nil && !seq.fse.preDefined {
  532. fseDecoderPool.Put(seq.fse)
  533. }
  534. seq.fse = &fsePredef[i]
  535. case compModeRLE:
  536. if br.remain() < 1 {
  537. return ErrBlockTooSmall
  538. }
  539. v := br.Uint8()
  540. br.advance(1)
  541. if seq.fse == nil || seq.fse.preDefined {
  542. seq.fse = fseDecoderPool.Get().(*fseDecoder)
  543. }
  544. symb, err := decSymbolValue(v, symbolTableX[i])
  545. if err != nil {
  546. printf("RLE Transform table (%v) error: %v", tableIndex(i), err)
  547. return err
  548. }
  549. seq.fse.setRLE(symb)
  550. if debugDecoder {
  551. printf("RLE set to 0x%x, code: %v", symb, v)
  552. }
  553. case compModeFSE:
  554. if debugDecoder {
  555. println("Reading table for", tableIndex(i))
  556. }
  557. if seq.fse == nil || seq.fse.preDefined {
  558. seq.fse = fseDecoderPool.Get().(*fseDecoder)
  559. }
  560. err := seq.fse.readNCount(&br, uint16(maxTableSymbol[i]))
  561. if err != nil {
  562. println("Read table error:", err)
  563. return err
  564. }
  565. err = seq.fse.transform(symbolTableX[i])
  566. if err != nil {
  567. println("Transform table error:", err)
  568. return err
  569. }
  570. if debugDecoder {
  571. println("Read table ok", "symbolLen:", seq.fse.symbolLen)
  572. }
  573. case compModeRepeat:
  574. seq.repeat = true
  575. }
  576. if br.overread() {
  577. return io.ErrUnexpectedEOF
  578. }
  579. }
  580. in = br.unread()
  581. }
  582. if debugDecoder {
  583. println("Literals:", len(seqs.literals), "hash:", xxhash.Sum64(seqs.literals), "and", seqs.nSeqs, "sequences.")
  584. }
  585. if nSeqs == 0 {
  586. if len(b.sequence) > 0 {
  587. b.sequence = b.sequence[:0]
  588. }
  589. return nil
  590. }
  591. br := seqs.br
  592. if br == nil {
  593. br = &bitReader{}
  594. }
  595. if err := br.init(in); err != nil {
  596. return err
  597. }
  598. if err := seqs.initialize(br, hist, b.dst); err != nil {
  599. println("initializing sequences:", err)
  600. return err
  601. }
  602. return nil
  603. }
  604. func (b *blockDec) decodeSequences(hist *history) error {
  605. if cap(b.sequence) < hist.decoders.nSeqs {
  606. if b.lowMem {
  607. b.sequence = make([]seqVals, 0, hist.decoders.nSeqs)
  608. } else {
  609. b.sequence = make([]seqVals, 0, 0x7F00+0xffff)
  610. }
  611. }
  612. b.sequence = b.sequence[:hist.decoders.nSeqs]
  613. if hist.decoders.nSeqs == 0 {
  614. hist.decoders.seqSize = len(hist.decoders.literals)
  615. return nil
  616. }
  617. hist.decoders.windowSize = hist.windowSize
  618. hist.decoders.prevOffset = hist.recentOffsets
  619. err := hist.decoders.decode(b.sequence)
  620. hist.recentOffsets = hist.decoders.prevOffset
  621. return err
  622. }
  623. func (b *blockDec) executeSequences(hist *history) error {
  624. hbytes := hist.b
  625. if len(hbytes) > hist.windowSize {
  626. hbytes = hbytes[len(hbytes)-hist.windowSize:]
  627. // We do not need history anymore.
  628. if hist.dict != nil {
  629. hist.dict.content = nil
  630. }
  631. }
  632. hist.decoders.windowSize = hist.windowSize
  633. hist.decoders.out = b.dst[:0]
  634. err := hist.decoders.execute(b.sequence, hbytes)
  635. if err != nil {
  636. return err
  637. }
  638. return b.updateHistory(hist)
  639. }
  640. func (b *blockDec) updateHistory(hist *history) error {
  641. if len(b.data) > maxCompressedBlockSize {
  642. return fmt.Errorf("compressed block size too large (%d)", len(b.data))
  643. }
  644. // Set output and release references.
  645. b.dst = hist.decoders.out
  646. hist.recentOffsets = hist.decoders.prevOffset
  647. if b.Last {
  648. // if last block we don't care about history.
  649. println("Last block, no history returned")
  650. hist.b = hist.b[:0]
  651. return nil
  652. } else {
  653. hist.append(b.dst)
  654. if debugDecoder {
  655. println("Finished block with ", len(b.sequence), "sequences. Added", len(b.dst), "to history, now length", len(hist.b))
  656. }
  657. }
  658. hist.decoders.out, hist.decoders.literals = nil, nil
  659. return nil
  660. }