MCPcopy Create free account
hub / github.com/9chu/LuaSTGPlus / build_tree

Function build_tree

ZLib/trees.c:617–699  ·  view source on GitHub ↗

=========================================================================== * Construct one Huffman tree and assigns the code bit strings and lengths. * Update the total bit length for the current block. * IN assertion: the field freq is set for all tree elements. * OUT assertions: the fields len and code are set to the optimal bit length * and corresponding code. The length opt_len is up

(s, desc)

Source from the content-addressed store, hash-verified

615 * also updated if stree is not null. The field max_code is set.
616 */
617local void build_tree(s, desc)
618 deflate_state *s;
619 tree_desc *desc; /* the tree descriptor */
620{
621 ct_data *tree = desc->dyn_tree;
622 const ct_data *stree = desc->stat_desc->static_tree;
623 int elems = desc->stat_desc->elems;
624 int n, m; /* iterate over heap elements */
625 int max_code = -1; /* largest code with non zero frequency */
626 int node; /* new node being created */
627
628 /* Construct the initial heap, with least frequent element in
629 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
630 * heap[0] is not used.
631 */
632 s->heap_len = 0, s->heap_max = HEAP_SIZE;
633
634 for (n = 0; n < elems; n++) {
635 if (tree[n].Freq != 0) {
636 s->heap[++(s->heap_len)] = max_code = n;
637 s->depth[n] = 0;
638 } else {
639 tree[n].Len = 0;
640 }
641 }
642
643 /* The pkzip format requires that at least one distance code exists,
644 * and that at least one bit should be sent even if there is only one
645 * possible code. So to avoid special checks later on we force at least
646 * two codes of non zero frequency.
647 */
648 while (s->heap_len < 2) {
649 node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
650 tree[node].Freq = 1;
651 s->depth[node] = 0;
652 s->opt_len--; if (stree) s->static_len -= stree[node].Len;
653 /* node is 0 or 1 so it does not have extra bits */
654 }
655 desc->max_code = max_code;
656
657 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
658 * establish sub-heaps of increasing lengths:
659 */
660 for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
661
662 /* Construct the Huffman tree by repeatedly combining the least two
663 * frequent nodes.
664 */
665 node = elems; /* next internal node of the tree */
666 do {
667 pqremove(s, tree, n); /* n = node of least frequency */
668 m = s->heap[SMALLEST]; /* m = node of next least frequency */
669
670 s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
671 s->heap[--(s->heap_max)] = m;
672
673 /* Create a new node father of n and m */
674 tree[node].Freq = tree[n].Freq + tree[m].Freq;

Callers 2

build_bl_treeFunction · 0.85
trees.cFile · 0.85

Calls 3

pqdownheapFunction · 0.85
gen_bitlenFunction · 0.85
gen_codesFunction · 0.85

Tested by

no test coverage detected