compress.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. // Copyright 2018 Klaus Post. 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. // Based on work Copyright (c) 2013, Yann Collet, released under BSD License.
  5. package fse
  6. import (
  7. "errors"
  8. "fmt"
  9. )
  10. // Compress the input bytes. Input must be < 2GB.
  11. // Provide a Scratch buffer to avoid memory allocations.
  12. // Note that the output is also kept in the scratch buffer.
  13. // If input is too hard to compress, ErrIncompressible is returned.
  14. // If input is a single byte value repeated ErrUseRLE is returned.
  15. func Compress(in []byte, s *Scratch) ([]byte, error) {
  16. if len(in) <= 1 {
  17. return nil, ErrIncompressible
  18. }
  19. if len(in) > (2<<30)-1 {
  20. return nil, errors.New("input too big, must be < 2GB")
  21. }
  22. s, err := s.prepare(in)
  23. if err != nil {
  24. return nil, err
  25. }
  26. // Create histogram, if none was provided.
  27. maxCount := s.maxCount
  28. if maxCount == 0 {
  29. maxCount = s.countSimple(in)
  30. }
  31. // Reset for next run.
  32. s.clearCount = true
  33. s.maxCount = 0
  34. if maxCount == len(in) {
  35. // One symbol, use RLE
  36. return nil, ErrUseRLE
  37. }
  38. if maxCount == 1 || maxCount < (len(in)>>7) {
  39. // Each symbol present maximum once or too well distributed.
  40. return nil, ErrIncompressible
  41. }
  42. s.optimalTableLog()
  43. err = s.normalizeCount()
  44. if err != nil {
  45. return nil, err
  46. }
  47. err = s.writeCount()
  48. if err != nil {
  49. return nil, err
  50. }
  51. if false {
  52. err = s.validateNorm()
  53. if err != nil {
  54. return nil, err
  55. }
  56. }
  57. err = s.buildCTable()
  58. if err != nil {
  59. return nil, err
  60. }
  61. err = s.compress(in)
  62. if err != nil {
  63. return nil, err
  64. }
  65. s.Out = s.bw.out
  66. // Check if we compressed.
  67. if len(s.Out) >= len(in) {
  68. return nil, ErrIncompressible
  69. }
  70. return s.Out, nil
  71. }
  72. // cState contains the compression state of a stream.
  73. type cState struct {
  74. bw *bitWriter
  75. stateTable []uint16
  76. state uint16
  77. }
  78. // init will initialize the compression state to the first symbol of the stream.
  79. func (c *cState) init(bw *bitWriter, ct *cTable, tableLog uint8, first symbolTransform) {
  80. c.bw = bw
  81. c.stateTable = ct.stateTable
  82. nbBitsOut := (first.deltaNbBits + (1 << 15)) >> 16
  83. im := int32((nbBitsOut << 16) - first.deltaNbBits)
  84. lu := (im >> nbBitsOut) + first.deltaFindState
  85. c.state = c.stateTable[lu]
  86. }
  87. // encode the output symbol provided and write it to the bitstream.
  88. func (c *cState) encode(symbolTT symbolTransform) {
  89. nbBitsOut := (uint32(c.state) + symbolTT.deltaNbBits) >> 16
  90. dstState := int32(c.state>>(nbBitsOut&15)) + symbolTT.deltaFindState
  91. c.bw.addBits16NC(c.state, uint8(nbBitsOut))
  92. c.state = c.stateTable[dstState]
  93. }
  94. // encode the output symbol provided and write it to the bitstream.
  95. func (c *cState) encodeZero(symbolTT symbolTransform) {
  96. nbBitsOut := (uint32(c.state) + symbolTT.deltaNbBits) >> 16
  97. dstState := int32(c.state>>(nbBitsOut&15)) + symbolTT.deltaFindState
  98. c.bw.addBits16ZeroNC(c.state, uint8(nbBitsOut))
  99. c.state = c.stateTable[dstState]
  100. }
  101. // flush will write the tablelog to the output and flush the remaining full bytes.
  102. func (c *cState) flush(tableLog uint8) {
  103. c.bw.flush32()
  104. c.bw.addBits16NC(c.state, tableLog)
  105. c.bw.flush()
  106. }
  107. // compress is the main compression loop that will encode the input from the last byte to the first.
  108. func (s *Scratch) compress(src []byte) error {
  109. if len(src) <= 2 {
  110. return errors.New("compress: src too small")
  111. }
  112. tt := s.ct.symbolTT[:256]
  113. s.bw.reset(s.Out)
  114. // Our two states each encodes every second byte.
  115. // Last byte encoded (first byte decoded) will always be encoded by c1.
  116. var c1, c2 cState
  117. // Encode so remaining size is divisible by 4.
  118. ip := len(src)
  119. if ip&1 == 1 {
  120. c1.init(&s.bw, &s.ct, s.actualTableLog, tt[src[ip-1]])
  121. c2.init(&s.bw, &s.ct, s.actualTableLog, tt[src[ip-2]])
  122. c1.encodeZero(tt[src[ip-3]])
  123. ip -= 3
  124. } else {
  125. c2.init(&s.bw, &s.ct, s.actualTableLog, tt[src[ip-1]])
  126. c1.init(&s.bw, &s.ct, s.actualTableLog, tt[src[ip-2]])
  127. ip -= 2
  128. }
  129. if ip&2 != 0 {
  130. c2.encodeZero(tt[src[ip-1]])
  131. c1.encodeZero(tt[src[ip-2]])
  132. ip -= 2
  133. }
  134. src = src[:ip]
  135. // Main compression loop.
  136. switch {
  137. case !s.zeroBits && s.actualTableLog <= 8:
  138. // We can encode 4 symbols without requiring a flush.
  139. // We do not need to check if any output is 0 bits.
  140. for ; len(src) >= 4; src = src[:len(src)-4] {
  141. s.bw.flush32()
  142. v3, v2, v1, v0 := src[len(src)-4], src[len(src)-3], src[len(src)-2], src[len(src)-1]
  143. c2.encode(tt[v0])
  144. c1.encode(tt[v1])
  145. c2.encode(tt[v2])
  146. c1.encode(tt[v3])
  147. }
  148. case !s.zeroBits:
  149. // We do not need to check if any output is 0 bits.
  150. for ; len(src) >= 4; src = src[:len(src)-4] {
  151. s.bw.flush32()
  152. v3, v2, v1, v0 := src[len(src)-4], src[len(src)-3], src[len(src)-2], src[len(src)-1]
  153. c2.encode(tt[v0])
  154. c1.encode(tt[v1])
  155. s.bw.flush32()
  156. c2.encode(tt[v2])
  157. c1.encode(tt[v3])
  158. }
  159. case s.actualTableLog <= 8:
  160. // We can encode 4 symbols without requiring a flush
  161. for ; len(src) >= 4; src = src[:len(src)-4] {
  162. s.bw.flush32()
  163. v3, v2, v1, v0 := src[len(src)-4], src[len(src)-3], src[len(src)-2], src[len(src)-1]
  164. c2.encodeZero(tt[v0])
  165. c1.encodeZero(tt[v1])
  166. c2.encodeZero(tt[v2])
  167. c1.encodeZero(tt[v3])
  168. }
  169. default:
  170. for ; len(src) >= 4; src = src[:len(src)-4] {
  171. s.bw.flush32()
  172. v3, v2, v1, v0 := src[len(src)-4], src[len(src)-3], src[len(src)-2], src[len(src)-1]
  173. c2.encodeZero(tt[v0])
  174. c1.encodeZero(tt[v1])
  175. s.bw.flush32()
  176. c2.encodeZero(tt[v2])
  177. c1.encodeZero(tt[v3])
  178. }
  179. }
  180. // Flush final state.
  181. // Used to initialize state when decoding.
  182. c2.flush(s.actualTableLog)
  183. c1.flush(s.actualTableLog)
  184. s.bw.close()
  185. return nil
  186. }
  187. // writeCount will write the normalized histogram count to header.
  188. // This is read back by readNCount.
  189. func (s *Scratch) writeCount() error {
  190. var (
  191. tableLog = s.actualTableLog
  192. tableSize = 1 << tableLog
  193. previous0 bool
  194. charnum uint16
  195. maxHeaderSize = ((int(s.symbolLen)*int(tableLog) + 4 + 2) >> 3) + 3
  196. // Write Table Size
  197. bitStream = uint32(tableLog - minTablelog)
  198. bitCount = uint(4)
  199. remaining = int16(tableSize + 1) /* +1 for extra accuracy */
  200. threshold = int16(tableSize)
  201. nbBits = uint(tableLog + 1)
  202. )
  203. if cap(s.Out) < maxHeaderSize {
  204. s.Out = make([]byte, 0, s.br.remain()+maxHeaderSize)
  205. }
  206. outP := uint(0)
  207. out := s.Out[:maxHeaderSize]
  208. // stops at 1
  209. for remaining > 1 {
  210. if previous0 {
  211. start := charnum
  212. for s.norm[charnum] == 0 {
  213. charnum++
  214. }
  215. for charnum >= start+24 {
  216. start += 24
  217. bitStream += uint32(0xFFFF) << bitCount
  218. out[outP] = byte(bitStream)
  219. out[outP+1] = byte(bitStream >> 8)
  220. outP += 2
  221. bitStream >>= 16
  222. }
  223. for charnum >= start+3 {
  224. start += 3
  225. bitStream += 3 << bitCount
  226. bitCount += 2
  227. }
  228. bitStream += uint32(charnum-start) << bitCount
  229. bitCount += 2
  230. if bitCount > 16 {
  231. out[outP] = byte(bitStream)
  232. out[outP+1] = byte(bitStream >> 8)
  233. outP += 2
  234. bitStream >>= 16
  235. bitCount -= 16
  236. }
  237. }
  238. count := s.norm[charnum]
  239. charnum++
  240. max := (2*threshold - 1) - remaining
  241. if count < 0 {
  242. remaining += count
  243. } else {
  244. remaining -= count
  245. }
  246. count++ // +1 for extra accuracy
  247. if count >= threshold {
  248. count += max // [0..max[ [max..threshold[ (...) [threshold+max 2*threshold[
  249. }
  250. bitStream += uint32(count) << bitCount
  251. bitCount += nbBits
  252. if count < max {
  253. bitCount--
  254. }
  255. previous0 = count == 1
  256. if remaining < 1 {
  257. return errors.New("internal error: remaining<1")
  258. }
  259. for remaining < threshold {
  260. nbBits--
  261. threshold >>= 1
  262. }
  263. if bitCount > 16 {
  264. out[outP] = byte(bitStream)
  265. out[outP+1] = byte(bitStream >> 8)
  266. outP += 2
  267. bitStream >>= 16
  268. bitCount -= 16
  269. }
  270. }
  271. out[outP] = byte(bitStream)
  272. out[outP+1] = byte(bitStream >> 8)
  273. outP += (bitCount + 7) / 8
  274. if charnum > s.symbolLen {
  275. return errors.New("internal error: charnum > s.symbolLen")
  276. }
  277. s.Out = out[:outP]
  278. return nil
  279. }
  280. // symbolTransform contains the state transform for a symbol.
  281. type symbolTransform struct {
  282. deltaFindState int32
  283. deltaNbBits uint32
  284. }
  285. // String prints values as a human readable string.
  286. func (s symbolTransform) String() string {
  287. return fmt.Sprintf("dnbits: %08x, fs:%d", s.deltaNbBits, s.deltaFindState)
  288. }
  289. // cTable contains tables used for compression.
  290. type cTable struct {
  291. tableSymbol []byte
  292. stateTable []uint16
  293. symbolTT []symbolTransform
  294. }
  295. // allocCtable will allocate tables needed for compression.
  296. // If existing tables a re big enough, they are simply re-used.
  297. func (s *Scratch) allocCtable() {
  298. tableSize := 1 << s.actualTableLog
  299. // get tableSymbol that is big enough.
  300. if cap(s.ct.tableSymbol) < tableSize {
  301. s.ct.tableSymbol = make([]byte, tableSize)
  302. }
  303. s.ct.tableSymbol = s.ct.tableSymbol[:tableSize]
  304. ctSize := tableSize
  305. if cap(s.ct.stateTable) < ctSize {
  306. s.ct.stateTable = make([]uint16, ctSize)
  307. }
  308. s.ct.stateTable = s.ct.stateTable[:ctSize]
  309. if cap(s.ct.symbolTT) < 256 {
  310. s.ct.symbolTT = make([]symbolTransform, 256)
  311. }
  312. s.ct.symbolTT = s.ct.symbolTT[:256]
  313. }
  314. // buildCTable will populate the compression table so it is ready to be used.
  315. func (s *Scratch) buildCTable() error {
  316. tableSize := uint32(1 << s.actualTableLog)
  317. highThreshold := tableSize - 1
  318. var cumul [maxSymbolValue + 2]int16
  319. s.allocCtable()
  320. tableSymbol := s.ct.tableSymbol[:tableSize]
  321. // symbol start positions
  322. {
  323. cumul[0] = 0
  324. for ui, v := range s.norm[:s.symbolLen-1] {
  325. u := byte(ui) // one less than reference
  326. if v == -1 {
  327. // Low proba symbol
  328. cumul[u+1] = cumul[u] + 1
  329. tableSymbol[highThreshold] = u
  330. highThreshold--
  331. } else {
  332. cumul[u+1] = cumul[u] + v
  333. }
  334. }
  335. // Encode last symbol separately to avoid overflowing u
  336. u := int(s.symbolLen - 1)
  337. v := s.norm[s.symbolLen-1]
  338. if v == -1 {
  339. // Low proba symbol
  340. cumul[u+1] = cumul[u] + 1
  341. tableSymbol[highThreshold] = byte(u)
  342. highThreshold--
  343. } else {
  344. cumul[u+1] = cumul[u] + v
  345. }
  346. if uint32(cumul[s.symbolLen]) != tableSize {
  347. return fmt.Errorf("internal error: expected cumul[s.symbolLen] (%d) == tableSize (%d)", cumul[s.symbolLen], tableSize)
  348. }
  349. cumul[s.symbolLen] = int16(tableSize) + 1
  350. }
  351. // Spread symbols
  352. s.zeroBits = false
  353. {
  354. step := tableStep(tableSize)
  355. tableMask := tableSize - 1
  356. var position uint32
  357. // if any symbol > largeLimit, we may have 0 bits output.
  358. largeLimit := int16(1 << (s.actualTableLog - 1))
  359. for ui, v := range s.norm[:s.symbolLen] {
  360. symbol := byte(ui)
  361. if v > largeLimit {
  362. s.zeroBits = true
  363. }
  364. for nbOccurrences := int16(0); nbOccurrences < v; nbOccurrences++ {
  365. tableSymbol[position] = symbol
  366. position = (position + step) & tableMask
  367. for position > highThreshold {
  368. position = (position + step) & tableMask
  369. } /* Low proba area */
  370. }
  371. }
  372. // Check if we have gone through all positions
  373. if position != 0 {
  374. return errors.New("position!=0")
  375. }
  376. }
  377. // Build table
  378. table := s.ct.stateTable
  379. {
  380. tsi := int(tableSize)
  381. for u, v := range tableSymbol {
  382. // TableU16 : sorted by symbol order; gives next state value
  383. table[cumul[v]] = uint16(tsi + u)
  384. cumul[v]++
  385. }
  386. }
  387. // Build Symbol Transformation Table
  388. {
  389. total := int16(0)
  390. symbolTT := s.ct.symbolTT[:s.symbolLen]
  391. tableLog := s.actualTableLog
  392. tl := (uint32(tableLog) << 16) - (1 << tableLog)
  393. for i, v := range s.norm[:s.symbolLen] {
  394. switch v {
  395. case 0:
  396. case -1, 1:
  397. symbolTT[i].deltaNbBits = tl
  398. symbolTT[i].deltaFindState = int32(total - 1)
  399. total++
  400. default:
  401. maxBitsOut := uint32(tableLog) - highBits(uint32(v-1))
  402. minStatePlus := uint32(v) << maxBitsOut
  403. symbolTT[i].deltaNbBits = (maxBitsOut << 16) - minStatePlus
  404. symbolTT[i].deltaFindState = int32(total - v)
  405. total += v
  406. }
  407. }
  408. if total != int16(tableSize) {
  409. return fmt.Errorf("total mismatch %d (got) != %d (want)", total, tableSize)
  410. }
  411. }
  412. return nil
  413. }
  414. // countSimple will create a simple histogram in s.count.
  415. // Returns the biggest count.
  416. // Does not update s.clearCount.
  417. func (s *Scratch) countSimple(in []byte) (max int) {
  418. for _, v := range in {
  419. s.count[v]++
  420. }
  421. m, symlen := uint32(0), s.symbolLen
  422. for i, v := range s.count[:] {
  423. if v == 0 {
  424. continue
  425. }
  426. if v > m {
  427. m = v
  428. }
  429. symlen = uint16(i) + 1
  430. }
  431. s.symbolLen = symlen
  432. return int(m)
  433. }
  434. // minTableLog provides the minimum logSize to safely represent a distribution.
  435. func (s *Scratch) minTableLog() uint8 {
  436. minBitsSrc := highBits(uint32(s.br.remain()-1)) + 1
  437. minBitsSymbols := highBits(uint32(s.symbolLen-1)) + 2
  438. if minBitsSrc < minBitsSymbols {
  439. return uint8(minBitsSrc)
  440. }
  441. return uint8(minBitsSymbols)
  442. }
  443. // optimalTableLog calculates and sets the optimal tableLog in s.actualTableLog
  444. func (s *Scratch) optimalTableLog() {
  445. tableLog := s.TableLog
  446. minBits := s.minTableLog()
  447. maxBitsSrc := uint8(highBits(uint32(s.br.remain()-1))) - 2
  448. if maxBitsSrc < tableLog {
  449. // Accuracy can be reduced
  450. tableLog = maxBitsSrc
  451. }
  452. if minBits > tableLog {
  453. tableLog = minBits
  454. }
  455. // Need a minimum to safely represent all symbol values
  456. if tableLog < minTablelog {
  457. tableLog = minTablelog
  458. }
  459. if tableLog > maxTableLog {
  460. tableLog = maxTableLog
  461. }
  462. s.actualTableLog = tableLog
  463. }
  464. var rtbTable = [...]uint32{0, 473195, 504333, 520860, 550000, 700000, 750000, 830000}
  465. // normalizeCount will normalize the count of the symbols so
  466. // the total is equal to the table size.
  467. func (s *Scratch) normalizeCount() error {
  468. var (
  469. tableLog = s.actualTableLog
  470. scale = 62 - uint64(tableLog)
  471. step = (1 << 62) / uint64(s.br.remain())
  472. vStep = uint64(1) << (scale - 20)
  473. stillToDistribute = int16(1 << tableLog)
  474. largest int
  475. largestP int16
  476. lowThreshold = (uint32)(s.br.remain() >> tableLog)
  477. )
  478. for i, cnt := range s.count[:s.symbolLen] {
  479. // already handled
  480. // if (count[s] == s.length) return 0; /* rle special case */
  481. if cnt == 0 {
  482. s.norm[i] = 0
  483. continue
  484. }
  485. if cnt <= lowThreshold {
  486. s.norm[i] = -1
  487. stillToDistribute--
  488. } else {
  489. proba := (int16)((uint64(cnt) * step) >> scale)
  490. if proba < 8 {
  491. restToBeat := vStep * uint64(rtbTable[proba])
  492. v := uint64(cnt)*step - (uint64(proba) << scale)
  493. if v > restToBeat {
  494. proba++
  495. }
  496. }
  497. if proba > largestP {
  498. largestP = proba
  499. largest = i
  500. }
  501. s.norm[i] = proba
  502. stillToDistribute -= proba
  503. }
  504. }
  505. if -stillToDistribute >= (s.norm[largest] >> 1) {
  506. // corner case, need another normalization method
  507. return s.normalizeCount2()
  508. }
  509. s.norm[largest] += stillToDistribute
  510. return nil
  511. }
  512. // Secondary normalization method.
  513. // To be used when primary method fails.
  514. func (s *Scratch) normalizeCount2() error {
  515. const notYetAssigned = -2
  516. var (
  517. distributed uint32
  518. total = uint32(s.br.remain())
  519. tableLog = s.actualTableLog
  520. lowThreshold = total >> tableLog
  521. lowOne = (total * 3) >> (tableLog + 1)
  522. )
  523. for i, cnt := range s.count[:s.symbolLen] {
  524. if cnt == 0 {
  525. s.norm[i] = 0
  526. continue
  527. }
  528. if cnt <= lowThreshold {
  529. s.norm[i] = -1
  530. distributed++
  531. total -= cnt
  532. continue
  533. }
  534. if cnt <= lowOne {
  535. s.norm[i] = 1
  536. distributed++
  537. total -= cnt
  538. continue
  539. }
  540. s.norm[i] = notYetAssigned
  541. }
  542. toDistribute := (1 << tableLog) - distributed
  543. if (total / toDistribute) > lowOne {
  544. // risk of rounding to zero
  545. lowOne = (total * 3) / (toDistribute * 2)
  546. for i, cnt := range s.count[:s.symbolLen] {
  547. if (s.norm[i] == notYetAssigned) && (cnt <= lowOne) {
  548. s.norm[i] = 1
  549. distributed++
  550. total -= cnt
  551. continue
  552. }
  553. }
  554. toDistribute = (1 << tableLog) - distributed
  555. }
  556. if distributed == uint32(s.symbolLen)+1 {
  557. // all values are pretty poor;
  558. // probably incompressible data (should have already been detected);
  559. // find max, then give all remaining points to max
  560. var maxV int
  561. var maxC uint32
  562. for i, cnt := range s.count[:s.symbolLen] {
  563. if cnt > maxC {
  564. maxV = i
  565. maxC = cnt
  566. }
  567. }
  568. s.norm[maxV] += int16(toDistribute)
  569. return nil
  570. }
  571. if total == 0 {
  572. // all of the symbols were low enough for the lowOne or lowThreshold
  573. for i := uint32(0); toDistribute > 0; i = (i + 1) % (uint32(s.symbolLen)) {
  574. if s.norm[i] > 0 {
  575. toDistribute--
  576. s.norm[i]++
  577. }
  578. }
  579. return nil
  580. }
  581. var (
  582. vStepLog = 62 - uint64(tableLog)
  583. mid = uint64((1 << (vStepLog - 1)) - 1)
  584. rStep = (((1 << vStepLog) * uint64(toDistribute)) + mid) / uint64(total) // scale on remaining
  585. tmpTotal = mid
  586. )
  587. for i, cnt := range s.count[:s.symbolLen] {
  588. if s.norm[i] == notYetAssigned {
  589. var (
  590. end = tmpTotal + uint64(cnt)*rStep
  591. sStart = uint32(tmpTotal >> vStepLog)
  592. sEnd = uint32(end >> vStepLog)
  593. weight = sEnd - sStart
  594. )
  595. if weight < 1 {
  596. return errors.New("weight < 1")
  597. }
  598. s.norm[i] = int16(weight)
  599. tmpTotal = end
  600. }
  601. }
  602. return nil
  603. }
  604. // validateNorm validates the normalized histogram table.
  605. func (s *Scratch) validateNorm() (err error) {
  606. var total int
  607. for _, v := range s.norm[:s.symbolLen] {
  608. if v >= 0 {
  609. total += int(v)
  610. } else {
  611. total -= int(v)
  612. }
  613. }
  614. defer func() {
  615. if err == nil {
  616. return
  617. }
  618. fmt.Printf("selected TableLog: %d, Symbol length: %d\n", s.actualTableLog, s.symbolLen)
  619. for i, v := range s.norm[:s.symbolLen] {
  620. fmt.Printf("%3d: %5d -> %4d \n", i, s.count[i], v)
  621. }
  622. }()
  623. if total != (1 << s.actualTableLog) {
  624. return fmt.Errorf("warning: Total == %d != %d", total, 1<<s.actualTableLog)
  625. }
  626. for i, v := range s.count[s.symbolLen:] {
  627. if v != 0 {
  628. return fmt.Errorf("warning: Found symbol out of range, %d after cut", i)
  629. }
  630. }
  631. return nil
  632. }