fse_decoder.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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. "encoding/binary"
  7. "errors"
  8. "fmt"
  9. "io"
  10. )
  11. const (
  12. tablelogAbsoluteMax = 9
  13. )
  14. const (
  15. /*!MEMORY_USAGE :
  16. * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
  17. * Increasing memory usage improves compression ratio
  18. * Reduced memory usage can improve speed, due to cache effect
  19. * Recommended max value is 14, for 16KB, which nicely fits into Intel x86 L1 cache */
  20. maxMemoryUsage = tablelogAbsoluteMax + 2
  21. maxTableLog = maxMemoryUsage - 2
  22. maxTablesize = 1 << maxTableLog
  23. maxTableMask = (1 << maxTableLog) - 1
  24. minTablelog = 5
  25. maxSymbolValue = 255
  26. )
  27. // fseDecoder provides temporary storage for compression and decompression.
  28. type fseDecoder struct {
  29. dt [maxTablesize]decSymbol // Decompression table.
  30. symbolLen uint16 // Length of active part of the symbol table.
  31. actualTableLog uint8 // Selected tablelog.
  32. maxBits uint8 // Maximum number of additional bits
  33. // used for table creation to avoid allocations.
  34. stateTable [256]uint16
  35. norm [maxSymbolValue + 1]int16
  36. preDefined bool
  37. }
  38. // tableStep returns the next table index.
  39. func tableStep(tableSize uint32) uint32 {
  40. return (tableSize >> 1) + (tableSize >> 3) + 3
  41. }
  42. // readNCount will read the symbol distribution so decoding tables can be constructed.
  43. func (s *fseDecoder) readNCount(b *byteReader, maxSymbol uint16) error {
  44. var (
  45. charnum uint16
  46. previous0 bool
  47. )
  48. if b.remain() < 4 {
  49. return errors.New("input too small")
  50. }
  51. bitStream := b.Uint32NC()
  52. nbBits := uint((bitStream & 0xF) + minTablelog) // extract tableLog
  53. if nbBits > tablelogAbsoluteMax {
  54. println("Invalid tablelog:", nbBits)
  55. return errors.New("tableLog too large")
  56. }
  57. bitStream >>= 4
  58. bitCount := uint(4)
  59. s.actualTableLog = uint8(nbBits)
  60. remaining := int32((1 << nbBits) + 1)
  61. threshold := int32(1 << nbBits)
  62. gotTotal := int32(0)
  63. nbBits++
  64. for remaining > 1 && charnum <= maxSymbol {
  65. if previous0 {
  66. //println("prev0")
  67. n0 := charnum
  68. for (bitStream & 0xFFFF) == 0xFFFF {
  69. //println("24 x 0")
  70. n0 += 24
  71. if r := b.remain(); r > 5 {
  72. b.advance(2)
  73. // The check above should make sure we can read 32 bits
  74. bitStream = b.Uint32NC() >> bitCount
  75. } else {
  76. // end of bit stream
  77. bitStream >>= 16
  78. bitCount += 16
  79. }
  80. }
  81. //printf("bitstream: %d, 0b%b", bitStream&3, bitStream)
  82. for (bitStream & 3) == 3 {
  83. n0 += 3
  84. bitStream >>= 2
  85. bitCount += 2
  86. }
  87. n0 += uint16(bitStream & 3)
  88. bitCount += 2
  89. if n0 > maxSymbolValue {
  90. return errors.New("maxSymbolValue too small")
  91. }
  92. //println("inserting ", n0-charnum, "zeroes from idx", charnum, "ending before", n0)
  93. for charnum < n0 {
  94. s.norm[uint8(charnum)] = 0
  95. charnum++
  96. }
  97. if r := b.remain(); r >= 7 || r-int(bitCount>>3) >= 4 {
  98. b.advance(bitCount >> 3)
  99. bitCount &= 7
  100. // The check above should make sure we can read 32 bits
  101. bitStream = b.Uint32NC() >> bitCount
  102. } else {
  103. bitStream >>= 2
  104. }
  105. }
  106. max := (2*threshold - 1) - remaining
  107. var count int32
  108. if int32(bitStream)&(threshold-1) < max {
  109. count = int32(bitStream) & (threshold - 1)
  110. if debugAsserts && nbBits < 1 {
  111. panic("nbBits underflow")
  112. }
  113. bitCount += nbBits - 1
  114. } else {
  115. count = int32(bitStream) & (2*threshold - 1)
  116. if count >= threshold {
  117. count -= max
  118. }
  119. bitCount += nbBits
  120. }
  121. // extra accuracy
  122. count--
  123. if count < 0 {
  124. // -1 means +1
  125. remaining += count
  126. gotTotal -= count
  127. } else {
  128. remaining -= count
  129. gotTotal += count
  130. }
  131. s.norm[charnum&0xff] = int16(count)
  132. charnum++
  133. previous0 = count == 0
  134. for remaining < threshold {
  135. nbBits--
  136. threshold >>= 1
  137. }
  138. if r := b.remain(); r >= 7 || r-int(bitCount>>3) >= 4 {
  139. b.advance(bitCount >> 3)
  140. bitCount &= 7
  141. // The check above should make sure we can read 32 bits
  142. bitStream = b.Uint32NC() >> (bitCount & 31)
  143. } else {
  144. bitCount -= (uint)(8 * (len(b.b) - 4 - b.off))
  145. b.off = len(b.b) - 4
  146. bitStream = b.Uint32() >> (bitCount & 31)
  147. }
  148. }
  149. s.symbolLen = charnum
  150. if s.symbolLen <= 1 {
  151. return fmt.Errorf("symbolLen (%d) too small", s.symbolLen)
  152. }
  153. if s.symbolLen > maxSymbolValue+1 {
  154. return fmt.Errorf("symbolLen (%d) too big", s.symbolLen)
  155. }
  156. if remaining != 1 {
  157. return fmt.Errorf("corruption detected (remaining %d != 1)", remaining)
  158. }
  159. if bitCount > 32 {
  160. return fmt.Errorf("corruption detected (bitCount %d > 32)", bitCount)
  161. }
  162. if gotTotal != 1<<s.actualTableLog {
  163. return fmt.Errorf("corruption detected (total %d != %d)", gotTotal, 1<<s.actualTableLog)
  164. }
  165. b.advance((bitCount + 7) >> 3)
  166. return s.buildDtable()
  167. }
  168. func (s *fseDecoder) mustReadFrom(r io.Reader) {
  169. fatalErr := func(err error) {
  170. if err != nil {
  171. panic(err)
  172. }
  173. }
  174. // dt [maxTablesize]decSymbol // Decompression table.
  175. // symbolLen uint16 // Length of active part of the symbol table.
  176. // actualTableLog uint8 // Selected tablelog.
  177. // maxBits uint8 // Maximum number of additional bits
  178. // // used for table creation to avoid allocations.
  179. // stateTable [256]uint16
  180. // norm [maxSymbolValue + 1]int16
  181. // preDefined bool
  182. fatalErr(binary.Read(r, binary.LittleEndian, &s.dt))
  183. fatalErr(binary.Read(r, binary.LittleEndian, &s.symbolLen))
  184. fatalErr(binary.Read(r, binary.LittleEndian, &s.actualTableLog))
  185. fatalErr(binary.Read(r, binary.LittleEndian, &s.maxBits))
  186. fatalErr(binary.Read(r, binary.LittleEndian, &s.stateTable))
  187. fatalErr(binary.Read(r, binary.LittleEndian, &s.norm))
  188. fatalErr(binary.Read(r, binary.LittleEndian, &s.preDefined))
  189. }
  190. // decSymbol contains information about a state entry,
  191. // Including the state offset base, the output symbol and
  192. // the number of bits to read for the low part of the destination state.
  193. // Using a composite uint64 is faster than a struct with separate members.
  194. type decSymbol uint64
  195. func newDecSymbol(nbits, addBits uint8, newState uint16, baseline uint32) decSymbol {
  196. return decSymbol(nbits) | (decSymbol(addBits) << 8) | (decSymbol(newState) << 16) | (decSymbol(baseline) << 32)
  197. }
  198. func (d decSymbol) nbBits() uint8 {
  199. return uint8(d)
  200. }
  201. func (d decSymbol) addBits() uint8 {
  202. return uint8(d >> 8)
  203. }
  204. func (d decSymbol) newState() uint16 {
  205. return uint16(d >> 16)
  206. }
  207. func (d decSymbol) baselineInt() int {
  208. return int(d >> 32)
  209. }
  210. func (d *decSymbol) setNBits(nBits uint8) {
  211. const mask = 0xffffffffffffff00
  212. *d = (*d & mask) | decSymbol(nBits)
  213. }
  214. func (d *decSymbol) setAddBits(addBits uint8) {
  215. const mask = 0xffffffffffff00ff
  216. *d = (*d & mask) | (decSymbol(addBits) << 8)
  217. }
  218. func (d *decSymbol) setNewState(state uint16) {
  219. const mask = 0xffffffff0000ffff
  220. *d = (*d & mask) | decSymbol(state)<<16
  221. }
  222. func (d *decSymbol) setExt(addBits uint8, baseline uint32) {
  223. const mask = 0xffff00ff
  224. *d = (*d & mask) | (decSymbol(addBits) << 8) | (decSymbol(baseline) << 32)
  225. }
  226. // decSymbolValue returns the transformed decSymbol for the given symbol.
  227. func decSymbolValue(symb uint8, t []baseOffset) (decSymbol, error) {
  228. if int(symb) >= len(t) {
  229. return 0, fmt.Errorf("rle symbol %d >= max %d", symb, len(t))
  230. }
  231. lu := t[symb]
  232. return newDecSymbol(0, lu.addBits, 0, lu.baseLine), nil
  233. }
  234. // setRLE will set the decoder til RLE mode.
  235. func (s *fseDecoder) setRLE(symbol decSymbol) {
  236. s.actualTableLog = 0
  237. s.maxBits = symbol.addBits()
  238. s.dt[0] = symbol
  239. }
  240. // transform will transform the decoder table into a table usable for
  241. // decoding without having to apply the transformation while decoding.
  242. // The state will contain the base value and the number of bits to read.
  243. func (s *fseDecoder) transform(t []baseOffset) error {
  244. tableSize := uint16(1 << s.actualTableLog)
  245. s.maxBits = 0
  246. for i, v := range s.dt[:tableSize] {
  247. add := v.addBits()
  248. if int(add) >= len(t) {
  249. return fmt.Errorf("invalid decoding table entry %d, symbol %d >= max (%d)", i, v.addBits(), len(t))
  250. }
  251. lu := t[add]
  252. if lu.addBits > s.maxBits {
  253. s.maxBits = lu.addBits
  254. }
  255. v.setExt(lu.addBits, lu.baseLine)
  256. s.dt[i] = v
  257. }
  258. return nil
  259. }
  260. type fseState struct {
  261. dt []decSymbol
  262. state decSymbol
  263. }
  264. // Initialize and decodeAsync first state and symbol.
  265. func (s *fseState) init(br *bitReader, tableLog uint8, dt []decSymbol) {
  266. s.dt = dt
  267. br.fill()
  268. s.state = dt[br.getBits(tableLog)]
  269. }
  270. // final returns the current state symbol without decoding the next.
  271. func (s decSymbol) final() (int, uint8) {
  272. return s.baselineInt(), s.addBits()
  273. }