25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

731 lines
17 KiB

  1. package huff0
  2. import (
  3. "fmt"
  4. "math"
  5. "runtime"
  6. "sync"
  7. )
  8. // Compress1X will compress the input.
  9. // The output can be decoded using Decompress1X.
  10. // Supply a Scratch object. The scratch object contains state about re-use,
  11. // So when sharing across independent encodes, be sure to set the re-use policy.
  12. func Compress1X(in []byte, s *Scratch) (out []byte, reUsed bool, err error) {
  13. s, err = s.prepare(in)
  14. if err != nil {
  15. return nil, false, err
  16. }
  17. return compress(in, s, s.compress1X)
  18. }
  19. // Compress4X will compress the input. The input is split into 4 independent blocks
  20. // and compressed similar to Compress1X.
  21. // The output can be decoded using Decompress4X.
  22. // Supply a Scratch object. The scratch object contains state about re-use,
  23. // So when sharing across independent encodes, be sure to set the re-use policy.
  24. func Compress4X(in []byte, s *Scratch) (out []byte, reUsed bool, err error) {
  25. s, err = s.prepare(in)
  26. if err != nil {
  27. return nil, false, err
  28. }
  29. if false {
  30. // TODO: compress4Xp only slightly faster.
  31. const parallelThreshold = 8 << 10
  32. if len(in) < parallelThreshold || runtime.GOMAXPROCS(0) == 1 {
  33. return compress(in, s, s.compress4X)
  34. }
  35. return compress(in, s, s.compress4Xp)
  36. }
  37. return compress(in, s, s.compress4X)
  38. }
  39. func compress(in []byte, s *Scratch, compressor func(src []byte) ([]byte, error)) (out []byte, reUsed bool, err error) {
  40. // Nuke previous table if we cannot reuse anyway.
  41. if s.Reuse == ReusePolicyNone {
  42. s.prevTable = s.prevTable[:0]
  43. }
  44. // Create histogram, if none was provided.
  45. maxCount := s.maxCount
  46. var canReuse = false
  47. if maxCount == 0 {
  48. maxCount, canReuse = s.countSimple(in)
  49. } else {
  50. canReuse = s.canUseTable(s.prevTable)
  51. }
  52. // We want the output size to be less than this:
  53. wantSize := len(in)
  54. if s.WantLogLess > 0 {
  55. wantSize -= wantSize >> s.WantLogLess
  56. }
  57. // Reset for next run.
  58. s.clearCount = true
  59. s.maxCount = 0
  60. if maxCount >= len(in) {
  61. if maxCount > len(in) {
  62. return nil, false, fmt.Errorf("maxCount (%d) > length (%d)", maxCount, len(in))
  63. }
  64. if len(in) == 1 {
  65. return nil, false, ErrIncompressible
  66. }
  67. // One symbol, use RLE
  68. return nil, false, ErrUseRLE
  69. }
  70. if maxCount == 1 || maxCount < (len(in)>>7) {
  71. // Each symbol present maximum once or too well distributed.
  72. return nil, false, ErrIncompressible
  73. }
  74. if s.Reuse == ReusePolicyMust && !canReuse {
  75. // We must reuse, but we can't.
  76. return nil, false, ErrIncompressible
  77. }
  78. if (s.Reuse == ReusePolicyPrefer || s.Reuse == ReusePolicyMust) && canReuse {
  79. keepTable := s.cTable
  80. keepTL := s.actualTableLog
  81. s.cTable = s.prevTable
  82. s.actualTableLog = s.prevTableLog
  83. s.Out, err = compressor(in)
  84. s.cTable = keepTable
  85. s.actualTableLog = keepTL
  86. if err == nil && len(s.Out) < wantSize {
  87. s.OutData = s.Out
  88. return s.Out, true, nil
  89. }
  90. if s.Reuse == ReusePolicyMust {
  91. return nil, false, ErrIncompressible
  92. }
  93. // Do not attempt to re-use later.
  94. s.prevTable = s.prevTable[:0]
  95. }
  96. // Calculate new table.
  97. err = s.buildCTable()
  98. if err != nil {
  99. return nil, false, err
  100. }
  101. if false && !s.canUseTable(s.cTable) {
  102. panic("invalid table generated")
  103. }
  104. if s.Reuse == ReusePolicyAllow && canReuse {
  105. hSize := len(s.Out)
  106. oldSize := s.prevTable.estimateSize(s.count[:s.symbolLen])
  107. newSize := s.cTable.estimateSize(s.count[:s.symbolLen])
  108. if oldSize <= hSize+newSize || hSize+12 >= wantSize {
  109. // Retain cTable even if we re-use.
  110. keepTable := s.cTable
  111. keepTL := s.actualTableLog
  112. s.cTable = s.prevTable
  113. s.actualTableLog = s.prevTableLog
  114. s.Out, err = compressor(in)
  115. // Restore ctable.
  116. s.cTable = keepTable
  117. s.actualTableLog = keepTL
  118. if err != nil {
  119. return nil, false, err
  120. }
  121. if len(s.Out) >= wantSize {
  122. return nil, false, ErrIncompressible
  123. }
  124. s.OutData = s.Out
  125. return s.Out, true, nil
  126. }
  127. }
  128. // Use new table
  129. err = s.cTable.write(s)
  130. if err != nil {
  131. s.OutTable = nil
  132. return nil, false, err
  133. }
  134. s.OutTable = s.Out
  135. // Compress using new table
  136. s.Out, err = compressor(in)
  137. if err != nil {
  138. s.OutTable = nil
  139. return nil, false, err
  140. }
  141. if len(s.Out) >= wantSize {
  142. s.OutTable = nil
  143. return nil, false, ErrIncompressible
  144. }
  145. // Move current table into previous.
  146. s.prevTable, s.prevTableLog, s.cTable = s.cTable, s.actualTableLog, s.prevTable[:0]
  147. s.OutData = s.Out[len(s.OutTable):]
  148. return s.Out, false, nil
  149. }
  150. // EstimateSizes will estimate the data sizes
  151. func EstimateSizes(in []byte, s *Scratch) (tableSz, dataSz, reuseSz int, err error) {
  152. s, err = s.prepare(in)
  153. if err != nil {
  154. return 0, 0, 0, err
  155. }
  156. // Create histogram, if none was provided.
  157. tableSz, dataSz, reuseSz = -1, -1, -1
  158. maxCount := s.maxCount
  159. var canReuse = false
  160. if maxCount == 0 {
  161. maxCount, canReuse = s.countSimple(in)
  162. } else {
  163. canReuse = s.canUseTable(s.prevTable)
  164. }
  165. // We want the output size to be less than this:
  166. wantSize := len(in)
  167. if s.WantLogLess > 0 {
  168. wantSize -= wantSize >> s.WantLogLess
  169. }
  170. // Reset for next run.
  171. s.clearCount = true
  172. s.maxCount = 0
  173. if maxCount >= len(in) {
  174. if maxCount > len(in) {
  175. return 0, 0, 0, fmt.Errorf("maxCount (%d) > length (%d)", maxCount, len(in))
  176. }
  177. if len(in) == 1 {
  178. return 0, 0, 0, ErrIncompressible
  179. }
  180. // One symbol, use RLE
  181. return 0, 0, 0, ErrUseRLE
  182. }
  183. if maxCount == 1 || maxCount < (len(in)>>7) {
  184. // Each symbol present maximum once or too well distributed.
  185. return 0, 0, 0, ErrIncompressible
  186. }
  187. // Calculate new table.
  188. err = s.buildCTable()
  189. if err != nil {
  190. return 0, 0, 0, err
  191. }
  192. if false && !s.canUseTable(s.cTable) {
  193. panic("invalid table generated")
  194. }
  195. tableSz, err = s.cTable.estTableSize(s)
  196. if err != nil {
  197. return 0, 0, 0, err
  198. }
  199. if canReuse {
  200. reuseSz = s.prevTable.estimateSize(s.count[:s.symbolLen])
  201. }
  202. dataSz = s.cTable.estimateSize(s.count[:s.symbolLen])
  203. // Restore
  204. return tableSz, dataSz, reuseSz, nil
  205. }
  206. func (s *Scratch) compress1X(src []byte) ([]byte, error) {
  207. return s.compress1xDo(s.Out, src)
  208. }
  209. func (s *Scratch) compress1xDo(dst, src []byte) ([]byte, error) {
  210. var bw = bitWriter{out: dst}
  211. // N is length divisible by 4.
  212. n := len(src)
  213. n -= n & 3
  214. cTable := s.cTable[:256]
  215. // Encode last bytes.
  216. for i := len(src) & 3; i > 0; i-- {
  217. bw.encSymbol(cTable, src[n+i-1])
  218. }
  219. n -= 4
  220. if s.actualTableLog <= 8 {
  221. for ; n >= 0; n -= 4 {
  222. tmp := src[n : n+4]
  223. // tmp should be len 4
  224. bw.flush32()
  225. bw.encTwoSymbols(cTable, tmp[3], tmp[2])
  226. bw.encTwoSymbols(cTable, tmp[1], tmp[0])
  227. }
  228. } else {
  229. for ; n >= 0; n -= 4 {
  230. tmp := src[n : n+4]
  231. // tmp should be len 4
  232. bw.flush32()
  233. bw.encTwoSymbols(cTable, tmp[3], tmp[2])
  234. bw.flush32()
  235. bw.encTwoSymbols(cTable, tmp[1], tmp[0])
  236. }
  237. }
  238. err := bw.close()
  239. return bw.out, err
  240. }
  241. var sixZeros [6]byte
  242. func (s *Scratch) compress4X(src []byte) ([]byte, error) {
  243. if len(src) < 12 {
  244. return nil, ErrIncompressible
  245. }
  246. segmentSize := (len(src) + 3) / 4
  247. // Add placeholder for output length
  248. offsetIdx := len(s.Out)
  249. s.Out = append(s.Out, sixZeros[:]...)
  250. for i := 0; i < 4; i++ {
  251. toDo := src
  252. if len(toDo) > segmentSize {
  253. toDo = toDo[:segmentSize]
  254. }
  255. src = src[len(toDo):]
  256. var err error
  257. idx := len(s.Out)
  258. s.Out, err = s.compress1xDo(s.Out, toDo)
  259. if err != nil {
  260. return nil, err
  261. }
  262. if len(s.Out)-idx > math.MaxUint16 {
  263. // We cannot store the size in the jump table
  264. return nil, ErrIncompressible
  265. }
  266. // Write compressed length as little endian before block.
  267. if i < 3 {
  268. // Last length is not written.
  269. length := len(s.Out) - idx
  270. s.Out[i*2+offsetIdx] = byte(length)
  271. s.Out[i*2+offsetIdx+1] = byte(length >> 8)
  272. }
  273. }
  274. return s.Out, nil
  275. }
  276. // compress4Xp will compress 4 streams using separate goroutines.
  277. func (s *Scratch) compress4Xp(src []byte) ([]byte, error) {
  278. if len(src) < 12 {
  279. return nil, ErrIncompressible
  280. }
  281. // Add placeholder for output length
  282. s.Out = s.Out[:6]
  283. segmentSize := (len(src) + 3) / 4
  284. var wg sync.WaitGroup
  285. var errs [4]error
  286. wg.Add(4)
  287. for i := 0; i < 4; i++ {
  288. toDo := src
  289. if len(toDo) > segmentSize {
  290. toDo = toDo[:segmentSize]
  291. }
  292. src = src[len(toDo):]
  293. // Separate goroutine for each block.
  294. go func(i int) {
  295. s.tmpOut[i], errs[i] = s.compress1xDo(s.tmpOut[i][:0], toDo)
  296. wg.Done()
  297. }(i)
  298. }
  299. wg.Wait()
  300. for i := 0; i < 4; i++ {
  301. if errs[i] != nil {
  302. return nil, errs[i]
  303. }
  304. o := s.tmpOut[i]
  305. if len(o) > math.MaxUint16 {
  306. // We cannot store the size in the jump table
  307. return nil, ErrIncompressible
  308. }
  309. // Write compressed length as little endian before block.
  310. if i < 3 {
  311. // Last length is not written.
  312. s.Out[i*2] = byte(len(o))
  313. s.Out[i*2+1] = byte(len(o) >> 8)
  314. }
  315. // Write output.
  316. s.Out = append(s.Out, o...)
  317. }
  318. return s.Out, nil
  319. }
  320. // countSimple will create a simple histogram in s.count.
  321. // Returns the biggest count.
  322. // Does not update s.clearCount.
  323. func (s *Scratch) countSimple(in []byte) (max int, reuse bool) {
  324. reuse = true
  325. for _, v := range in {
  326. s.count[v]++
  327. }
  328. m := uint32(0)
  329. if len(s.prevTable) > 0 {
  330. for i, v := range s.count[:] {
  331. if v > m {
  332. m = v
  333. }
  334. if v > 0 {
  335. s.symbolLen = uint16(i) + 1
  336. if i >= len(s.prevTable) {
  337. reuse = false
  338. } else {
  339. if s.prevTable[i].nBits == 0 {
  340. reuse = false
  341. }
  342. }
  343. }
  344. }
  345. return int(m), reuse
  346. }
  347. for i, v := range s.count[:] {
  348. if v > m {
  349. m = v
  350. }
  351. if v > 0 {
  352. s.symbolLen = uint16(i) + 1
  353. }
  354. }
  355. return int(m), false
  356. }
  357. func (s *Scratch) canUseTable(c cTable) bool {
  358. if len(c) < int(s.symbolLen) {
  359. return false
  360. }
  361. for i, v := range s.count[:s.symbolLen] {
  362. if v != 0 && c[i].nBits == 0 {
  363. return false
  364. }
  365. }
  366. return true
  367. }
  368. //lint:ignore U1000 used for debugging
  369. func (s *Scratch) validateTable(c cTable) bool {
  370. if len(c) < int(s.symbolLen) {
  371. return false
  372. }
  373. for i, v := range s.count[:s.symbolLen] {
  374. if v != 0 {
  375. if c[i].nBits == 0 {
  376. return false
  377. }
  378. if c[i].nBits > s.actualTableLog {
  379. return false
  380. }
  381. }
  382. }
  383. return true
  384. }
  385. // minTableLog provides the minimum logSize to safely represent a distribution.
  386. func (s *Scratch) minTableLog() uint8 {
  387. minBitsSrc := highBit32(uint32(s.br.remain())) + 1
  388. minBitsSymbols := highBit32(uint32(s.symbolLen-1)) + 2
  389. if minBitsSrc < minBitsSymbols {
  390. return uint8(minBitsSrc)
  391. }
  392. return uint8(minBitsSymbols)
  393. }
  394. // optimalTableLog calculates and sets the optimal tableLog in s.actualTableLog
  395. func (s *Scratch) optimalTableLog() {
  396. tableLog := s.TableLog
  397. minBits := s.minTableLog()
  398. maxBitsSrc := uint8(highBit32(uint32(s.br.remain()-1))) - 1
  399. if maxBitsSrc < tableLog {
  400. // Accuracy can be reduced
  401. tableLog = maxBitsSrc
  402. }
  403. if minBits > tableLog {
  404. tableLog = minBits
  405. }
  406. // Need a minimum to safely represent all symbol values
  407. if tableLog < minTablelog {
  408. tableLog = minTablelog
  409. }
  410. if tableLog > tableLogMax {
  411. tableLog = tableLogMax
  412. }
  413. s.actualTableLog = tableLog
  414. }
  415. type cTableEntry struct {
  416. val uint16
  417. nBits uint8
  418. // We have 8 bits extra
  419. }
  420. const huffNodesMask = huffNodesLen - 1
  421. func (s *Scratch) buildCTable() error {
  422. s.optimalTableLog()
  423. s.huffSort()
  424. if cap(s.cTable) < maxSymbolValue+1 {
  425. s.cTable = make([]cTableEntry, s.symbolLen, maxSymbolValue+1)
  426. } else {
  427. s.cTable = s.cTable[:s.symbolLen]
  428. for i := range s.cTable {
  429. s.cTable[i] = cTableEntry{}
  430. }
  431. }
  432. var startNode = int16(s.symbolLen)
  433. nonNullRank := s.symbolLen - 1
  434. nodeNb := startNode
  435. huffNode := s.nodes[1 : huffNodesLen+1]
  436. // This overlays the slice above, but allows "-1" index lookups.
  437. // Different from reference implementation.
  438. huffNode0 := s.nodes[0 : huffNodesLen+1]
  439. for huffNode[nonNullRank].count == 0 {
  440. nonNullRank--
  441. }
  442. lowS := int16(nonNullRank)
  443. nodeRoot := nodeNb + lowS - 1
  444. lowN := nodeNb
  445. huffNode[nodeNb].count = huffNode[lowS].count + huffNode[lowS-1].count
  446. huffNode[lowS].parent, huffNode[lowS-1].parent = uint16(nodeNb), uint16(nodeNb)
  447. nodeNb++
  448. lowS -= 2
  449. for n := nodeNb; n <= nodeRoot; n++ {
  450. huffNode[n].count = 1 << 30
  451. }
  452. // fake entry, strong barrier
  453. huffNode0[0].count = 1 << 31
  454. // create parents
  455. for nodeNb <= nodeRoot {
  456. var n1, n2 int16
  457. if huffNode0[lowS+1].count < huffNode0[lowN+1].count {
  458. n1 = lowS
  459. lowS--
  460. } else {
  461. n1 = lowN
  462. lowN++
  463. }
  464. if huffNode0[lowS+1].count < huffNode0[lowN+1].count {
  465. n2 = lowS
  466. lowS--
  467. } else {
  468. n2 = lowN
  469. lowN++
  470. }
  471. huffNode[nodeNb].count = huffNode0[n1+1].count + huffNode0[n2+1].count
  472. huffNode0[n1+1].parent, huffNode0[n2+1].parent = uint16(nodeNb), uint16(nodeNb)
  473. nodeNb++
  474. }
  475. // distribute weights (unlimited tree height)
  476. huffNode[nodeRoot].nbBits = 0
  477. for n := nodeRoot - 1; n >= startNode; n-- {
  478. huffNode[n].nbBits = huffNode[huffNode[n].parent].nbBits + 1
  479. }
  480. for n := uint16(0); n <= nonNullRank; n++ {
  481. huffNode[n].nbBits = huffNode[huffNode[n].parent].nbBits + 1
  482. }
  483. s.actualTableLog = s.setMaxHeight(int(nonNullRank))
  484. maxNbBits := s.actualTableLog
  485. // fill result into tree (val, nbBits)
  486. if maxNbBits > tableLogMax {
  487. return fmt.Errorf("internal error: maxNbBits (%d) > tableLogMax (%d)", maxNbBits, tableLogMax)
  488. }
  489. var nbPerRank [tableLogMax + 1]uint16
  490. var valPerRank [16]uint16
  491. for _, v := range huffNode[:nonNullRank+1] {
  492. nbPerRank[v.nbBits]++
  493. }
  494. // determine stating value per rank
  495. {
  496. min := uint16(0)
  497. for n := maxNbBits; n > 0; n-- {
  498. // get starting value within each rank
  499. valPerRank[n] = min
  500. min += nbPerRank[n]
  501. min >>= 1
  502. }
  503. }
  504. // push nbBits per symbol, symbol order
  505. for _, v := range huffNode[:nonNullRank+1] {
  506. s.cTable[v.symbol].nBits = v.nbBits
  507. }
  508. // assign value within rank, symbol order
  509. t := s.cTable[:s.symbolLen]
  510. for n, val := range t {
  511. nbits := val.nBits & 15
  512. v := valPerRank[nbits]
  513. t[n].val = v
  514. valPerRank[nbits] = v + 1
  515. }
  516. return nil
  517. }
  518. // huffSort will sort symbols, decreasing order.
  519. func (s *Scratch) huffSort() {
  520. type rankPos struct {
  521. base uint32
  522. current uint32
  523. }
  524. // Clear nodes
  525. nodes := s.nodes[:huffNodesLen+1]
  526. s.nodes = nodes
  527. nodes = nodes[1 : huffNodesLen+1]
  528. // Sort into buckets based on length of symbol count.
  529. var rank [32]rankPos
  530. for _, v := range s.count[:s.symbolLen] {
  531. r := highBit32(v+1) & 31
  532. rank[r].base++
  533. }
  534. // maxBitLength is log2(BlockSizeMax) + 1
  535. const maxBitLength = 18 + 1
  536. for n := maxBitLength; n > 0; n-- {
  537. rank[n-1].base += rank[n].base
  538. }
  539. for n := range rank[:maxBitLength] {
  540. rank[n].current = rank[n].base
  541. }
  542. for n, c := range s.count[:s.symbolLen] {
  543. r := (highBit32(c+1) + 1) & 31
  544. pos := rank[r].current
  545. rank[r].current++
  546. prev := nodes[(pos-1)&huffNodesMask]
  547. for pos > rank[r].base && c > prev.count {
  548. nodes[pos&huffNodesMask] = prev
  549. pos--
  550. prev = nodes[(pos-1)&huffNodesMask]
  551. }
  552. nodes[pos&huffNodesMask] = nodeElt{count: c, symbol: byte(n)}
  553. }
  554. }
  555. func (s *Scratch) setMaxHeight(lastNonNull int) uint8 {
  556. maxNbBits := s.actualTableLog
  557. huffNode := s.nodes[1 : huffNodesLen+1]
  558. //huffNode = huffNode[: huffNodesLen]
  559. largestBits := huffNode[lastNonNull].nbBits
  560. // early exit : no elt > maxNbBits
  561. if largestBits <= maxNbBits {
  562. return largestBits
  563. }
  564. totalCost := int(0)
  565. baseCost := int(1) << (largestBits - maxNbBits)
  566. n := uint32(lastNonNull)
  567. for huffNode[n].nbBits > maxNbBits {
  568. totalCost += baseCost - (1 << (largestBits - huffNode[n].nbBits))
  569. huffNode[n].nbBits = maxNbBits
  570. n--
  571. }
  572. // n stops at huffNode[n].nbBits <= maxNbBits
  573. for huffNode[n].nbBits == maxNbBits {
  574. n--
  575. }
  576. // n end at index of smallest symbol using < maxNbBits
  577. // renorm totalCost
  578. totalCost >>= largestBits - maxNbBits /* note : totalCost is necessarily a multiple of baseCost */
  579. // repay normalized cost
  580. {
  581. const noSymbol = 0xF0F0F0F0
  582. var rankLast [tableLogMax + 2]uint32
  583. for i := range rankLast[:] {
  584. rankLast[i] = noSymbol
  585. }
  586. // Get pos of last (smallest) symbol per rank
  587. {
  588. currentNbBits := maxNbBits
  589. for pos := int(n); pos >= 0; pos-- {
  590. if huffNode[pos].nbBits >= currentNbBits {
  591. continue
  592. }
  593. currentNbBits = huffNode[pos].nbBits // < maxNbBits
  594. rankLast[maxNbBits-currentNbBits] = uint32(pos)
  595. }
  596. }
  597. for totalCost > 0 {
  598. nBitsToDecrease := uint8(highBit32(uint32(totalCost))) + 1
  599. for ; nBitsToDecrease > 1; nBitsToDecrease-- {
  600. highPos := rankLast[nBitsToDecrease]
  601. lowPos := rankLast[nBitsToDecrease-1]
  602. if highPos == noSymbol {
  603. continue
  604. }
  605. if lowPos == noSymbol {
  606. break
  607. }
  608. highTotal := huffNode[highPos].count
  609. lowTotal := 2 * huffNode[lowPos].count
  610. if highTotal <= lowTotal {
  611. break
  612. }
  613. }
  614. // only triggered when no more rank 1 symbol left => find closest one (note : there is necessarily at least one !)
  615. // HUF_MAX_TABLELOG test just to please gcc 5+; but it should not be necessary
  616. // FIXME: try to remove
  617. for (nBitsToDecrease <= tableLogMax) && (rankLast[nBitsToDecrease] == noSymbol) {
  618. nBitsToDecrease++
  619. }
  620. totalCost -= 1 << (nBitsToDecrease - 1)
  621. if rankLast[nBitsToDecrease-1] == noSymbol {
  622. // this rank is no longer empty
  623. rankLast[nBitsToDecrease-1] = rankLast[nBitsToDecrease]
  624. }
  625. huffNode[rankLast[nBitsToDecrease]].nbBits++
  626. if rankLast[nBitsToDecrease] == 0 {
  627. /* special case, reached largest symbol */
  628. rankLast[nBitsToDecrease] = noSymbol
  629. } else {
  630. rankLast[nBitsToDecrease]--
  631. if huffNode[rankLast[nBitsToDecrease]].nbBits != maxNbBits-nBitsToDecrease {
  632. rankLast[nBitsToDecrease] = noSymbol /* this rank is now empty */
  633. }
  634. }
  635. }
  636. for totalCost < 0 { /* Sometimes, cost correction overshoot */
  637. if rankLast[1] == noSymbol { /* special case : no rank 1 symbol (using maxNbBits-1); let's create one from largest rank 0 (using maxNbBits) */
  638. for huffNode[n].nbBits == maxNbBits {
  639. n--
  640. }
  641. huffNode[n+1].nbBits--
  642. rankLast[1] = n + 1
  643. totalCost++
  644. continue
  645. }
  646. huffNode[rankLast[1]+1].nbBits--
  647. rankLast[1]++
  648. totalCost++
  649. }
  650. }
  651. return maxNbBits
  652. }
  653. type nodeElt struct {
  654. count uint32
  655. parent uint16
  656. symbol byte
  657. nbBits uint8
  658. }