huffman_bit_writer.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package flate
  5. import (
  6. "io"
  7. )
  8. const (
  9. // The largest offset code.
  10. offsetCodeCount = 30
  11. // The special code used to mark the end of a block.
  12. endBlockMarker = 256
  13. // The first length code.
  14. lengthCodesStart = 257
  15. // The number of codegen codes.
  16. codegenCodeCount = 19
  17. badCode = 255
  18. // bufferFlushSize indicates the buffer size
  19. // after which bytes are flushed to the writer.
  20. // Should preferably be a multiple of 6, since
  21. // we accumulate 6 bytes between writes to the buffer.
  22. bufferFlushSize = 240
  23. // bufferSize is the actual output byte buffer size.
  24. // It must have additional headroom for a flush
  25. // which can contain up to 8 bytes.
  26. bufferSize = bufferFlushSize + 8
  27. )
  28. // The number of extra bits needed by length code X - LENGTH_CODES_START.
  29. var lengthExtraBits = []int8{
  30. /* 257 */ 0, 0, 0,
  31. /* 260 */ 0, 0, 0, 0, 0, 1, 1, 1, 1, 2,
  32. /* 270 */ 2, 2, 2, 3, 3, 3, 3, 4, 4, 4,
  33. /* 280 */ 4, 5, 5, 5, 5, 0,
  34. }
  35. // The length indicated by length code X - LENGTH_CODES_START.
  36. var lengthBase = []uint32{
  37. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10,
  38. 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  39. 64, 80, 96, 112, 128, 160, 192, 224, 255,
  40. }
  41. // offset code word extra bits.
  42. var offsetExtraBits = []int8{
  43. 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
  44. 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
  45. 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
  46. }
  47. var offsetBase = []uint32{
  48. 0x000000, 0x000001, 0x000002, 0x000003, 0x000004,
  49. 0x000006, 0x000008, 0x00000c, 0x000010, 0x000018,
  50. 0x000020, 0x000030, 0x000040, 0x000060, 0x000080,
  51. 0x0000c0, 0x000100, 0x000180, 0x000200, 0x000300,
  52. 0x000400, 0x000600, 0x000800, 0x000c00, 0x001000,
  53. 0x001800, 0x002000, 0x003000, 0x004000, 0x006000,
  54. }
  55. // The odd order in which the codegen code sizes are written.
  56. var codegenOrder = []uint32{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}
  57. type huffmanBitWriter struct {
  58. // writer is the underlying writer.
  59. // Do not use it directly; use the write method, which ensures
  60. // that Write errors are sticky.
  61. writer io.Writer
  62. // Data waiting to be written is bytes[0:nbytes]
  63. // and then the low nbits of bits. Data is always written
  64. // sequentially into the bytes array.
  65. bits uint64
  66. nbits uint
  67. bytes [bufferSize]byte
  68. codegenFreq [codegenCodeCount]int32
  69. nbytes int
  70. literalFreq []int32
  71. offsetFreq []int32
  72. codegen []uint8
  73. literalEncoding *huffmanEncoder
  74. offsetEncoding *huffmanEncoder
  75. codegenEncoding *huffmanEncoder
  76. err error
  77. }
  78. func newHuffmanBitWriter(w io.Writer) *huffmanBitWriter {
  79. return &huffmanBitWriter{
  80. writer: w,
  81. literalFreq: make([]int32, maxNumLit),
  82. offsetFreq: make([]int32, offsetCodeCount),
  83. codegen: make([]uint8, maxNumLit+offsetCodeCount+1),
  84. literalEncoding: newHuffmanEncoder(maxNumLit),
  85. codegenEncoding: newHuffmanEncoder(codegenCodeCount),
  86. offsetEncoding: newHuffmanEncoder(offsetCodeCount),
  87. }
  88. }
  89. func (w *huffmanBitWriter) reset(writer io.Writer) {
  90. w.writer = writer
  91. w.bits, w.nbits, w.nbytes, w.err = 0, 0, 0, nil
  92. }
  93. func (w *huffmanBitWriter) flush() {
  94. if w.err != nil {
  95. w.nbits = 0
  96. return
  97. }
  98. n := w.nbytes
  99. for w.nbits != 0 {
  100. w.bytes[n] = byte(w.bits)
  101. w.bits >>= 8
  102. if w.nbits > 8 { // Avoid underflow
  103. w.nbits -= 8
  104. } else {
  105. w.nbits = 0
  106. }
  107. n++
  108. }
  109. w.bits = 0
  110. w.write(w.bytes[:n])
  111. w.nbytes = 0
  112. }
  113. func (w *huffmanBitWriter) write(b []byte) {
  114. if w.err != nil {
  115. return
  116. }
  117. _, w.err = w.writer.Write(b)
  118. }
  119. func (w *huffmanBitWriter) writeBits(b int32, nb uint) {
  120. if w.err != nil {
  121. return
  122. }
  123. w.bits |= uint64(b) << w.nbits
  124. w.nbits += nb
  125. if w.nbits >= 48 {
  126. bits := w.bits
  127. w.bits >>= 48
  128. w.nbits -= 48
  129. n := w.nbytes
  130. bytes := w.bytes[n : n+6]
  131. bytes[0] = byte(bits)
  132. bytes[1] = byte(bits >> 8)
  133. bytes[2] = byte(bits >> 16)
  134. bytes[3] = byte(bits >> 24)
  135. bytes[4] = byte(bits >> 32)
  136. bytes[5] = byte(bits >> 40)
  137. n += 6
  138. if n >= bufferFlushSize {
  139. w.write(w.bytes[:n])
  140. n = 0
  141. }
  142. w.nbytes = n
  143. }
  144. }
  145. func (w *huffmanBitWriter) writeBytes(bytes []byte) {
  146. if w.err != nil {
  147. return
  148. }
  149. n := w.nbytes
  150. if w.nbits&7 != 0 {
  151. w.err = InternalError("writeBytes with unfinished bits")
  152. return
  153. }
  154. for w.nbits != 0 {
  155. w.bytes[n] = byte(w.bits)
  156. w.bits >>= 8
  157. w.nbits -= 8
  158. n++
  159. }
  160. if n != 0 {
  161. w.write(w.bytes[:n])
  162. }
  163. w.nbytes = 0
  164. w.write(bytes)
  165. }
  166. // RFC 1951 3.2.7 specifies a special run-length encoding for specifying
  167. // the literal and offset lengths arrays (which are concatenated into a single
  168. // array). This method generates that run-length encoding.
  169. //
  170. // The result is written into the codegen array, and the frequencies
  171. // of each code is written into the codegenFreq array.
  172. // Codes 0-15 are single byte codes. Codes 16-18 are followed by additional
  173. // information. Code badCode is an end marker
  174. //
  175. // numLiterals The number of literals in literalEncoding
  176. // numOffsets The number of offsets in offsetEncoding
  177. // litenc, offenc The literal and offset encoder to use
  178. func (w *huffmanBitWriter) generateCodegen(numLiterals int, numOffsets int, litEnc, offEnc *huffmanEncoder) {
  179. for i := range w.codegenFreq {
  180. w.codegenFreq[i] = 0
  181. }
  182. // Note that we are using codegen both as a temporary variable for holding
  183. // a copy of the frequencies, and as the place where we put the result.
  184. // This is fine because the output is always shorter than the input used
  185. // so far.
  186. codegen := w.codegen // cache
  187. // Copy the concatenated code sizes to codegen. Put a marker at the end.
  188. cgnl := codegen[:numLiterals]
  189. for i := range cgnl {
  190. cgnl[i] = uint8(litEnc.codes[i].len)
  191. }
  192. cgnl = codegen[numLiterals : numLiterals+numOffsets]
  193. for i := range cgnl {
  194. cgnl[i] = uint8(offEnc.codes[i].len)
  195. }
  196. codegen[numLiterals+numOffsets] = badCode
  197. size := codegen[0]
  198. count := 1
  199. outIndex := 0
  200. for inIndex := 1; size != badCode; inIndex++ {
  201. // INVARIANT: We have seen "count" copies of size that have not yet
  202. // had output generated for them.
  203. nextSize := codegen[inIndex]
  204. if nextSize == size {
  205. count++
  206. continue
  207. }
  208. // We need to generate codegen indicating "count" of size.
  209. if size != 0 {
  210. codegen[outIndex] = size
  211. outIndex++
  212. w.codegenFreq[size]++
  213. count--
  214. for count >= 3 {
  215. n := 6
  216. if n > count {
  217. n = count
  218. }
  219. codegen[outIndex] = 16
  220. outIndex++
  221. codegen[outIndex] = uint8(n - 3)
  222. outIndex++
  223. w.codegenFreq[16]++
  224. count -= n
  225. }
  226. } else {
  227. for count >= 11 {
  228. n := 138
  229. if n > count {
  230. n = count
  231. }
  232. codegen[outIndex] = 18
  233. outIndex++
  234. codegen[outIndex] = uint8(n - 11)
  235. outIndex++
  236. w.codegenFreq[18]++
  237. count -= n
  238. }
  239. if count >= 3 {
  240. // count >= 3 && count <= 10
  241. codegen[outIndex] = 17
  242. outIndex++
  243. codegen[outIndex] = uint8(count - 3)
  244. outIndex++
  245. w.codegenFreq[17]++
  246. count = 0
  247. }
  248. }
  249. count--
  250. for ; count >= 0; count-- {
  251. codegen[outIndex] = size
  252. outIndex++
  253. w.codegenFreq[size]++
  254. }
  255. // Set up invariant for next time through the loop.
  256. size = nextSize
  257. count = 1
  258. }
  259. // Marker indicating the end of the codegen.
  260. codegen[outIndex] = badCode
  261. }
  262. // dynamicSize returns the size of dynamically encoded data in bits.
  263. func (w *huffmanBitWriter) dynamicSize(litEnc, offEnc *huffmanEncoder, extraBits int) (size, numCodegens int) {
  264. numCodegens = len(w.codegenFreq)
  265. for numCodegens > 4 && w.codegenFreq[codegenOrder[numCodegens-1]] == 0 {
  266. numCodegens--
  267. }
  268. header := 3 + 5 + 5 + 4 + (3 * numCodegens) +
  269. w.codegenEncoding.bitLength(w.codegenFreq[:]) +
  270. int(w.codegenFreq[16])*2 +
  271. int(w.codegenFreq[17])*3 +
  272. int(w.codegenFreq[18])*7
  273. size = header +
  274. litEnc.bitLength(w.literalFreq) +
  275. offEnc.bitLength(w.offsetFreq) +
  276. extraBits
  277. return size, numCodegens
  278. }
  279. // fixedSize returns the size of dynamically encoded data in bits.
  280. func (w *huffmanBitWriter) fixedSize(extraBits int) int {
  281. return 3 +
  282. fixedLiteralEncoding.bitLength(w.literalFreq) +
  283. fixedOffsetEncoding.bitLength(w.offsetFreq) +
  284. extraBits
  285. }
  286. // storedSize calculates the stored size, including header.
  287. // The function returns the size in bits and whether the block
  288. // fits inside a single block.
  289. func (w *huffmanBitWriter) storedSize(in []byte) (int, bool) {
  290. if in == nil {
  291. return 0, false
  292. }
  293. if len(in) <= maxStoreBlockSize {
  294. return (len(in) + 5) * 8, true
  295. }
  296. return 0, false
  297. }
  298. func (w *huffmanBitWriter) writeCode(c hcode) {
  299. if w.err != nil {
  300. return
  301. }
  302. w.bits |= uint64(c.code) << w.nbits
  303. w.nbits += uint(c.len)
  304. if w.nbits >= 48 {
  305. bits := w.bits
  306. w.bits >>= 48
  307. w.nbits -= 48
  308. n := w.nbytes
  309. bytes := w.bytes[n : n+6]
  310. bytes[0] = byte(bits)
  311. bytes[1] = byte(bits >> 8)
  312. bytes[2] = byte(bits >> 16)
  313. bytes[3] = byte(bits >> 24)
  314. bytes[4] = byte(bits >> 32)
  315. bytes[5] = byte(bits >> 40)
  316. n += 6
  317. if n >= bufferFlushSize {
  318. w.write(w.bytes[:n])
  319. n = 0
  320. }
  321. w.nbytes = n
  322. }
  323. }
  324. // Write the header of a dynamic Huffman block to the output stream.
  325. //
  326. // numLiterals The number of literals specified in codegen
  327. // numOffsets The number of offsets specified in codegen
  328. // numCodegens The number of codegens used in codegen
  329. func (w *huffmanBitWriter) writeDynamicHeader(numLiterals int, numOffsets int, numCodegens int, isEof bool) {
  330. if w.err != nil {
  331. return
  332. }
  333. var firstBits int32 = 4
  334. if isEof {
  335. firstBits = 5
  336. }
  337. w.writeBits(firstBits, 3)
  338. w.writeBits(int32(numLiterals-257), 5)
  339. w.writeBits(int32(numOffsets-1), 5)
  340. w.writeBits(int32(numCodegens-4), 4)
  341. for i := 0; i < numCodegens; i++ {
  342. value := uint(w.codegenEncoding.codes[codegenOrder[i]].len)
  343. w.writeBits(int32(value), 3)
  344. }
  345. i := 0
  346. for {
  347. var codeWord int = int(w.codegen[i])
  348. i++
  349. if codeWord == badCode {
  350. break
  351. }
  352. w.writeCode(w.codegenEncoding.codes[uint32(codeWord)])
  353. switch codeWord {
  354. case 16:
  355. w.writeBits(int32(w.codegen[i]), 2)
  356. i++
  357. break
  358. case 17:
  359. w.writeBits(int32(w.codegen[i]), 3)
  360. i++
  361. break
  362. case 18:
  363. w.writeBits(int32(w.codegen[i]), 7)
  364. i++
  365. break
  366. }
  367. }
  368. }
  369. func (w *huffmanBitWriter) writeStoredHeader(length int, isEof bool) {
  370. if w.err != nil {
  371. return
  372. }
  373. var flag int32
  374. if isEof {
  375. flag = 1
  376. }
  377. w.writeBits(flag, 3)
  378. w.flush()
  379. w.writeBits(int32(length), 16)
  380. w.writeBits(int32(^uint16(length)), 16)
  381. }
  382. func (w *huffmanBitWriter) writeFixedHeader(isEof bool) {
  383. if w.err != nil {
  384. return
  385. }
  386. // Indicate that we are a fixed Huffman block
  387. var value int32 = 2
  388. if isEof {
  389. value = 3
  390. }
  391. w.writeBits(value, 3)
  392. }
  393. // writeBlock will write a block of tokens with the smallest encoding.
  394. // The original input can be supplied, and if the huffman encoded data
  395. // is larger than the original bytes, the data will be written as a
  396. // stored block.
  397. // If the input is nil, the tokens will always be Huffman encoded.
  398. func (w *huffmanBitWriter) writeBlock(tokens []token, eof bool, input []byte) {
  399. if w.err != nil {
  400. return
  401. }
  402. tokens = append(tokens, endBlockMarker)
  403. numLiterals, numOffsets := w.indexTokens(tokens)
  404. var extraBits int
  405. storedSize, storable := w.storedSize(input)
  406. if storable {
  407. // We only bother calculating the costs of the extra bits required by
  408. // the length of offset fields (which will be the same for both fixed
  409. // and dynamic encoding), if we need to compare those two encodings
  410. // against stored encoding.
  411. for lengthCode := lengthCodesStart + 8; lengthCode < numLiterals; lengthCode++ {
  412. // First eight length codes have extra size = 0.
  413. extraBits += int(w.literalFreq[lengthCode]) * int(lengthExtraBits[lengthCode-lengthCodesStart])
  414. }
  415. for offsetCode := 4; offsetCode < numOffsets; offsetCode++ {
  416. // First four offset codes have extra size = 0.
  417. extraBits += int(w.offsetFreq[offsetCode]) * int(offsetExtraBits[offsetCode])
  418. }
  419. }
  420. // Figure out smallest code.
  421. // Fixed Huffman baseline.
  422. var literalEncoding = fixedLiteralEncoding
  423. var offsetEncoding = fixedOffsetEncoding
  424. var size = w.fixedSize(extraBits)
  425. // Dynamic Huffman?
  426. var numCodegens int
  427. // Generate codegen and codegenFrequencies, which indicates how to encode
  428. // the literalEncoding and the offsetEncoding.
  429. w.generateCodegen(numLiterals, numOffsets, w.literalEncoding, w.offsetEncoding)
  430. w.codegenEncoding.generate(w.codegenFreq[:], 7)
  431. dynamicSize, numCodegens := w.dynamicSize(w.literalEncoding, w.offsetEncoding, extraBits)
  432. if dynamicSize < size {
  433. size = dynamicSize
  434. literalEncoding = w.literalEncoding
  435. offsetEncoding = w.offsetEncoding
  436. }
  437. // Stored bytes?
  438. if storable && storedSize < size {
  439. w.writeStoredHeader(len(input), eof)
  440. w.writeBytes(input)
  441. return
  442. }
  443. // Huffman.
  444. if literalEncoding == fixedLiteralEncoding {
  445. w.writeFixedHeader(eof)
  446. } else {
  447. w.writeDynamicHeader(numLiterals, numOffsets, numCodegens, eof)
  448. }
  449. // Write the tokens.
  450. w.writeTokens(tokens, literalEncoding.codes, offsetEncoding.codes)
  451. }
  452. // writeBlockDynamic encodes a block using a dynamic Huffman table.
  453. // This should be used if the symbols used have a disproportionate
  454. // histogram distribution.
  455. // If input is supplied and the compression savings are below 1/16th of the
  456. // input size the block is stored.
  457. func (w *huffmanBitWriter) writeBlockDynamic(tokens []token, eof bool, input []byte) {
  458. if w.err != nil {
  459. return
  460. }
  461. tokens = append(tokens, endBlockMarker)
  462. numLiterals, numOffsets := w.indexTokens(tokens)
  463. // Generate codegen and codegenFrequencies, which indicates how to encode
  464. // the literalEncoding and the offsetEncoding.
  465. w.generateCodegen(numLiterals, numOffsets, w.literalEncoding, w.offsetEncoding)
  466. w.codegenEncoding.generate(w.codegenFreq[:], 7)
  467. size, numCodegens := w.dynamicSize(w.literalEncoding, w.offsetEncoding, 0)
  468. // Store bytes, if we don't get a reasonable improvement.
  469. if ssize, storable := w.storedSize(input); storable && ssize < (size+size>>4) {
  470. w.writeStoredHeader(len(input), eof)
  471. w.writeBytes(input)
  472. return
  473. }
  474. // Write Huffman table.
  475. w.writeDynamicHeader(numLiterals, numOffsets, numCodegens, eof)
  476. // Write the tokens.
  477. w.writeTokens(tokens, w.literalEncoding.codes, w.offsetEncoding.codes)
  478. }
  479. // indexTokens indexes a slice of tokens, and updates
  480. // literalFreq and offsetFreq, and generates literalEncoding
  481. // and offsetEncoding.
  482. // The number of literal and offset tokens is returned.
  483. func (w *huffmanBitWriter) indexTokens(tokens []token) (numLiterals, numOffsets int) {
  484. for i := range w.literalFreq {
  485. w.literalFreq[i] = 0
  486. }
  487. for i := range w.offsetFreq {
  488. w.offsetFreq[i] = 0
  489. }
  490. for _, t := range tokens {
  491. if t < matchType {
  492. w.literalFreq[t.literal()]++
  493. continue
  494. }
  495. length := t.length()
  496. offset := t.offset()
  497. w.literalFreq[lengthCodesStart+lengthCode(length)]++
  498. w.offsetFreq[offsetCode(offset)]++
  499. }
  500. // get the number of literals
  501. numLiterals = len(w.literalFreq)
  502. for w.literalFreq[numLiterals-1] == 0 {
  503. numLiterals--
  504. }
  505. // get the number of offsets
  506. numOffsets = len(w.offsetFreq)
  507. for numOffsets > 0 && w.offsetFreq[numOffsets-1] == 0 {
  508. numOffsets--
  509. }
  510. if numOffsets == 0 {
  511. // We haven't found a single match. If we want to go with the dynamic encoding,
  512. // we should count at least one offset to be sure that the offset huffman tree could be encoded.
  513. w.offsetFreq[0] = 1
  514. numOffsets = 1
  515. }
  516. w.literalEncoding.generate(w.literalFreq, 15)
  517. w.offsetEncoding.generate(w.offsetFreq, 15)
  518. return
  519. }
  520. // writeTokens writes a slice of tokens to the output.
  521. // codes for literal and offset encoding must be supplied.
  522. func (w *huffmanBitWriter) writeTokens(tokens []token, leCodes, oeCodes []hcode) {
  523. if w.err != nil {
  524. return
  525. }
  526. for _, t := range tokens {
  527. if t < matchType {
  528. w.writeCode(leCodes[t.literal()])
  529. continue
  530. }
  531. // Write the length
  532. length := t.length()
  533. lengthCode := lengthCode(length)
  534. w.writeCode(leCodes[lengthCode+lengthCodesStart])
  535. extraLengthBits := uint(lengthExtraBits[lengthCode])
  536. if extraLengthBits > 0 {
  537. extraLength := int32(length - lengthBase[lengthCode])
  538. w.writeBits(extraLength, extraLengthBits)
  539. }
  540. // Write the offset
  541. offset := t.offset()
  542. offsetCode := offsetCode(offset)
  543. w.writeCode(oeCodes[offsetCode])
  544. extraOffsetBits := uint(offsetExtraBits[offsetCode])
  545. if extraOffsetBits > 0 {
  546. extraOffset := int32(offset - offsetBase[offsetCode])
  547. w.writeBits(extraOffset, extraOffsetBits)
  548. }
  549. }
  550. }
  551. // huffOffset is a static offset encoder used for huffman only encoding.
  552. // It can be reused since we will not be encoding offset values.
  553. var huffOffset *huffmanEncoder
  554. func init() {
  555. offsetFreq := make([]int32, offsetCodeCount)
  556. offsetFreq[0] = 1
  557. huffOffset = newHuffmanEncoder(offsetCodeCount)
  558. huffOffset.generate(offsetFreq, 15)
  559. }
  560. // writeBlockHuff encodes a block of bytes as either
  561. // Huffman encoded literals or uncompressed bytes if the
  562. // results only gains very little from compression.
  563. func (w *huffmanBitWriter) writeBlockHuff(eof bool, input []byte) {
  564. if w.err != nil {
  565. return
  566. }
  567. // Clear histogram
  568. for i := range w.literalFreq {
  569. w.literalFreq[i] = 0
  570. }
  571. // Add everything as literals
  572. histogram(input, w.literalFreq)
  573. w.literalFreq[endBlockMarker] = 1
  574. const numLiterals = endBlockMarker + 1
  575. w.offsetFreq[0] = 1
  576. const numOffsets = 1
  577. w.literalEncoding.generate(w.literalFreq, 15)
  578. // Figure out smallest code.
  579. // Always use dynamic Huffman or Store
  580. var numCodegens int
  581. // Generate codegen and codegenFrequencies, which indicates how to encode
  582. // the literalEncoding and the offsetEncoding.
  583. w.generateCodegen(numLiterals, numOffsets, w.literalEncoding, huffOffset)
  584. w.codegenEncoding.generate(w.codegenFreq[:], 7)
  585. size, numCodegens := w.dynamicSize(w.literalEncoding, huffOffset, 0)
  586. // Store bytes, if we don't get a reasonable improvement.
  587. if ssize, storable := w.storedSize(input); storable && ssize < (size+size>>4) {
  588. w.writeStoredHeader(len(input), eof)
  589. w.writeBytes(input)
  590. return
  591. }
  592. // Huffman.
  593. w.writeDynamicHeader(numLiterals, numOffsets, numCodegens, eof)
  594. encoding := w.literalEncoding.codes[:257]
  595. n := w.nbytes
  596. for _, t := range input {
  597. // Bitwriting inlined, ~30% speedup
  598. c := encoding[t]
  599. w.bits |= uint64(c.code) << w.nbits
  600. w.nbits += uint(c.len)
  601. if w.nbits < 48 {
  602. continue
  603. }
  604. // Store 6 bytes
  605. bits := w.bits
  606. w.bits >>= 48
  607. w.nbits -= 48
  608. bytes := w.bytes[n : n+6]
  609. bytes[0] = byte(bits)
  610. bytes[1] = byte(bits >> 8)
  611. bytes[2] = byte(bits >> 16)
  612. bytes[3] = byte(bits >> 24)
  613. bytes[4] = byte(bits >> 32)
  614. bytes[5] = byte(bits >> 40)
  615. n += 6
  616. if n < bufferFlushSize {
  617. continue
  618. }
  619. w.write(w.bytes[:n])
  620. if w.err != nil {
  621. return // Return early in the event of write failures
  622. }
  623. n = 0
  624. }
  625. w.nbytes = n
  626. w.writeCode(encoding[endBlockMarker])
  627. }
  628. // histogram accumulates a histogram of b in h.
  629. //
  630. // len(h) must be >= 256, and h's elements must be all zeroes.
  631. func histogram(b []byte, h []int32) {
  632. h = h[:256]
  633. for _, t := range b {
  634. h[t]++
  635. }
  636. }