huffman.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. // Copyright 2014 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 hpack
  5. import (
  6. "bytes"
  7. "errors"
  8. "io"
  9. "sync"
  10. )
  11. var bufPool = sync.Pool{
  12. New: func() interface{} { return new(bytes.Buffer) },
  13. }
  14. // HuffmanDecode decodes the string in v and writes the expanded
  15. // result to w, returning the number of bytes written to w and the
  16. // Write call's return value. At most one Write call is made.
  17. func HuffmanDecode(w io.Writer, v []byte) (int, error) {
  18. buf := bufPool.Get().(*bytes.Buffer)
  19. buf.Reset()
  20. defer bufPool.Put(buf)
  21. if err := huffmanDecode(buf, 0, v); err != nil {
  22. return 0, err
  23. }
  24. return w.Write(buf.Bytes())
  25. }
  26. // HuffmanDecodeToString decodes the string in v.
  27. func HuffmanDecodeToString(v []byte) (string, error) {
  28. buf := bufPool.Get().(*bytes.Buffer)
  29. buf.Reset()
  30. defer bufPool.Put(buf)
  31. if err := huffmanDecode(buf, 0, v); err != nil {
  32. return "", err
  33. }
  34. return buf.String(), nil
  35. }
  36. // ErrInvalidHuffman is returned for errors found decoding
  37. // Huffman-encoded strings.
  38. var ErrInvalidHuffman = errors.New("hpack: invalid Huffman-encoded data")
  39. // huffmanDecode decodes v to buf.
  40. // If maxLen is greater than 0, attempts to write more to buf than
  41. // maxLen bytes will return ErrStringLength.
  42. func huffmanDecode(buf *bytes.Buffer, maxLen int, v []byte) error {
  43. rootHuffmanNode := getRootHuffmanNode()
  44. n := rootHuffmanNode
  45. // cur is the bit buffer that has not been fed into n.
  46. // cbits is the number of low order bits in cur that are valid.
  47. // sbits is the number of bits of the symbol prefix being decoded.
  48. cur, cbits, sbits := uint(0), uint8(0), uint8(0)
  49. for _, b := range v {
  50. cur = cur<<8 | uint(b)
  51. cbits += 8
  52. sbits += 8
  53. for cbits >= 8 {
  54. idx := byte(cur >> (cbits - 8))
  55. n = n.children[idx]
  56. if n == nil {
  57. return ErrInvalidHuffman
  58. }
  59. if n.children == nil {
  60. if maxLen != 0 && buf.Len() == maxLen {
  61. return ErrStringLength
  62. }
  63. buf.WriteByte(n.sym)
  64. cbits -= n.codeLen
  65. n = rootHuffmanNode
  66. sbits = cbits
  67. } else {
  68. cbits -= 8
  69. }
  70. }
  71. }
  72. for cbits > 0 {
  73. n = n.children[byte(cur<<(8-cbits))]
  74. if n == nil {
  75. return ErrInvalidHuffman
  76. }
  77. if n.children != nil || n.codeLen > cbits {
  78. break
  79. }
  80. if maxLen != 0 && buf.Len() == maxLen {
  81. return ErrStringLength
  82. }
  83. buf.WriteByte(n.sym)
  84. cbits -= n.codeLen
  85. n = rootHuffmanNode
  86. sbits = cbits
  87. }
  88. if sbits > 7 {
  89. // Either there was an incomplete symbol, or overlong padding.
  90. // Both are decoding errors per RFC 7541 section 5.2.
  91. return ErrInvalidHuffman
  92. }
  93. if mask := uint(1<<cbits - 1); cur&mask != mask {
  94. // Trailing bits must be a prefix of EOS per RFC 7541 section 5.2.
  95. return ErrInvalidHuffman
  96. }
  97. return nil
  98. }
  99. // incomparable is a zero-width, non-comparable type. Adding it to a struct
  100. // makes that struct also non-comparable, and generally doesn't add
  101. // any size (as long as it's first).
  102. type incomparable [0]func()
  103. type node struct {
  104. _ incomparable
  105. // children is non-nil for internal nodes
  106. children *[256]*node
  107. // The following are only valid if children is nil:
  108. codeLen uint8 // number of bits that led to the output of sym
  109. sym byte // output symbol
  110. }
  111. func newInternalNode() *node {
  112. return &node{children: new([256]*node)}
  113. }
  114. var (
  115. buildRootOnce sync.Once
  116. lazyRootHuffmanNode *node
  117. )
  118. func getRootHuffmanNode() *node {
  119. buildRootOnce.Do(buildRootHuffmanNode)
  120. return lazyRootHuffmanNode
  121. }
  122. func buildRootHuffmanNode() {
  123. if len(huffmanCodes) != 256 {
  124. panic("unexpected size")
  125. }
  126. lazyRootHuffmanNode = newInternalNode()
  127. for i, code := range huffmanCodes {
  128. addDecoderNode(byte(i), code, huffmanCodeLen[i])
  129. }
  130. }
  131. func addDecoderNode(sym byte, code uint32, codeLen uint8) {
  132. cur := lazyRootHuffmanNode
  133. for codeLen > 8 {
  134. codeLen -= 8
  135. i := uint8(code >> codeLen)
  136. if cur.children[i] == nil {
  137. cur.children[i] = newInternalNode()
  138. }
  139. cur = cur.children[i]
  140. }
  141. shift := 8 - codeLen
  142. start, end := int(uint8(code<<shift)), int(1<<shift)
  143. for i := start; i < start+end; i++ {
  144. cur.children[i] = &node{sym: sym, codeLen: codeLen}
  145. }
  146. }
  147. // AppendHuffmanString appends s, as encoded in Huffman codes, to dst
  148. // and returns the extended buffer.
  149. func AppendHuffmanString(dst []byte, s string) []byte {
  150. rembits := uint8(8)
  151. for i := 0; i < len(s); i++ {
  152. if rembits == 8 {
  153. dst = append(dst, 0)
  154. }
  155. dst, rembits = appendByteToHuffmanCode(dst, rembits, s[i])
  156. }
  157. if rembits < 8 {
  158. // special EOS symbol
  159. code := uint32(0x3fffffff)
  160. nbits := uint8(30)
  161. t := uint8(code >> (nbits - rembits))
  162. dst[len(dst)-1] |= t
  163. }
  164. return dst
  165. }
  166. // HuffmanEncodeLength returns the number of bytes required to encode
  167. // s in Huffman codes. The result is round up to byte boundary.
  168. func HuffmanEncodeLength(s string) uint64 {
  169. n := uint64(0)
  170. for i := 0; i < len(s); i++ {
  171. n += uint64(huffmanCodeLen[s[i]])
  172. }
  173. return (n + 7) / 8
  174. }
  175. // appendByteToHuffmanCode appends Huffman code for c to dst and
  176. // returns the extended buffer and the remaining bits in the last
  177. // element. The appending is not byte aligned and the remaining bits
  178. // in the last element of dst is given in rembits.
  179. func appendByteToHuffmanCode(dst []byte, rembits uint8, c byte) ([]byte, uint8) {
  180. code := huffmanCodes[c]
  181. nbits := huffmanCodeLen[c]
  182. for {
  183. if rembits > nbits {
  184. t := uint8(code << (rembits - nbits))
  185. dst[len(dst)-1] |= t
  186. rembits -= nbits
  187. break
  188. }
  189. t := uint8(code >> (nbits - rembits))
  190. dst[len(dst)-1] |= t
  191. nbits -= rembits
  192. rembits = 8
  193. if nbits == 0 {
  194. break
  195. }
  196. dst = append(dst, 0)
  197. }
  198. return dst, rembits
  199. }