react / wstein / node_modules / browserify / node_modules / browserify-zlib / node_modules / pako / lib / zlib / trees.js
80549 views'use strict';123var utils = require('../utils/common');45/* Public constants ==========================================================*/6/* ===========================================================================*/789//var Z_FILTERED = 1;10//var Z_HUFFMAN_ONLY = 2;11//var Z_RLE = 3;12var Z_FIXED = 4;13//var Z_DEFAULT_STRATEGY = 0;1415/* Possible values of the data_type field (though see inflate()) */16var Z_BINARY = 0;17var Z_TEXT = 1;18//var Z_ASCII = 1; // = Z_TEXT19var Z_UNKNOWN = 2;2021/*============================================================================*/222324function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }2526// From zutil.h2728var STORED_BLOCK = 0;29var STATIC_TREES = 1;30var DYN_TREES = 2;31/* The three kinds of block type */3233var MIN_MATCH = 3;34var MAX_MATCH = 258;35/* The minimum and maximum match lengths */3637// From deflate.h38/* ===========================================================================39* Internal compression state.40*/4142var LENGTH_CODES = 29;43/* number of length codes, not counting the special END_BLOCK code */4445var LITERALS = 256;46/* number of literal bytes 0..255 */4748var L_CODES = LITERALS + 1 + LENGTH_CODES;49/* number of Literal or Length codes, including the END_BLOCK code */5051var D_CODES = 30;52/* number of distance codes */5354var BL_CODES = 19;55/* number of codes used to transfer the bit lengths */5657var HEAP_SIZE = 2*L_CODES + 1;58/* maximum heap size */5960var MAX_BITS = 15;61/* All codes must not exceed MAX_BITS bits */6263var Buf_size = 16;64/* size of bit buffer in bi_buf */656667/* ===========================================================================68* Constants69*/7071var MAX_BL_BITS = 7;72/* Bit length codes must not exceed MAX_BL_BITS bits */7374var END_BLOCK = 256;75/* end of block literal code */7677var REP_3_6 = 16;78/* repeat previous bit length 3-6 times (2 bits of repeat count) */7980var REPZ_3_10 = 17;81/* repeat a zero length 3-10 times (3 bits of repeat count) */8283var REPZ_11_138 = 18;84/* repeat a zero length 11-138 times (7 bits of repeat count) */8586var extra_lbits = /* extra bits for each length code */87[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];8889var extra_dbits = /* extra bits for each distance code */90[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];9192var extra_blbits = /* extra bits for each bit length code */93[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];9495var bl_order =96[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];97/* The lengths of the bit length codes are sent in order of decreasing98* probability, to avoid transmitting the lengths for unused bit length codes.99*/100101/* ===========================================================================102* Local data. These are initialized only once.103*/104105// We pre-fill arrays with 0 to avoid uninitialized gaps106107var DIST_CODE_LEN = 512; /* see definition of array dist_code below */108109// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1110var static_ltree = new Array((L_CODES+2) * 2);111zero(static_ltree);112/* The static literal tree. Since the bit lengths are imposed, there is no113* need for the L_CODES extra codes used during heap construction. However114* The codes 286 and 287 are needed to build a canonical tree (see _tr_init115* below).116*/117118var static_dtree = new Array(D_CODES * 2);119zero(static_dtree);120/* The static distance tree. (Actually a trivial tree since all codes use121* 5 bits.)122*/123124var _dist_code = new Array(DIST_CODE_LEN);125zero(_dist_code);126/* Distance codes. The first 256 values correspond to the distances127* 3 .. 258, the last 256 values correspond to the top 8 bits of128* the 15 bit distances.129*/130131var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);132zero(_length_code);133/* length code for each normalized match length (0 == MIN_MATCH) */134135var base_length = new Array(LENGTH_CODES);136zero(base_length);137/* First normalized length for each code (0 = MIN_MATCH) */138139var base_dist = new Array(D_CODES);140zero(base_dist);141/* First normalized distance for each code (0 = distance of 1) */142143144var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {145146this.static_tree = static_tree; /* static tree or NULL */147this.extra_bits = extra_bits; /* extra bits for each code or NULL */148this.extra_base = extra_base; /* base index for extra_bits */149this.elems = elems; /* max number of elements in the tree */150this.max_length = max_length; /* max bit length for the codes */151152// show if `static_tree` has data or dummy - needed for monomorphic objects153this.has_stree = static_tree && static_tree.length;154};155156157var static_l_desc;158var static_d_desc;159var static_bl_desc;160161162var TreeDesc = function(dyn_tree, stat_desc) {163this.dyn_tree = dyn_tree; /* the dynamic tree */164this.max_code = 0; /* largest code with non zero frequency */165this.stat_desc = stat_desc; /* the corresponding static tree */166};167168169170function d_code(dist) {171return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];172}173174175/* ===========================================================================176* Output a short LSB first on the stream.177* IN assertion: there is enough room in pendingBuf.178*/179function put_short (s, w) {180// put_byte(s, (uch)((w) & 0xff));181// put_byte(s, (uch)((ush)(w) >> 8));182s.pending_buf[s.pending++] = (w) & 0xff;183s.pending_buf[s.pending++] = (w >>> 8) & 0xff;184}185186187/* ===========================================================================188* Send a value on a given number of bits.189* IN assertion: length <= 16 and value fits in length bits.190*/191function send_bits(s, value, length) {192if (s.bi_valid > (Buf_size - length)) {193s.bi_buf |= (value << s.bi_valid) & 0xffff;194put_short(s, s.bi_buf);195s.bi_buf = value >> (Buf_size - s.bi_valid);196s.bi_valid += length - Buf_size;197} else {198s.bi_buf |= (value << s.bi_valid) & 0xffff;199s.bi_valid += length;200}201}202203204function send_code(s, c, tree) {205send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);206}207208209/* ===========================================================================210* Reverse the first len bits of a code, using straightforward code (a faster211* method would use a table)212* IN assertion: 1 <= len <= 15213*/214function bi_reverse(code, len) {215var res = 0;216do {217res |= code & 1;218code >>>= 1;219res <<= 1;220} while (--len > 0);221return res >>> 1;222}223224225/* ===========================================================================226* Flush the bit buffer, keeping at most 7 bits in it.227*/228function bi_flush(s) {229if (s.bi_valid === 16) {230put_short(s, s.bi_buf);231s.bi_buf = 0;232s.bi_valid = 0;233234} else if (s.bi_valid >= 8) {235s.pending_buf[s.pending++] = s.bi_buf & 0xff;236s.bi_buf >>= 8;237s.bi_valid -= 8;238}239}240241242/* ===========================================================================243* Compute the optimal bit lengths for a tree and update the total bit length244* for the current block.245* IN assertion: the fields freq and dad are set, heap[heap_max] and246* above are the tree nodes sorted by increasing frequency.247* OUT assertions: the field len is set to the optimal bit length, the248* array bl_count contains the frequencies for each bit length.249* The length opt_len is updated; static_len is also updated if stree is250* not null.251*/252function gen_bitlen(s, desc)253// deflate_state *s;254// tree_desc *desc; /* the tree descriptor */255{256var tree = desc.dyn_tree;257var max_code = desc.max_code;258var stree = desc.stat_desc.static_tree;259var has_stree = desc.stat_desc.has_stree;260var extra = desc.stat_desc.extra_bits;261var base = desc.stat_desc.extra_base;262var max_length = desc.stat_desc.max_length;263var h; /* heap index */264var n, m; /* iterate over the tree elements */265var bits; /* bit length */266var xbits; /* extra bits */267var f; /* frequency */268var overflow = 0; /* number of elements with bit length too large */269270for (bits = 0; bits <= MAX_BITS; bits++) {271s.bl_count[bits] = 0;272}273274/* In a first pass, compute the optimal bit lengths (which may275* overflow in the case of the bit length tree).276*/277tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */278279for (h = s.heap_max+1; h < HEAP_SIZE; h++) {280n = s.heap[h];281bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;282if (bits > max_length) {283bits = max_length;284overflow++;285}286tree[n*2 + 1]/*.Len*/ = bits;287/* We overwrite tree[n].Dad which is no longer needed */288289if (n > max_code) { continue; } /* not a leaf node */290291s.bl_count[bits]++;292xbits = 0;293if (n >= base) {294xbits = extra[n-base];295}296f = tree[n * 2]/*.Freq*/;297s.opt_len += f * (bits + xbits);298if (has_stree) {299s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);300}301}302if (overflow === 0) { return; }303304// Trace((stderr,"\nbit length overflow\n"));305/* This happens for example on obj2 and pic of the Calgary corpus */306307/* Find the first bit length which could increase: */308do {309bits = max_length-1;310while (s.bl_count[bits] === 0) { bits--; }311s.bl_count[bits]--; /* move one leaf down the tree */312s.bl_count[bits+1] += 2; /* move one overflow item as its brother */313s.bl_count[max_length]--;314/* The brother of the overflow item also moves one step up,315* but this does not affect bl_count[max_length]316*/317overflow -= 2;318} while (overflow > 0);319320/* Now recompute all bit lengths, scanning in increasing frequency.321* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all322* lengths instead of fixing only the wrong ones. This idea is taken323* from 'ar' written by Haruhiko Okumura.)324*/325for (bits = max_length; bits !== 0; bits--) {326n = s.bl_count[bits];327while (n !== 0) {328m = s.heap[--h];329if (m > max_code) { continue; }330if (tree[m*2 + 1]/*.Len*/ !== bits) {331// Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));332s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;333tree[m*2 + 1]/*.Len*/ = bits;334}335n--;336}337}338}339340341/* ===========================================================================342* Generate the codes for a given tree and bit counts (which need not be343* optimal).344* IN assertion: the array bl_count contains the bit length statistics for345* the given tree and the field len is set for all tree elements.346* OUT assertion: the field code is set for all tree elements of non347* zero code length.348*/349function gen_codes(tree, max_code, bl_count)350// ct_data *tree; /* the tree to decorate */351// int max_code; /* largest code with non zero frequency */352// ushf *bl_count; /* number of codes at each bit length */353{354var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */355var code = 0; /* running code value */356var bits; /* bit index */357var n; /* code index */358359/* The distribution counts are first used to generate the code values360* without bit reversal.361*/362for (bits = 1; bits <= MAX_BITS; bits++) {363next_code[bits] = code = (code + bl_count[bits-1]) << 1;364}365/* Check that the bit counts in bl_count are consistent. The last code366* must be all ones.367*/368//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,369// "inconsistent bit counts");370//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));371372for (n = 0; n <= max_code; n++) {373var len = tree[n*2 + 1]/*.Len*/;374if (len === 0) { continue; }375/* Now reverse the bits */376tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);377378//Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",379// n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));380}381}382383384/* ===========================================================================385* Initialize the various 'constant' tables.386*/387function tr_static_init() {388var n; /* iterates over tree elements */389var bits; /* bit counter */390var length; /* length value */391var code; /* code value */392var dist; /* distance index */393var bl_count = new Array(MAX_BITS+1);394/* number of codes at each bit length for an optimal tree */395396// do check in _tr_init()397//if (static_init_done) return;398399/* For some embedded targets, global variables are not initialized: */400/*#ifdef NO_INIT_GLOBAL_POINTERS401static_l_desc.static_tree = static_ltree;402static_l_desc.extra_bits = extra_lbits;403static_d_desc.static_tree = static_dtree;404static_d_desc.extra_bits = extra_dbits;405static_bl_desc.extra_bits = extra_blbits;406#endif*/407408/* Initialize the mapping length (0..255) -> length code (0..28) */409length = 0;410for (code = 0; code < LENGTH_CODES-1; code++) {411base_length[code] = length;412for (n = 0; n < (1<<extra_lbits[code]); n++) {413_length_code[length++] = code;414}415}416//Assert (length == 256, "tr_static_init: length != 256");417/* Note that the length 255 (match length 258) can be represented418* in two different ways: code 284 + 5 bits or code 285, so we419* overwrite length_code[255] to use the best encoding:420*/421_length_code[length-1] = code;422423/* Initialize the mapping dist (0..32K) -> dist code (0..29) */424dist = 0;425for (code = 0 ; code < 16; code++) {426base_dist[code] = dist;427for (n = 0; n < (1<<extra_dbits[code]); n++) {428_dist_code[dist++] = code;429}430}431//Assert (dist == 256, "tr_static_init: dist != 256");432dist >>= 7; /* from now on, all distances are divided by 128 */433for ( ; code < D_CODES; code++) {434base_dist[code] = dist << 7;435for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {436_dist_code[256 + dist++] = code;437}438}439//Assert (dist == 256, "tr_static_init: 256+dist != 512");440441/* Construct the codes of the static literal tree */442for (bits = 0; bits <= MAX_BITS; bits++) {443bl_count[bits] = 0;444}445446n = 0;447while (n <= 143) {448static_ltree[n*2 + 1]/*.Len*/ = 8;449n++;450bl_count[8]++;451}452while (n <= 255) {453static_ltree[n*2 + 1]/*.Len*/ = 9;454n++;455bl_count[9]++;456}457while (n <= 279) {458static_ltree[n*2 + 1]/*.Len*/ = 7;459n++;460bl_count[7]++;461}462while (n <= 287) {463static_ltree[n*2 + 1]/*.Len*/ = 8;464n++;465bl_count[8]++;466}467/* Codes 286 and 287 do not exist, but we must include them in the468* tree construction to get a canonical Huffman tree (longest code469* all ones)470*/471gen_codes(static_ltree, L_CODES+1, bl_count);472473/* The static distance tree is trivial: */474for (n = 0; n < D_CODES; n++) {475static_dtree[n*2 + 1]/*.Len*/ = 5;476static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);477}478479// Now data ready and we can init static trees480static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);481static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);482static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);483484//static_init_done = true;485}486487488/* ===========================================================================489* Initialize a new block.490*/491function init_block(s) {492var n; /* iterates over tree elements */493494/* Initialize the trees. */495for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }496for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }497for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }498499s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;500s.opt_len = s.static_len = 0;501s.last_lit = s.matches = 0;502}503504505/* ===========================================================================506* Flush the bit buffer and align the output on a byte boundary507*/508function bi_windup(s)509{510if (s.bi_valid > 8) {511put_short(s, s.bi_buf);512} else if (s.bi_valid > 0) {513//put_byte(s, (Byte)s->bi_buf);514s.pending_buf[s.pending++] = s.bi_buf;515}516s.bi_buf = 0;517s.bi_valid = 0;518}519520/* ===========================================================================521* Copy a stored block, storing first the length and its522* one's complement if requested.523*/524function copy_block(s, buf, len, header)525//DeflateState *s;526//charf *buf; /* the input data */527//unsigned len; /* its length */528//int header; /* true if block header must be written */529{530bi_windup(s); /* align on byte boundary */531532if (header) {533put_short(s, len);534put_short(s, ~len);535}536// while (len--) {537// put_byte(s, *buf++);538// }539utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);540s.pending += len;541}542543/* ===========================================================================544* Compares to subtrees, using the tree depth as tie breaker when545* the subtrees have equal frequency. This minimizes the worst case length.546*/547function smaller(tree, n, m, depth) {548var _n2 = n*2;549var _m2 = m*2;550return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||551(tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));552}553554/* ===========================================================================555* Restore the heap property by moving down the tree starting at node k,556* exchanging a node with the smallest of its two sons if necessary, stopping557* when the heap property is re-established (each father smaller than its558* two sons).559*/560function pqdownheap(s, tree, k)561// deflate_state *s;562// ct_data *tree; /* the tree to restore */563// int k; /* node to move down */564{565var v = s.heap[k];566var j = k << 1; /* left son of k */567while (j <= s.heap_len) {568/* Set j to the smallest of the two sons: */569if (j < s.heap_len &&570smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {571j++;572}573/* Exit if v is smaller than both sons */574if (smaller(tree, v, s.heap[j], s.depth)) { break; }575576/* Exchange v with the smallest son */577s.heap[k] = s.heap[j];578k = j;579580/* And continue down the tree, setting j to the left son of k */581j <<= 1;582}583s.heap[k] = v;584}585586587// inlined manually588// var SMALLEST = 1;589590/* ===========================================================================591* Send the block data compressed using the given Huffman trees592*/593function compress_block(s, ltree, dtree)594// deflate_state *s;595// const ct_data *ltree; /* literal tree */596// const ct_data *dtree; /* distance tree */597{598var dist; /* distance of matched string */599var lc; /* match length or unmatched char (if dist == 0) */600var lx = 0; /* running index in l_buf */601var code; /* the code to send */602var extra; /* number of extra bits to send */603604if (s.last_lit !== 0) {605do {606dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);607lc = s.pending_buf[s.l_buf + lx];608lx++;609610if (dist === 0) {611send_code(s, lc, ltree); /* send a literal byte */612//Tracecv(isgraph(lc), (stderr," '%c' ", lc));613} else {614/* Here, lc is the match length - MIN_MATCH */615code = _length_code[lc];616send_code(s, code+LITERALS+1, ltree); /* send the length code */617extra = extra_lbits[code];618if (extra !== 0) {619lc -= base_length[code];620send_bits(s, lc, extra); /* send the extra length bits */621}622dist--; /* dist is now the match distance - 1 */623code = d_code(dist);624//Assert (code < D_CODES, "bad d_code");625626send_code(s, code, dtree); /* send the distance code */627extra = extra_dbits[code];628if (extra !== 0) {629dist -= base_dist[code];630send_bits(s, dist, extra); /* send the extra distance bits */631}632} /* literal or match pair ? */633634/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */635//Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,636// "pendingBuf overflow");637638} while (lx < s.last_lit);639}640641send_code(s, END_BLOCK, ltree);642}643644645/* ===========================================================================646* Construct one Huffman tree and assigns the code bit strings and lengths.647* Update the total bit length for the current block.648* IN assertion: the field freq is set for all tree elements.649* OUT assertions: the fields len and code are set to the optimal bit length650* and corresponding code. The length opt_len is updated; static_len is651* also updated if stree is not null. The field max_code is set.652*/653function build_tree(s, desc)654// deflate_state *s;655// tree_desc *desc; /* the tree descriptor */656{657var tree = desc.dyn_tree;658var stree = desc.stat_desc.static_tree;659var has_stree = desc.stat_desc.has_stree;660var elems = desc.stat_desc.elems;661var n, m; /* iterate over heap elements */662var max_code = -1; /* largest code with non zero frequency */663var node; /* new node being created */664665/* Construct the initial heap, with least frequent element in666* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].667* heap[0] is not used.668*/669s.heap_len = 0;670s.heap_max = HEAP_SIZE;671672for (n = 0; n < elems; n++) {673if (tree[n * 2]/*.Freq*/ !== 0) {674s.heap[++s.heap_len] = max_code = n;675s.depth[n] = 0;676677} else {678tree[n*2 + 1]/*.Len*/ = 0;679}680}681682/* The pkzip format requires that at least one distance code exists,683* and that at least one bit should be sent even if there is only one684* possible code. So to avoid special checks later on we force at least685* two codes of non zero frequency.686*/687while (s.heap_len < 2) {688node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);689tree[node * 2]/*.Freq*/ = 1;690s.depth[node] = 0;691s.opt_len--;692693if (has_stree) {694s.static_len -= stree[node*2 + 1]/*.Len*/;695}696/* node is 0 or 1 so it does not have extra bits */697}698desc.max_code = max_code;699700/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,701* establish sub-heaps of increasing lengths:702*/703for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }704705/* Construct the Huffman tree by repeatedly combining the least two706* frequent nodes.707*/708node = elems; /* next internal node of the tree */709do {710//pqremove(s, tree, n); /* n = node of least frequency */711/*** pqremove ***/712n = s.heap[1/*SMALLEST*/];713s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];714pqdownheap(s, tree, 1/*SMALLEST*/);715/***/716717m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */718719s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */720s.heap[--s.heap_max] = m;721722/* Create a new node father of n and m */723tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;724s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;725tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;726727/* and insert the new node in the heap */728s.heap[1/*SMALLEST*/] = node++;729pqdownheap(s, tree, 1/*SMALLEST*/);730731} while (s.heap_len >= 2);732733s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];734735/* At this point, the fields freq and dad are set. We can now736* generate the bit lengths.737*/738gen_bitlen(s, desc);739740/* The field len is now set, we can generate the bit codes */741gen_codes(tree, max_code, s.bl_count);742}743744745/* ===========================================================================746* Scan a literal or distance tree to determine the frequencies of the codes747* in the bit length tree.748*/749function scan_tree(s, tree, max_code)750// deflate_state *s;751// ct_data *tree; /* the tree to be scanned */752// int max_code; /* and its largest code of non zero frequency */753{754var n; /* iterates over all tree elements */755var prevlen = -1; /* last emitted length */756var curlen; /* length of current code */757758var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */759760var count = 0; /* repeat count of the current code */761var max_count = 7; /* max repeat count */762var min_count = 4; /* min repeat count */763764if (nextlen === 0) {765max_count = 138;766min_count = 3;767}768tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */769770for (n = 0; n <= max_code; n++) {771curlen = nextlen;772nextlen = tree[(n+1)*2 + 1]/*.Len*/;773774if (++count < max_count && curlen === nextlen) {775continue;776777} else if (count < min_count) {778s.bl_tree[curlen * 2]/*.Freq*/ += count;779780} else if (curlen !== 0) {781782if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }783s.bl_tree[REP_3_6*2]/*.Freq*/++;784785} else if (count <= 10) {786s.bl_tree[REPZ_3_10*2]/*.Freq*/++;787788} else {789s.bl_tree[REPZ_11_138*2]/*.Freq*/++;790}791792count = 0;793prevlen = curlen;794795if (nextlen === 0) {796max_count = 138;797min_count = 3;798799} else if (curlen === nextlen) {800max_count = 6;801min_count = 3;802803} else {804max_count = 7;805min_count = 4;806}807}808}809810811/* ===========================================================================812* Send a literal or distance tree in compressed form, using the codes in813* bl_tree.814*/815function send_tree(s, tree, max_code)816// deflate_state *s;817// ct_data *tree; /* the tree to be scanned */818// int max_code; /* and its largest code of non zero frequency */819{820var n; /* iterates over all tree elements */821var prevlen = -1; /* last emitted length */822var curlen; /* length of current code */823824var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */825826var count = 0; /* repeat count of the current code */827var max_count = 7; /* max repeat count */828var min_count = 4; /* min repeat count */829830/* tree[max_code+1].Len = -1; */ /* guard already set */831if (nextlen === 0) {832max_count = 138;833min_count = 3;834}835836for (n = 0; n <= max_code; n++) {837curlen = nextlen;838nextlen = tree[(n+1)*2 + 1]/*.Len*/;839840if (++count < max_count && curlen === nextlen) {841continue;842843} else if (count < min_count) {844do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);845846} else if (curlen !== 0) {847if (curlen !== prevlen) {848send_code(s, curlen, s.bl_tree);849count--;850}851//Assert(count >= 3 && count <= 6, " 3_6?");852send_code(s, REP_3_6, s.bl_tree);853send_bits(s, count-3, 2);854855} else if (count <= 10) {856send_code(s, REPZ_3_10, s.bl_tree);857send_bits(s, count-3, 3);858859} else {860send_code(s, REPZ_11_138, s.bl_tree);861send_bits(s, count-11, 7);862}863864count = 0;865prevlen = curlen;866if (nextlen === 0) {867max_count = 138;868min_count = 3;869870} else if (curlen === nextlen) {871max_count = 6;872min_count = 3;873874} else {875max_count = 7;876min_count = 4;877}878}879}880881882/* ===========================================================================883* Construct the Huffman tree for the bit lengths and return the index in884* bl_order of the last bit length code to send.885*/886function build_bl_tree(s) {887var max_blindex; /* index of last bit length code of non zero freq */888889/* Determine the bit length frequencies for literal and distance trees */890scan_tree(s, s.dyn_ltree, s.l_desc.max_code);891scan_tree(s, s.dyn_dtree, s.d_desc.max_code);892893/* Build the bit length tree: */894build_tree(s, s.bl_desc);895/* opt_len now includes the length of the tree representations, except896* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.897*/898899/* Determine the number of bit length codes to send. The pkzip format900* requires that at least 4 bit length codes be sent. (appnote.txt says901* 3 but the actual value used is 4.)902*/903for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {904if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {905break;906}907}908/* Update opt_len to include the bit length tree and counts */909s.opt_len += 3*(max_blindex+1) + 5+5+4;910//Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",911// s->opt_len, s->static_len));912913return max_blindex;914}915916917/* ===========================================================================918* Send the header for a block using dynamic Huffman trees: the counts, the919* lengths of the bit length codes, the literal tree and the distance tree.920* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.921*/922function send_all_trees(s, lcodes, dcodes, blcodes)923// deflate_state *s;924// int lcodes, dcodes, blcodes; /* number of codes for each tree */925{926var rank; /* index in bl_order */927928//Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");929//Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,930// "too many codes");931//Tracev((stderr, "\nbl counts: "));932send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */933send_bits(s, dcodes-1, 5);934send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */935for (rank = 0; rank < blcodes; rank++) {936//Tracev((stderr, "\nbl code %2d ", bl_order[rank]));937send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);938}939//Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));940941send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */942//Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));943944send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */945//Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));946}947948949/* ===========================================================================950* Check if the data type is TEXT or BINARY, using the following algorithm:951* - TEXT if the two conditions below are satisfied:952* a) There are no non-portable control characters belonging to the953* "black list" (0..6, 14..25, 28..31).954* b) There is at least one printable character belonging to the955* "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).956* - BINARY otherwise.957* - The following partially-portable control characters form a958* "gray list" that is ignored in this detection algorithm:959* (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).960* IN assertion: the fields Freq of dyn_ltree are set.961*/962function detect_data_type(s) {963/* black_mask is the bit mask of black-listed bytes964* set bits 0..6, 14..25, and 28..31965* 0xf3ffc07f = binary 11110011111111111100000001111111966*/967var black_mask = 0xf3ffc07f;968var n;969970/* Check for non-textual ("black-listed") bytes. */971for (n = 0; n <= 31; n++, black_mask >>>= 1) {972if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {973return Z_BINARY;974}975}976977/* Check for textual ("white-listed") bytes. */978if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||979s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {980return Z_TEXT;981}982for (n = 32; n < LITERALS; n++) {983if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {984return Z_TEXT;985}986}987988/* There are no "black-listed" or "white-listed" bytes:989* this stream either is empty or has tolerated ("gray-listed") bytes only.990*/991return Z_BINARY;992}993994995var static_init_done = false;996997/* ===========================================================================998* Initialize the tree data structures for a new zlib stream.999*/1000function _tr_init(s)1001{10021003if (!static_init_done) {1004tr_static_init();1005static_init_done = true;1006}10071008s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);1009s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);1010s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);10111012s.bi_buf = 0;1013s.bi_valid = 0;10141015/* Initialize the first block of the first file: */1016init_block(s);1017}101810191020/* ===========================================================================1021* Send a stored block1022*/1023function _tr_stored_block(s, buf, stored_len, last)1024//DeflateState *s;1025//charf *buf; /* input block */1026//ulg stored_len; /* length of input block */1027//int last; /* one if this is the last block for a file */1028{1029send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */1030copy_block(s, buf, stored_len, true); /* with header */1031}103210331034/* ===========================================================================1035* Send one empty static block to give enough lookahead for inflate.1036* This takes 10 bits, of which 7 may remain in the bit buffer.1037*/1038function _tr_align(s) {1039send_bits(s, STATIC_TREES<<1, 3);1040send_code(s, END_BLOCK, static_ltree);1041bi_flush(s);1042}104310441045/* ===========================================================================1046* Determine the best encoding for the current block: dynamic trees, static1047* trees or store, and output the encoded block to the zip file.1048*/1049function _tr_flush_block(s, buf, stored_len, last)1050//DeflateState *s;1051//charf *buf; /* input block, or NULL if too old */1052//ulg stored_len; /* length of input block */1053//int last; /* one if this is the last block for a file */1054{1055var opt_lenb, static_lenb; /* opt_len and static_len in bytes */1056var max_blindex = 0; /* index of last bit length code of non zero freq */10571058/* Build the Huffman trees unless a stored block is forced */1059if (s.level > 0) {10601061/* Check if the file is binary or text */1062if (s.strm.data_type === Z_UNKNOWN) {1063s.strm.data_type = detect_data_type(s);1064}10651066/* Construct the literal and distance trees */1067build_tree(s, s.l_desc);1068// Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,1069// s->static_len));10701071build_tree(s, s.d_desc);1072// Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,1073// s->static_len));1074/* At this point, opt_len and static_len are the total bit lengths of1075* the compressed block data, excluding the tree representations.1076*/10771078/* Build the bit length tree for the above two trees, and get the index1079* in bl_order of the last bit length code to send.1080*/1081max_blindex = build_bl_tree(s);10821083/* Determine the best encoding. Compute the block lengths in bytes. */1084opt_lenb = (s.opt_len+3+7) >>> 3;1085static_lenb = (s.static_len+3+7) >>> 3;10861087// Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",1088// opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,1089// s->last_lit));10901091if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }10921093} else {1094// Assert(buf != (char*)0, "lost buf");1095opt_lenb = static_lenb = stored_len + 5; /* force a stored block */1096}10971098if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {1099/* 4: two words for the lengths */11001101/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.1102* Otherwise we can't have processed more than WSIZE input bytes since1103* the last block flush, because compression would have been1104* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to1105* transform a block into a stored block.1106*/1107_tr_stored_block(s, buf, stored_len, last);11081109} else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {11101111send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);1112compress_block(s, static_ltree, static_dtree);11131114} else {1115send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);1116send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);1117compress_block(s, s.dyn_ltree, s.dyn_dtree);1118}1119// Assert (s->compressed_len == s->bits_sent, "bad compressed size");1120/* The above check is made mod 2^32, for files larger than 512 MB1121* and uLong implemented on 32 bits.1122*/1123init_block(s);11241125if (last) {1126bi_windup(s);1127}1128// Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,1129// s->compressed_len-7*last));1130}11311132/* ===========================================================================1133* Save the match info and tally the frequency counts. Return true if1134* the current block must be flushed.1135*/1136function _tr_tally(s, dist, lc)1137// deflate_state *s;1138// unsigned dist; /* distance of matched string */1139// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */1140{1141//var out_length, in_length, dcode;11421143s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;1144s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;11451146s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;1147s.last_lit++;11481149if (dist === 0) {1150/* lc is the unmatched char */1151s.dyn_ltree[lc*2]/*.Freq*/++;1152} else {1153s.matches++;1154/* Here, lc is the match length - MIN_MATCH */1155dist--; /* dist = match distance - 1 */1156//Assert((ush)dist < (ush)MAX_DIST(s) &&1157// (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&1158// (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");11591160s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;1161s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;1162}11631164// (!) This block is disabled in zlib defailts,1165// don't enable it for binary compatibility11661167//#ifdef TRUNCATE_BLOCK1168// /* Try to guess if it is profitable to stop the current block here */1169// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {1170// /* Compute an upper bound for the compressed length */1171// out_length = s.last_lit*8;1172// in_length = s.strstart - s.block_start;1173//1174// for (dcode = 0; dcode < D_CODES; dcode++) {1175// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);1176// }1177// out_length >>>= 3;1178// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",1179// // s->last_lit, in_length, out_length,1180// // 100L - out_length*100L/in_length));1181// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {1182// return true;1183// }1184// }1185//#endif11861187return (s.last_lit === s.lit_bufsize-1);1188/* We avoid equality with lit_bufsize because of wraparound at 64K1189* on 16 bit machines and because stored blocks are restricted to1190* 64K-1 bytes.1191*/1192}11931194exports._tr_init = _tr_init;1195exports._tr_stored_block = _tr_stored_block;1196exports._tr_flush_block = _tr_flush_block;1197exports._tr_tally = _tr_tally;1198exports._tr_align = _tr_align;11991200