blockdec.go 18 KB

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