• Main Page
  • Related Pages
  • Modules
  • Namespaces
  • Data Structures
  • Files
  • File List
  • Globals

contrib/zlib/trees.c

00001 /* trees.c -- output deflated data using Huffman coding
00002  * Copyright (C) 1995-2010 Jean-loup Gailly
00003  * detect_data_type() function provided freely by Cosmin Truta, 2006
00004  * For conditions of distribution and use, see copyright notice in zlib.h
00005  */
00006 
00007 /*
00008  *  ALGORITHM
00009  *
00010  *      The "deflation" process uses several Huffman trees. The more
00011  *      common source values are represented by shorter bit sequences.
00012  *
00013  *      Each code tree is stored in a compressed form which is itself
00014  * a Huffman encoding of the lengths of all the code strings (in
00015  * ascending order by source values).  The actual code strings are
00016  * reconstructed from the lengths in the inflate process, as described
00017  * in the deflate specification.
00018  *
00019  *  REFERENCES
00020  *
00021  *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
00022  *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
00023  *
00024  *      Storer, James A.
00025  *          Data Compression:  Methods and Theory, pp. 49-50.
00026  *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
00027  *
00028  *      Sedgewick, R.
00029  *          Algorithms, p290.
00030  *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
00031  */
00032 
00033 /* @(#) $Id$ */
00034 
00035 /* #define GEN_TREES_H */
00036 
00037 #include "deflate.h"
00038 
00039 #ifdef DEBUG
00040 #  include <ctype.h>
00041 #endif
00042 
00043 /* ===========================================================================
00044  * Constants
00045  */
00046 
00047 #define MAX_BL_BITS 7
00048 /* Bit length codes must not exceed MAX_BL_BITS bits */
00049 
00050 #define END_BLOCK 256
00051 /* end of block literal code */
00052 
00053 #define REP_3_6      16
00054 /* repeat previous bit length 3-6 times (2 bits of repeat count) */
00055 
00056 #define REPZ_3_10    17
00057 /* repeat a zero length 3-10 times  (3 bits of repeat count) */
00058 
00059 #define REPZ_11_138  18
00060 /* repeat a zero length 11-138 times  (7 bits of repeat count) */
00061 
00062 local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
00063    = {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};
00064 
00065 local const int extra_dbits[D_CODES] /* extra bits for each distance code */
00066    = {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};
00067 
00068 local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
00069    = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
00070 
00071 local const uch bl_order[BL_CODES]
00072    = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
00073 /* The lengths of the bit length codes are sent in order of decreasing
00074  * probability, to avoid transmitting the lengths for unused bit length codes.
00075  */
00076 
00077 #define Buf_size (8 * 2*sizeof(char))
00078 /* Number of bits used within bi_buf. (bi_buf might be implemented on
00079  * more than 16 bits on some systems.)
00080  */
00081 
00082 /* ===========================================================================
00083  * Local data. These are initialized only once.
00084  */
00085 
00086 #define DIST_CODE_LEN  512 /* see definition of array dist_code below */
00087 
00088 #if defined(GEN_TREES_H) || !defined(STDC)
00089 /* non ANSI compilers may not accept trees.h */
00090 
00091 local ct_data static_ltree[L_CODES+2];
00092 /* The static literal tree. Since the bit lengths are imposed, there is no
00093  * need for the L_CODES extra codes used during heap construction. However
00094  * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
00095  * below).
00096  */
00097 
00098 local ct_data static_dtree[D_CODES];
00099 /* The static distance tree. (Actually a trivial tree since all codes use
00100  * 5 bits.)
00101  */
00102 
00103 uch _dist_code[DIST_CODE_LEN];
00104 /* Distance codes. The first 256 values correspond to the distances
00105  * 3 .. 258, the last 256 values correspond to the top 8 bits of
00106  * the 15 bit distances.
00107  */
00108 
00109 uch _length_code[MAX_MATCH-MIN_MATCH+1];
00110 /* length code for each normalized match length (0 == MIN_MATCH) */
00111 
00112 local int base_length[LENGTH_CODES];
00113 /* First normalized length for each code (0 = MIN_MATCH) */
00114 
00115 local int base_dist[D_CODES];
00116 /* First normalized distance for each code (0 = distance of 1) */
00117 
00118 #else
00119 #  include "trees.h"
00120 #endif /* GEN_TREES_H */
00121 
00122 struct static_tree_desc_s {
00123     const ct_data *static_tree;  /* static tree or NULL */
00124     const intf *extra_bits;      /* extra bits for each code or NULL */
00125     int     extra_base;          /* base index for extra_bits */
00126     int     elems;               /* max number of elements in the tree */
00127     int     max_length;          /* max bit length for the codes */
00128 };
00129 
00130 local static_tree_desc  static_l_desc =
00131 {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
00132 
00133 local static_tree_desc  static_d_desc =
00134 {static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
00135 
00136 local static_tree_desc  static_bl_desc =
00137 {(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};
00138 
00139 /* ===========================================================================
00140  * Local (static) routines in this file.
00141  */
00142 
00143 local void tr_static_init OF((void));
00144 local void init_block     OF((deflate_state *s));
00145 local void pqdownheap     OF((deflate_state *s, ct_data *tree, int k));
00146 local void gen_bitlen     OF((deflate_state *s, tree_desc *desc));
00147 local void gen_codes      OF((ct_data *tree, int max_code, ushf *bl_count));
00148 local void build_tree     OF((deflate_state *s, tree_desc *desc));
00149 local void scan_tree      OF((deflate_state *s, ct_data *tree, int max_code));
00150 local void send_tree      OF((deflate_state *s, ct_data *tree, int max_code));
00151 local int  build_bl_tree  OF((deflate_state *s));
00152 local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
00153                               int blcodes));
00154 local void compress_block OF((deflate_state *s, ct_data *ltree,
00155                               ct_data *dtree));
00156 local int  detect_data_type OF((deflate_state *s));
00157 local unsigned bi_reverse OF((unsigned value, int length));
00158 local void bi_windup      OF((deflate_state *s));
00159 local void bi_flush       OF((deflate_state *s));
00160 local void copy_block     OF((deflate_state *s, charf *buf, unsigned len,
00161                               int header));
00162 
00163 #ifdef GEN_TREES_H
00164 local void gen_trees_header OF((void));
00165 #endif
00166 
00167 #ifndef DEBUG
00168 #  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
00169    /* Send a code of the given tree. c and tree must not have side effects */
00170 
00171 #else /* DEBUG */
00172 #  define send_code(s, c, tree) \
00173      { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
00174        send_bits(s, tree[c].Code, tree[c].Len); }
00175 #endif
00176 
00177 /* ===========================================================================
00178  * Output a short LSB first on the stream.
00179  * IN assertion: there is enough room in pendingBuf.
00180  */
00181 #define put_short(s, w) { \
00182     put_byte(s, (uch)((w) & 0xff)); \
00183     put_byte(s, (uch)((ush)(w) >> 8)); \
00184 }
00185 
00186 /* ===========================================================================
00187  * Send a value on a given number of bits.
00188  * IN assertion: length <= 16 and value fits in length bits.
00189  */
00190 #ifdef DEBUG
00191 local void send_bits      OF((deflate_state *s, int value, int length));
00192 
00193 local void send_bits(s, value, length)
00194     deflate_state *s;
00195     int value;  /* value to send */
00196     int length; /* number of bits */
00197 {
00198     Tracevv((stderr," l %2d v %4x ", length, value));
00199     Assert(length > 0 && length <= 15, "invalid length");
00200     s->bits_sent += (ulg)length;
00201 
00202     /* If not enough room in bi_buf, use (valid) bits from bi_buf and
00203      * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
00204      * unused bits in value.
00205      */
00206     if (s->bi_valid > (int)Buf_size - length) {
00207         s->bi_buf |= (ush)value << s->bi_valid;
00208         put_short(s, s->bi_buf);
00209         s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
00210         s->bi_valid += length - Buf_size;
00211     } else {
00212         s->bi_buf |= (ush)value << s->bi_valid;
00213         s->bi_valid += length;
00214     }
00215 }
00216 #else /* !DEBUG */
00217 
00218 #define send_bits(s, value, length) \
00219 { int len = length;\
00220   if (s->bi_valid > (int)Buf_size - len) {\
00221     int val = value;\
00222     s->bi_buf |= (ush)val << s->bi_valid;\
00223     put_short(s, s->bi_buf);\
00224     s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
00225     s->bi_valid += len - Buf_size;\
00226   } else {\
00227     s->bi_buf |= (ush)(value) << s->bi_valid;\
00228     s->bi_valid += len;\
00229   }\
00230 }
00231 #endif /* DEBUG */
00232 
00233 
00234 /* the arguments must not have side effects */
00235 
00236 /* ===========================================================================
00237  * Initialize the various 'constant' tables.
00238  */
00239 local void tr_static_init()
00240 {
00241 #if defined(GEN_TREES_H) || !defined(STDC)
00242     static int static_init_done = 0;
00243     int n;        /* iterates over tree elements */
00244     int bits;     /* bit counter */
00245     int length;   /* length value */
00246     int code;     /* code value */
00247     int dist;     /* distance index */
00248     ush bl_count[MAX_BITS+1];
00249     /* number of codes at each bit length for an optimal tree */
00250 
00251     if (static_init_done) return;
00252 
00253     /* For some embedded targets, global variables are not initialized: */
00254 #ifdef NO_INIT_GLOBAL_POINTERS
00255     static_l_desc.static_tree = static_ltree;
00256     static_l_desc.extra_bits = extra_lbits;
00257     static_d_desc.static_tree = static_dtree;
00258     static_d_desc.extra_bits = extra_dbits;
00259     static_bl_desc.extra_bits = extra_blbits;
00260 #endif
00261 
00262     /* Initialize the mapping length (0..255) -> length code (0..28) */
00263     length = 0;
00264     for (code = 0; code < LENGTH_CODES-1; code++) {
00265         base_length[code] = length;
00266         for (n = 0; n < (1<<extra_lbits[code]); n++) {
00267             _length_code[length++] = (uch)code;
00268         }
00269     }
00270     Assert (length == 256, "tr_static_init: length != 256");
00271     /* Note that the length 255 (match length 258) can be represented
00272      * in two different ways: code 284 + 5 bits or code 285, so we
00273      * overwrite length_code[255] to use the best encoding:
00274      */
00275     _length_code[length-1] = (uch)code;
00276 
00277     /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
00278     dist = 0;
00279     for (code = 0 ; code < 16; code++) {
00280         base_dist[code] = dist;
00281         for (n = 0; n < (1<<extra_dbits[code]); n++) {
00282             _dist_code[dist++] = (uch)code;
00283         }
00284     }
00285     Assert (dist == 256, "tr_static_init: dist != 256");
00286     dist >>= 7; /* from now on, all distances are divided by 128 */
00287     for ( ; code < D_CODES; code++) {
00288         base_dist[code] = dist << 7;
00289         for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
00290             _dist_code[256 + dist++] = (uch)code;
00291         }
00292     }
00293     Assert (dist == 256, "tr_static_init: 256+dist != 512");
00294 
00295     /* Construct the codes of the static literal tree */
00296     for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
00297     n = 0;
00298     while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
00299     while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
00300     while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
00301     while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
00302     /* Codes 286 and 287 do not exist, but we must include them in the
00303      * tree construction to get a canonical Huffman tree (longest code
00304      * all ones)
00305      */
00306     gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
00307 
00308     /* The static distance tree is trivial: */
00309     for (n = 0; n < D_CODES; n++) {
00310         static_dtree[n].Len = 5;
00311         static_dtree[n].Code = bi_reverse((unsigned)n, 5);
00312     }
00313     static_init_done = 1;
00314 
00315 #  ifdef GEN_TREES_H
00316     gen_trees_header();
00317 #  endif
00318 #endif /* defined(GEN_TREES_H) || !defined(STDC) */
00319 }
00320 
00321 /* ===========================================================================
00322  * Genererate the file trees.h describing the static trees.
00323  */
00324 #ifdef GEN_TREES_H
00325 #  ifndef DEBUG
00326 #    include <stdio.h>
00327 #  endif
00328 
00329 #  define SEPARATOR(i, last, width) \
00330       ((i) == (last)? "\n};\n\n" :    \
00331        ((i) % (width) == (width)-1 ? ",\n" : ", "))
00332 
00333 void gen_trees_header()
00334 {
00335     FILE *header = fopen("trees.h", "w");
00336     int i;
00337 
00338     Assert (header != NULL, "Can't open trees.h");
00339     fprintf(header,
00340             "/* header created automatically with -DGEN_TREES_H */\n\n");
00341 
00342     fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
00343     for (i = 0; i < L_CODES+2; i++) {
00344         fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
00345                 static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
00346     }
00347 
00348     fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
00349     for (i = 0; i < D_CODES; i++) {
00350         fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
00351                 static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
00352     }
00353 
00354     fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n");
00355     for (i = 0; i < DIST_CODE_LEN; i++) {
00356         fprintf(header, "%2u%s", _dist_code[i],
00357                 SEPARATOR(i, DIST_CODE_LEN-1, 20));
00358     }
00359 
00360     fprintf(header,
00361         "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
00362     for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
00363         fprintf(header, "%2u%s", _length_code[i],
00364                 SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
00365     }
00366 
00367     fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
00368     for (i = 0; i < LENGTH_CODES; i++) {
00369         fprintf(header, "%1u%s", base_length[i],
00370                 SEPARATOR(i, LENGTH_CODES-1, 20));
00371     }
00372 
00373     fprintf(header, "local const int base_dist[D_CODES] = {\n");
00374     for (i = 0; i < D_CODES; i++) {
00375         fprintf(header, "%5u%s", base_dist[i],
00376                 SEPARATOR(i, D_CODES-1, 10));
00377     }
00378 
00379     fclose(header);
00380 }
00381 #endif /* GEN_TREES_H */
00382 
00383 /* ===========================================================================
00384  * Initialize the tree data structures for a new zlib stream.
00385  */
00386 void ZLIB_INTERNAL _tr_init(s)
00387     deflate_state *s;
00388 {
00389     tr_static_init();
00390 
00391     s->l_desc.dyn_tree = s->dyn_ltree;
00392     s->l_desc.stat_desc = &static_l_desc;
00393 
00394     s->d_desc.dyn_tree = s->dyn_dtree;
00395     s->d_desc.stat_desc = &static_d_desc;
00396 
00397     s->bl_desc.dyn_tree = s->bl_tree;
00398     s->bl_desc.stat_desc = &static_bl_desc;
00399 
00400     s->bi_buf = 0;
00401     s->bi_valid = 0;
00402     s->last_eob_len = 8; /* enough lookahead for inflate */
00403 #ifdef DEBUG
00404     s->compressed_len = 0L;
00405     s->bits_sent = 0L;
00406 #endif
00407 
00408     /* Initialize the first block of the first file: */
00409     init_block(s);
00410 }
00411 
00412 /* ===========================================================================
00413  * Initialize a new block.
00414  */
00415 local void init_block(s)
00416     deflate_state *s;
00417 {
00418     int n; /* iterates over tree elements */
00419 
00420     /* Initialize the trees. */
00421     for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;
00422     for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;
00423     for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
00424 
00425     s->dyn_ltree[END_BLOCK].Freq = 1;
00426     s->opt_len = s->static_len = 0L;
00427     s->last_lit = s->matches = 0;
00428 }
00429 
00430 #define SMALLEST 1
00431 /* Index within the heap array of least frequent node in the Huffman tree */
00432 
00433 
00434 /* ===========================================================================
00435  * Remove the smallest element from the heap and recreate the heap with
00436  * one less element. Updates heap and heap_len.
00437  */
00438 #define pqremove(s, tree, top) \
00439 {\
00440     top = s->heap[SMALLEST]; \
00441     s->heap[SMALLEST] = s->heap[s->heap_len--]; \
00442     pqdownheap(s, tree, SMALLEST); \
00443 }
00444 
00445 /* ===========================================================================
00446  * Compares to subtrees, using the tree depth as tie breaker when
00447  * the subtrees have equal frequency. This minimizes the worst case length.
00448  */
00449 #define smaller(tree, n, m, depth) \
00450    (tree[n].Freq < tree[m].Freq || \
00451    (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
00452 
00453 /* ===========================================================================
00454  * Restore the heap property by moving down the tree starting at node k,
00455  * exchanging a node with the smallest of its two sons if necessary, stopping
00456  * when the heap property is re-established (each father smaller than its
00457  * two sons).
00458  */
00459 local void pqdownheap(s, tree, k)
00460     deflate_state *s;
00461     ct_data *tree;  /* the tree to restore */
00462     int k;               /* node to move down */
00463 {
00464     int v = s->heap[k];
00465     int j = k << 1;  /* left son of k */
00466     while (j <= s->heap_len) {
00467         /* Set j to the smallest of the two sons: */
00468         if (j < s->heap_len &&
00469             smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
00470             j++;
00471         }
00472         /* Exit if v is smaller than both sons */
00473         if (smaller(tree, v, s->heap[j], s->depth)) break;
00474 
00475         /* Exchange v with the smallest son */
00476         s->heap[k] = s->heap[j];  k = j;
00477 
00478         /* And continue down the tree, setting j to the left son of k */
00479         j <<= 1;
00480     }
00481     s->heap[k] = v;
00482 }
00483 
00484 /* ===========================================================================
00485  * Compute the optimal bit lengths for a tree and update the total bit length
00486  * for the current block.
00487  * IN assertion: the fields freq and dad are set, heap[heap_max] and
00488  *    above are the tree nodes sorted by increasing frequency.
00489  * OUT assertions: the field len is set to the optimal bit length, the
00490  *     array bl_count contains the frequencies for each bit length.
00491  *     The length opt_len is updated; static_len is also updated if stree is
00492  *     not null.
00493  */
00494 local void gen_bitlen(s, desc)
00495     deflate_state *s;
00496     tree_desc *desc;    /* the tree descriptor */
00497 {
00498     ct_data *tree        = desc->dyn_tree;
00499     int max_code         = desc->max_code;
00500     const ct_data *stree = desc->stat_desc->static_tree;
00501     const intf *extra    = desc->stat_desc->extra_bits;
00502     int base             = desc->stat_desc->extra_base;
00503     int max_length       = desc->stat_desc->max_length;
00504     int h;              /* heap index */
00505     int n, m;           /* iterate over the tree elements */
00506     int bits;           /* bit length */
00507     int xbits;          /* extra bits */
00508     ush f;              /* frequency */
00509     int overflow = 0;   /* number of elements with bit length too large */
00510 
00511     for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
00512 
00513     /* In a first pass, compute the optimal bit lengths (which may
00514      * overflow in the case of the bit length tree).
00515      */
00516     tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
00517 
00518     for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
00519         n = s->heap[h];
00520         bits = tree[tree[n].Dad].Len + 1;
00521         if (bits > max_length) bits = max_length, overflow++;
00522         tree[n].Len = (ush)bits;
00523         /* We overwrite tree[n].Dad which is no longer needed */
00524 
00525         if (n > max_code) continue; /* not a leaf node */
00526 
00527         s->bl_count[bits]++;
00528         xbits = 0;
00529         if (n >= base) xbits = extra[n-base];
00530         f = tree[n].Freq;
00531         s->opt_len += (ulg)f * (bits + xbits);
00532         if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
00533     }
00534     if (overflow == 0) return;
00535 
00536     Trace((stderr,"\nbit length overflow\n"));
00537     /* This happens for example on obj2 and pic of the Calgary corpus */
00538 
00539     /* Find the first bit length which could increase: */
00540     do {
00541         bits = max_length-1;
00542         while (s->bl_count[bits] == 0) bits--;
00543         s->bl_count[bits]--;      /* move one leaf down the tree */
00544         s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
00545         s->bl_count[max_length]--;
00546         /* The brother of the overflow item also moves one step up,
00547          * but this does not affect bl_count[max_length]
00548          */
00549         overflow -= 2;
00550     } while (overflow > 0);
00551 
00552     /* Now recompute all bit lengths, scanning in increasing frequency.
00553      * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
00554      * lengths instead of fixing only the wrong ones. This idea is taken
00555      * from 'ar' written by Haruhiko Okumura.)
00556      */
00557     for (bits = max_length; bits != 0; bits--) {
00558         n = s->bl_count[bits];
00559         while (n != 0) {
00560             m = s->heap[--h];
00561             if (m > max_code) continue;
00562             if ((unsigned) tree[m].Len != (unsigned) bits) {
00563                 Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
00564                 s->opt_len += ((long)bits - (long)tree[m].Len)
00565                               *(long)tree[m].Freq;
00566                 tree[m].Len = (ush)bits;
00567             }
00568             n--;
00569         }
00570     }
00571 }
00572 
00573 /* ===========================================================================
00574  * Generate the codes for a given tree and bit counts (which need not be
00575  * optimal).
00576  * IN assertion: the array bl_count contains the bit length statistics for
00577  * the given tree and the field len is set for all tree elements.
00578  * OUT assertion: the field code is set for all tree elements of non
00579  *     zero code length.
00580  */
00581 local void gen_codes (tree, max_code, bl_count)
00582     ct_data *tree;             /* the tree to decorate */
00583     int max_code;              /* largest code with non zero frequency */
00584     ushf *bl_count;            /* number of codes at each bit length */
00585 {
00586     ush next_code[MAX_BITS+1]; /* next code value for each bit length */
00587     ush code = 0;              /* running code value */
00588     int bits;                  /* bit index */
00589     int n;                     /* code index */
00590 
00591     /* The distribution counts are first used to generate the code values
00592      * without bit reversal.
00593      */
00594     for (bits = 1; bits <= MAX_BITS; bits++) {
00595         next_code[bits] = code = (code + bl_count[bits-1]) << 1;
00596     }
00597     /* Check that the bit counts in bl_count are consistent. The last code
00598      * must be all ones.
00599      */
00600     Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
00601             "inconsistent bit counts");
00602     Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
00603 
00604     for (n = 0;  n <= max_code; n++) {
00605         int len = tree[n].Len;
00606         if (len == 0) continue;
00607         /* Now reverse the bits */
00608         tree[n].Code = bi_reverse(next_code[len]++, len);
00609 
00610         Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
00611              n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
00612     }
00613 }
00614 
00615 /* ===========================================================================
00616  * Construct one Huffman tree and assigns the code bit strings and lengths.
00617  * Update the total bit length for the current block.
00618  * IN assertion: the field freq is set for all tree elements.
00619  * OUT assertions: the fields len and code are set to the optimal bit length
00620  *     and corresponding code. The length opt_len is updated; static_len is
00621  *     also updated if stree is not null. The field max_code is set.
00622  */
00623 local void build_tree(s, desc)
00624     deflate_state *s;
00625     tree_desc *desc; /* the tree descriptor */
00626 {
00627     ct_data *tree         = desc->dyn_tree;
00628     const ct_data *stree  = desc->stat_desc->static_tree;
00629     int elems             = desc->stat_desc->elems;
00630     int n, m;          /* iterate over heap elements */
00631     int max_code = -1; /* largest code with non zero frequency */
00632     int node;          /* new node being created */
00633 
00634     /* Construct the initial heap, with least frequent element in
00635      * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
00636      * heap[0] is not used.
00637      */
00638     s->heap_len = 0, s->heap_max = HEAP_SIZE;
00639 
00640     for (n = 0; n < elems; n++) {
00641         if (tree[n].Freq != 0) {
00642             s->heap[++(s->heap_len)] = max_code = n;
00643             s->depth[n] = 0;
00644         } else {
00645             tree[n].Len = 0;
00646         }
00647     }
00648 
00649     /* The pkzip format requires that at least one distance code exists,
00650      * and that at least one bit should be sent even if there is only one
00651      * possible code. So to avoid special checks later on we force at least
00652      * two codes of non zero frequency.
00653      */
00654     while (s->heap_len < 2) {
00655         node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
00656         tree[node].Freq = 1;
00657         s->depth[node] = 0;
00658         s->opt_len--; if (stree) s->static_len -= stree[node].Len;
00659         /* node is 0 or 1 so it does not have extra bits */
00660     }
00661     desc->max_code = max_code;
00662 
00663     /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
00664      * establish sub-heaps of increasing lengths:
00665      */
00666     for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
00667 
00668     /* Construct the Huffman tree by repeatedly combining the least two
00669      * frequent nodes.
00670      */
00671     node = elems;              /* next internal node of the tree */
00672     do {
00673         pqremove(s, tree, n);  /* n = node of least frequency */
00674         m = s->heap[SMALLEST]; /* m = node of next least frequency */
00675 
00676         s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
00677         s->heap[--(s->heap_max)] = m;
00678 
00679         /* Create a new node father of n and m */
00680         tree[node].Freq = tree[n].Freq + tree[m].Freq;
00681         s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
00682                                 s->depth[n] : s->depth[m]) + 1);
00683         tree[n].Dad = tree[m].Dad = (ush)node;
00684 #ifdef DUMP_BL_TREE
00685         if (tree == s->bl_tree) {
00686             fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
00687                     node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
00688         }
00689 #endif
00690         /* and insert the new node in the heap */
00691         s->heap[SMALLEST] = node++;
00692         pqdownheap(s, tree, SMALLEST);
00693 
00694     } while (s->heap_len >= 2);
00695 
00696     s->heap[--(s->heap_max)] = s->heap[SMALLEST];
00697 
00698     /* At this point, the fields freq and dad are set. We can now
00699      * generate the bit lengths.
00700      */
00701     gen_bitlen(s, (tree_desc *)desc);
00702 
00703     /* The field len is now set, we can generate the bit codes */
00704     gen_codes ((ct_data *)tree, max_code, s->bl_count);
00705 }
00706 
00707 /* ===========================================================================
00708  * Scan a literal or distance tree to determine the frequencies of the codes
00709  * in the bit length tree.
00710  */
00711 local void scan_tree (s, tree, max_code)
00712     deflate_state *s;
00713     ct_data *tree;   /* the tree to be scanned */
00714     int max_code;    /* and its largest code of non zero frequency */
00715 {
00716     int n;                     /* iterates over all tree elements */
00717     int prevlen = -1;          /* last emitted length */
00718     int curlen;                /* length of current code */
00719     int nextlen = tree[0].Len; /* length of next code */
00720     int count = 0;             /* repeat count of the current code */
00721     int max_count = 7;         /* max repeat count */
00722     int min_count = 4;         /* min repeat count */
00723 
00724     if (nextlen == 0) max_count = 138, min_count = 3;
00725     tree[max_code+1].Len = (ush)0xffff; /* guard */
00726 
00727     for (n = 0; n <= max_code; n++) {
00728         curlen = nextlen; nextlen = tree[n+1].Len;
00729         if (++count < max_count && curlen == nextlen) {
00730             continue;
00731         } else if (count < min_count) {
00732             s->bl_tree[curlen].Freq += count;
00733         } else if (curlen != 0) {
00734             if (curlen != prevlen) s->bl_tree[curlen].Freq++;
00735             s->bl_tree[REP_3_6].Freq++;
00736         } else if (count <= 10) {
00737             s->bl_tree[REPZ_3_10].Freq++;
00738         } else {
00739             s->bl_tree[REPZ_11_138].Freq++;
00740         }
00741         count = 0; prevlen = curlen;
00742         if (nextlen == 0) {
00743             max_count = 138, min_count = 3;
00744         } else if (curlen == nextlen) {
00745             max_count = 6, min_count = 3;
00746         } else {
00747             max_count = 7, min_count = 4;
00748         }
00749     }
00750 }
00751 
00752 /* ===========================================================================
00753  * Send a literal or distance tree in compressed form, using the codes in
00754  * bl_tree.
00755  */
00756 local void send_tree (s, tree, max_code)
00757     deflate_state *s;
00758     ct_data *tree; /* the tree to be scanned */
00759     int max_code;       /* and its largest code of non zero frequency */
00760 {
00761     int n;                     /* iterates over all tree elements */
00762     int prevlen = -1;          /* last emitted length */
00763     int curlen;                /* length of current code */
00764     int nextlen = tree[0].Len; /* length of next code */
00765     int count = 0;             /* repeat count of the current code */
00766     int max_count = 7;         /* max repeat count */
00767     int min_count = 4;         /* min repeat count */
00768 
00769     /* tree[max_code+1].Len = -1; */  /* guard already set */
00770     if (nextlen == 0) max_count = 138, min_count = 3;
00771 
00772     for (n = 0; n <= max_code; n++) {
00773         curlen = nextlen; nextlen = tree[n+1].Len;
00774         if (++count < max_count && curlen == nextlen) {
00775             continue;
00776         } else if (count < min_count) {
00777             do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
00778 
00779         } else if (curlen != 0) {
00780             if (curlen != prevlen) {
00781                 send_code(s, curlen, s->bl_tree); count--;
00782             }
00783             Assert(count >= 3 && count <= 6, " 3_6?");
00784             send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
00785 
00786         } else if (count <= 10) {
00787             send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
00788 
00789         } else {
00790             send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
00791         }
00792         count = 0; prevlen = curlen;
00793         if (nextlen == 0) {
00794             max_count = 138, min_count = 3;
00795         } else if (curlen == nextlen) {
00796             max_count = 6, min_count = 3;
00797         } else {
00798             max_count = 7, min_count = 4;
00799         }
00800     }
00801 }
00802 
00803 /* ===========================================================================
00804  * Construct the Huffman tree for the bit lengths and return the index in
00805  * bl_order of the last bit length code to send.
00806  */
00807 local int build_bl_tree(s)
00808     deflate_state *s;
00809 {
00810     int max_blindex;  /* index of last bit length code of non zero freq */
00811 
00812     /* Determine the bit length frequencies for literal and distance trees */
00813     scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
00814     scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
00815 
00816     /* Build the bit length tree: */
00817     build_tree(s, (tree_desc *)(&(s->bl_desc)));
00818     /* opt_len now includes the length of the tree representations, except
00819      * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
00820      */
00821 
00822     /* Determine the number of bit length codes to send. The pkzip format
00823      * requires that at least 4 bit length codes be sent. (appnote.txt says
00824      * 3 but the actual value used is 4.)
00825      */
00826     for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
00827         if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
00828     }
00829     /* Update opt_len to include the bit length tree and counts */
00830     s->opt_len += 3*(max_blindex+1) + 5+5+4;
00831     Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
00832             s->opt_len, s->static_len));
00833 
00834     return max_blindex;
00835 }
00836 
00837 /* ===========================================================================
00838  * Send the header for a block using dynamic Huffman trees: the counts, the
00839  * lengths of the bit length codes, the literal tree and the distance tree.
00840  * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
00841  */
00842 local void send_all_trees(s, lcodes, dcodes, blcodes)
00843     deflate_state *s;
00844     int lcodes, dcodes, blcodes; /* number of codes for each tree */
00845 {
00846     int rank;                    /* index in bl_order */
00847 
00848     Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
00849     Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
00850             "too many codes");
00851     Tracev((stderr, "\nbl counts: "));
00852     send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
00853     send_bits(s, dcodes-1,   5);
00854     send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */
00855     for (rank = 0; rank < blcodes; rank++) {
00856         Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
00857         send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
00858     }
00859     Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
00860 
00861     send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
00862     Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
00863 
00864     send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
00865     Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
00866 }
00867 
00868 /* ===========================================================================
00869  * Send a stored block
00870  */
00871 void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last)
00872     deflate_state *s;
00873     charf *buf;       /* input block */
00874     ulg stored_len;   /* length of input block */
00875     int last;         /* one if this is the last block for a file */
00876 {
00877     send_bits(s, (STORED_BLOCK<<1)+last, 3);    /* send block type */
00878 #ifdef DEBUG
00879     s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
00880     s->compressed_len += (stored_len + 4) << 3;
00881 #endif
00882     copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
00883 }
00884 
00885 /* ===========================================================================
00886  * Send one empty static block to give enough lookahead for inflate.
00887  * This takes 10 bits, of which 7 may remain in the bit buffer.
00888  * The current inflate code requires 9 bits of lookahead. If the
00889  * last two codes for the previous block (real code plus EOB) were coded
00890  * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
00891  * the last real code. In this case we send two empty static blocks instead
00892  * of one. (There are no problems if the previous block is stored or fixed.)
00893  * To simplify the code, we assume the worst case of last real code encoded
00894  * on one bit only.
00895  */
00896 void ZLIB_INTERNAL _tr_align(s)
00897     deflate_state *s;
00898 {
00899     send_bits(s, STATIC_TREES<<1, 3);
00900     send_code(s, END_BLOCK, static_ltree);
00901 #ifdef DEBUG
00902     s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
00903 #endif
00904     bi_flush(s);
00905     /* Of the 10 bits for the empty block, we have already sent
00906      * (10 - bi_valid) bits. The lookahead for the last real code (before
00907      * the EOB of the previous block) was thus at least one plus the length
00908      * of the EOB plus what we have just sent of the empty static block.
00909      */
00910     if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
00911         send_bits(s, STATIC_TREES<<1, 3);
00912         send_code(s, END_BLOCK, static_ltree);
00913 #ifdef DEBUG
00914         s->compressed_len += 10L;
00915 #endif
00916         bi_flush(s);
00917     }
00918     s->last_eob_len = 7;
00919 }
00920 
00921 /* ===========================================================================
00922  * Determine the best encoding for the current block: dynamic trees, static
00923  * trees or store, and output the encoded block to the zip file.
00924  */
00925 void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)
00926     deflate_state *s;
00927     charf *buf;       /* input block, or NULL if too old */
00928     ulg stored_len;   /* length of input block */
00929     int last;         /* one if this is the last block for a file */
00930 {
00931     ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
00932     int max_blindex = 0;  /* index of last bit length code of non zero freq */
00933 
00934     /* Build the Huffman trees unless a stored block is forced */
00935     if (s->level > 0) {
00936 
00937         /* Check if the file is binary or text */
00938         if (s->strm->data_type == Z_UNKNOWN)
00939             s->strm->data_type = detect_data_type(s);
00940 
00941         /* Construct the literal and distance trees */
00942         build_tree(s, (tree_desc *)(&(s->l_desc)));
00943         Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
00944                 s->static_len));
00945 
00946         build_tree(s, (tree_desc *)(&(s->d_desc)));
00947         Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
00948                 s->static_len));
00949         /* At this point, opt_len and static_len are the total bit lengths of
00950          * the compressed block data, excluding the tree representations.
00951          */
00952 
00953         /* Build the bit length tree for the above two trees, and get the index
00954          * in bl_order of the last bit length code to send.
00955          */
00956         max_blindex = build_bl_tree(s);
00957 
00958         /* Determine the best encoding. Compute the block lengths in bytes. */
00959         opt_lenb = (s->opt_len+3+7)>>3;
00960         static_lenb = (s->static_len+3+7)>>3;
00961 
00962         Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
00963                 opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
00964                 s->last_lit));
00965 
00966         if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
00967 
00968     } else {
00969         Assert(buf != (char*)0, "lost buf");
00970         opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
00971     }
00972 
00973 #ifdef FORCE_STORED
00974     if (buf != (char*)0) { /* force stored block */
00975 #else
00976     if (stored_len+4 <= opt_lenb && buf != (char*)0) {
00977                        /* 4: two words for the lengths */
00978 #endif
00979         /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
00980          * Otherwise we can't have processed more than WSIZE input bytes since
00981          * the last block flush, because compression would have been
00982          * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
00983          * transform a block into a stored block.
00984          */
00985         _tr_stored_block(s, buf, stored_len, last);
00986 
00987 #ifdef FORCE_STATIC
00988     } else if (static_lenb >= 0) { /* force static trees */
00989 #else
00990     } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
00991 #endif
00992         send_bits(s, (STATIC_TREES<<1)+last, 3);
00993         compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
00994 #ifdef DEBUG
00995         s->compressed_len += 3 + s->static_len;
00996 #endif
00997     } else {
00998         send_bits(s, (DYN_TREES<<1)+last, 3);
00999         send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
01000                        max_blindex+1);
01001         compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
01002 #ifdef DEBUG
01003         s->compressed_len += 3 + s->opt_len;
01004 #endif
01005     }
01006     Assert (s->compressed_len == s->bits_sent, "bad compressed size");
01007     /* The above check is made mod 2^32, for files larger than 512 MB
01008      * and uLong implemented on 32 bits.
01009      */
01010     init_block(s);
01011 
01012     if (last) {
01013         bi_windup(s);
01014 #ifdef DEBUG
01015         s->compressed_len += 7;  /* align on byte boundary */
01016 #endif
01017     }
01018     Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
01019            s->compressed_len-7*last));
01020 }
01021 
01022 /* ===========================================================================
01023  * Save the match info and tally the frequency counts. Return true if
01024  * the current block must be flushed.
01025  */
01026 int ZLIB_INTERNAL _tr_tally (s, dist, lc)
01027     deflate_state *s;
01028     unsigned dist;  /* distance of matched string */
01029     unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
01030 {
01031     s->d_buf[s->last_lit] = (ush)dist;
01032     s->l_buf[s->last_lit++] = (uch)lc;
01033     if (dist == 0) {
01034         /* lc is the unmatched char */
01035         s->dyn_ltree[lc].Freq++;
01036     } else {
01037         s->matches++;
01038         /* Here, lc is the match length - MIN_MATCH */
01039         dist--;             /* dist = match distance - 1 */
01040         Assert((ush)dist < (ush)MAX_DIST(s) &&
01041                (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
01042                (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
01043 
01044         s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
01045         s->dyn_dtree[d_code(dist)].Freq++;
01046     }
01047 
01048 #ifdef TRUNCATE_BLOCK
01049     /* Try to guess if it is profitable to stop the current block here */
01050     if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
01051         /* Compute an upper bound for the compressed length */
01052         ulg out_length = (ulg)s->last_lit*8L;
01053         ulg in_length = (ulg)((long)s->strstart - s->block_start);
01054         int dcode;
01055         for (dcode = 0; dcode < D_CODES; dcode++) {
01056             out_length += (ulg)s->dyn_dtree[dcode].Freq *
01057                 (5L+extra_dbits[dcode]);
01058         }
01059         out_length >>= 3;
01060         Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
01061                s->last_lit, in_length, out_length,
01062                100L - out_length*100L/in_length));
01063         if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
01064     }
01065 #endif
01066     return (s->last_lit == s->lit_bufsize-1);
01067     /* We avoid equality with lit_bufsize because of wraparound at 64K
01068      * on 16 bit machines and because stored blocks are restricted to
01069      * 64K-1 bytes.
01070      */
01071 }
01072 
01073 /* ===========================================================================
01074  * Send the block data compressed using the given Huffman trees
01075  */
01076 local void compress_block(s, ltree, dtree)
01077     deflate_state *s;
01078     ct_data *ltree; /* literal tree */
01079     ct_data *dtree; /* distance tree */
01080 {
01081     unsigned dist;      /* distance of matched string */
01082     int lc;             /* match length or unmatched char (if dist == 0) */
01083     unsigned lx = 0;    /* running index in l_buf */
01084     unsigned code;      /* the code to send */
01085     int extra;          /* number of extra bits to send */
01086 
01087     if (s->last_lit != 0) do {
01088         dist = s->d_buf[lx];
01089         lc = s->l_buf[lx++];
01090         if (dist == 0) {
01091             send_code(s, lc, ltree); /* send a literal byte */
01092             Tracecv(isgraph(lc), (stderr," '%c' ", lc));
01093         } else {
01094             /* Here, lc is the match length - MIN_MATCH */
01095             code = _length_code[lc];
01096             send_code(s, code+LITERALS+1, ltree); /* send the length code */
01097             extra = extra_lbits[code];
01098             if (extra != 0) {
01099                 lc -= base_length[code];
01100                 send_bits(s, lc, extra);       /* send the extra length bits */
01101             }
01102             dist--; /* dist is now the match distance - 1 */
01103             code = d_code(dist);
01104             Assert (code < D_CODES, "bad d_code");
01105 
01106             send_code(s, code, dtree);       /* send the distance code */
01107             extra = extra_dbits[code];
01108             if (extra != 0) {
01109                 dist -= base_dist[code];
01110                 send_bits(s, dist, extra);   /* send the extra distance bits */
01111             }
01112         } /* literal or match pair ? */
01113 
01114         /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
01115         Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
01116                "pendingBuf overflow");
01117 
01118     } while (lx < s->last_lit);
01119 
01120     send_code(s, END_BLOCK, ltree);
01121     s->last_eob_len = ltree[END_BLOCK].Len;
01122 }
01123 
01124 /* ===========================================================================
01125  * Check if the data type is TEXT or BINARY, using the following algorithm:
01126  * - TEXT if the two conditions below are satisfied:
01127  *    a) There are no non-portable control characters belonging to the
01128  *       "black list" (0..6, 14..25, 28..31).
01129  *    b) There is at least one printable character belonging to the
01130  *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
01131  * - BINARY otherwise.
01132  * - The following partially-portable control characters form a
01133  *   "gray list" that is ignored in this detection algorithm:
01134  *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
01135  * IN assertion: the fields Freq of dyn_ltree are set.
01136  */
01137 local int detect_data_type(s)
01138     deflate_state *s;
01139 {
01140     /* black_mask is the bit mask of black-listed bytes
01141      * set bits 0..6, 14..25, and 28..31
01142      * 0xf3ffc07f = binary 11110011111111111100000001111111
01143      */
01144     unsigned long black_mask = 0xf3ffc07fUL;
01145     int n;
01146 
01147     /* Check for non-textual ("black-listed") bytes. */
01148     for (n = 0; n <= 31; n++, black_mask >>= 1)
01149         if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0))
01150             return Z_BINARY;
01151 
01152     /* Check for textual ("white-listed") bytes. */
01153     if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0
01154             || s->dyn_ltree[13].Freq != 0)
01155         return Z_TEXT;
01156     for (n = 32; n < LITERALS; n++)
01157         if (s->dyn_ltree[n].Freq != 0)
01158             return Z_TEXT;
01159 
01160     /* There are no "black-listed" or "white-listed" bytes:
01161      * this stream either is empty or has tolerated ("gray-listed") bytes only.
01162      */
01163     return Z_BINARY;
01164 }
01165 
01166 /* ===========================================================================
01167  * Reverse the first len bits of a code, using straightforward code (a faster
01168  * method would use a table)
01169  * IN assertion: 1 <= len <= 15
01170  */
01171 local unsigned bi_reverse(code, len)
01172     unsigned code; /* the value to invert */
01173     int len;       /* its bit length */
01174 {
01175     register unsigned res = 0;
01176     do {
01177         res |= code & 1;
01178         code >>= 1, res <<= 1;
01179     } while (--len > 0);
01180     return res >> 1;
01181 }
01182 
01183 /* ===========================================================================
01184  * Flush the bit buffer, keeping at most 7 bits in it.
01185  */
01186 local void bi_flush(s)
01187     deflate_state *s;
01188 {
01189     if (s->bi_valid == 16) {
01190         put_short(s, s->bi_buf);
01191         s->bi_buf = 0;
01192         s->bi_valid = 0;
01193     } else if (s->bi_valid >= 8) {
01194         put_byte(s, (Byte)s->bi_buf);
01195         s->bi_buf >>= 8;
01196         s->bi_valid -= 8;
01197     }
01198 }
01199 
01200 /* ===========================================================================
01201  * Flush the bit buffer and align the output on a byte boundary
01202  */
01203 local void bi_windup(s)
01204     deflate_state *s;
01205 {
01206     if (s->bi_valid > 8) {
01207         put_short(s, s->bi_buf);
01208     } else if (s->bi_valid > 0) {
01209         put_byte(s, (Byte)s->bi_buf);
01210     }
01211     s->bi_buf = 0;
01212     s->bi_valid = 0;
01213 #ifdef DEBUG
01214     s->bits_sent = (s->bits_sent+7) & ~7;
01215 #endif
01216 }
01217 
01218 /* ===========================================================================
01219  * Copy a stored block, storing first the length and its
01220  * one's complement if requested.
01221  */
01222 local void copy_block(s, buf, len, header)
01223     deflate_state *s;
01224     charf    *buf;    /* the input data */
01225     unsigned len;     /* its length */
01226     int      header;  /* true if block header must be written */
01227 {
01228     bi_windup(s);        /* align on byte boundary */
01229     s->last_eob_len = 8; /* enough lookahead for inflate */
01230 
01231     if (header) {
01232         put_short(s, (ush)len);
01233         put_short(s, (ush)~len);
01234 #ifdef DEBUG
01235         s->bits_sent += 2*16;
01236 #endif
01237     }
01238 #ifdef DEBUG
01239     s->bits_sent += (ulg)len<<3;
01240 #endif
01241     while (len--) {
01242         put_byte(s, *buf++);
01243     }
01244 }

Generated on Wed Oct 20 2010 11:12:18 for APBS by  doxygen 1.7.2