]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libz/inftrees.c
This commit was generated by cvs2svn to compensate for changes in r91094,
[FreeBSD/FreeBSD.git] / lib / libz / inftrees.c
1 /* inftrees.c -- generate Huffman trees for efficient decoding
2  * Copyright (C) 1995-1998 Mark Adler
3  * For conditions of distribution and use, see copyright notice in zlib.h 
4  */
5
6 #include <sys/cdefs.h>
7 __FBSDID("$FreeBSD$");
8
9 #include "zutil.h"
10 #include "inftrees.h"
11
12 #if !defined(BUILDFIXED) && !defined(STDC)
13 #  define BUILDFIXED   /* non ANSI compilers may not accept inffixed.h */
14 #endif
15
16 const char inflate_copyright[] =
17    " inflate 1.1.3 Copyright 1995-1998 Mark Adler ";
18 /*
19   If you use the zlib library in a product, an acknowledgment is welcome
20   in the documentation of your product. If for some reason you cannot
21   include such an acknowledgment, I would appreciate that you keep this
22   copyright string in the executable of your product.
23  */
24 struct internal_state  {int dummy;}; /* for buggy compilers */
25
26 /* simplify the use of the inflate_huft type with some defines */
27 #define exop word.what.Exop
28 #define bits word.what.Bits
29
30
31 local int huft_build OF((
32     uIntf *,            /* code lengths in bits */
33     uInt,               /* number of codes */
34     uInt,               /* number of "simple" codes */
35     const uIntf *,      /* list of base values for non-simple codes */
36     const uIntf *,      /* list of extra bits for non-simple codes */
37     inflate_huft * FAR*,/* result: starting table */
38     uIntf *,            /* maximum lookup bits (returns actual) */
39     inflate_huft *,     /* space for trees */
40     uInt *,             /* hufts used in space */
41     uIntf * ));         /* space for values */
42
43 /* Tables for deflate from PKZIP's appnote.txt. */
44 local const uInt cplens[31] = { /* Copy lengths for literal codes 257..285 */
45         3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
46         35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
47         /* see note #13 above about 258 */
48 local const uInt cplext[31] = { /* Extra bits for literal codes 257..285 */
49         0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
50         3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112}; /* 112==invalid */
51 local const uInt cpdist[30] = { /* Copy offsets for distance codes 0..29 */
52         1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
53         257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
54         8193, 12289, 16385, 24577};
55 local const uInt cpdext[30] = { /* Extra bits for distance codes */
56         0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
57         7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
58         12, 12, 13, 13};
59
60 /*
61    Huffman code decoding is performed using a multi-level table lookup.
62    The fastest way to decode is to simply build a lookup table whose
63    size is determined by the longest code.  However, the time it takes
64    to build this table can also be a factor if the data being decoded
65    is not very long.  The most common codes are necessarily the
66    shortest codes, so those codes dominate the decoding time, and hence
67    the speed.  The idea is you can have a shorter table that decodes the
68    shorter, more probable codes, and then point to subsidiary tables for
69    the longer codes.  The time it costs to decode the longer codes is
70    then traded against the time it takes to make longer tables.
71
72    This results of this trade are in the variables lbits and dbits
73    below.  lbits is the number of bits the first level table for literal/
74    length codes can decode in one step, and dbits is the same thing for
75    the distance codes.  Subsequent tables are also less than or equal to
76    those sizes.  These values may be adjusted either when all of the
77    codes are shorter than that, in which case the longest code length in
78    bits is used, or when the shortest code is *longer* than the requested
79    table size, in which case the length of the shortest code in bits is
80    used.
81
82    There are two different values for the two tables, since they code a
83    different number of possibilities each.  The literal/length table
84    codes 286 possible values, or in a flat code, a little over eight
85    bits.  The distance table codes 30 possible values, or a little less
86    than five bits, flat.  The optimum values for speed end up being
87    about one bit more than those, so lbits is 8+1 and dbits is 5+1.
88    The optimum values may differ though from machine to machine, and
89    possibly even between compilers.  Your mileage may vary.
90  */
91
92
93 /* If BMAX needs to be larger than 16, then h and x[] should be uLong. */
94 #define BMAX 15         /* maximum bit length of any code */
95
96 local int huft_build(b, n, s, d, e, t, m, hp, hn, v)
97 uIntf *b;               /* code lengths in bits (all assumed <= BMAX) */
98 uInt n;                 /* number of codes (assumed <= 288) */
99 uInt s;                 /* number of simple-valued codes (0..s-1) */
100 const uIntf *d;         /* list of base values for non-simple codes */
101 const uIntf *e;         /* list of extra bits for non-simple codes */
102 inflate_huft * FAR *t;  /* result: starting table */
103 uIntf *m;               /* maximum lookup bits, returns actual */
104 inflate_huft *hp;       /* space for trees */
105 uInt *hn;               /* hufts used in space */
106 uIntf *v;               /* working area: values in order of bit length */
107 /* Given a list of code lengths and a maximum table size, make a set of
108    tables to decode that set of codes.  Return Z_OK on success, Z_BUF_ERROR
109    if the given code set is incomplete (the tables are still built in this
110    case), Z_DATA_ERROR if the input is invalid (an over-subscribed set of
111    lengths), or Z_MEM_ERROR if not enough memory. */
112 {
113
114   uInt a;                       /* counter for codes of length k */
115   uInt c[BMAX+1];               /* bit length count table */
116   uInt f;                       /* i repeats in table every f entries */
117   int g;                        /* maximum code length */
118   int h;                        /* table level */
119   register uInt i;              /* counter, current code */
120   register uInt j;              /* counter */
121   register int k;               /* number of bits in current code */
122   int l;                        /* bits per table (returned in m) */
123   uInt mask;                    /* (1 << w) - 1, to avoid cc -O bug on HP */
124   register uIntf *p;            /* pointer into c[], b[], or v[] */
125   inflate_huft *q;              /* points to current table */
126   struct inflate_huft_s r;      /* table entry for structure assignment */
127   inflate_huft *u[BMAX];        /* table stack */
128   register int w;               /* bits before this table == (l * h) */
129   uInt x[BMAX+1];               /* bit offsets, then code stack */
130   uIntf *xp;                    /* pointer into x */
131   int y;                        /* number of dummy codes added */
132   uInt z;                       /* number of entries in current table */
133
134
135   /* Generate counts for each bit length */
136   p = c;
137 #define C0 *p++ = 0;
138 #define C2 C0 C0 C0 C0
139 #define C4 C2 C2 C2 C2
140   C4                            /* clear c[]--assume BMAX+1 is 16 */
141   p = b;  i = n;
142   do {
143     c[*p++]++;                  /* assume all entries <= BMAX */
144   } while (--i);
145   if (c[0] == n)                /* null input--all zero length codes */
146   {
147     *t = (inflate_huft *)Z_NULL;
148     *m = 0;
149     return Z_OK;
150   }
151
152
153   /* Find minimum and maximum length, bound *m by those */
154   l = *m;
155   for (j = 1; j <= BMAX; j++)
156     if (c[j])
157       break;
158   k = j;                        /* minimum code length */
159   if ((uInt)l < j)
160     l = j;
161   for (i = BMAX; i; i--)
162     if (c[i])
163       break;
164   g = i;                        /* maximum code length */
165   if ((uInt)l > i)
166     l = i;
167   *m = l;
168
169
170   /* Adjust last length count to fill out codes, if needed */
171   for (y = 1 << j; j < i; j++, y <<= 1)
172     if ((y -= c[j]) < 0)
173       return Z_DATA_ERROR;
174   if ((y -= c[i]) < 0)
175     return Z_DATA_ERROR;
176   c[i] += y;
177
178
179   /* Generate starting offsets into the value table for each length */
180   x[1] = j = 0;
181   p = c + 1;  xp = x + 2;
182   while (--i) {                 /* note that i == g from above */
183     *xp++ = (j += *p++);
184   }
185
186
187   /* Make a table of values in order of bit lengths */
188   p = b;  i = 0;
189   do {
190     if ((j = *p++) != 0)
191       v[x[j]++] = i;
192   } while (++i < n);
193   n = x[g];                     /* set n to length of v */
194
195
196   /* Generate the Huffman codes and for each, make the table entries */
197   x[0] = i = 0;                 /* first Huffman code is zero */
198   p = v;                        /* grab values in bit order */
199   h = -1;                       /* no tables yet--level -1 */
200   w = -l;                       /* bits decoded == (l * h) */
201   u[0] = (inflate_huft *)Z_NULL;        /* just to keep compilers happy */
202   q = (inflate_huft *)Z_NULL;   /* ditto */
203   z = 0;                        /* ditto */
204
205   /* go through the bit lengths (k already is bits in shortest code) */
206   for (; k <= g; k++)
207   {
208     a = c[k];
209     while (a--)
210     {
211       /* here i is the Huffman code of length k bits for value *p */
212       /* make tables up to required level */
213       while (k > w + l)
214       {
215         h++;
216         w += l;                 /* previous table always l bits */
217
218         /* compute minimum size table less than or equal to l bits */
219         z = g - w;
220         z = z > (uInt)l ? l : z;        /* table size upper limit */
221         if ((f = 1 << (j = k - w)) > a + 1)     /* try a k-w bit table */
222         {                       /* too few codes for k-w bit table */
223           f -= a + 1;           /* deduct codes from patterns left */
224           xp = c + k;
225           if (j < z)
226             while (++j < z)     /* try smaller tables up to z bits */
227             {
228               if ((f <<= 1) <= *++xp)
229                 break;          /* enough codes to use up j bits */
230               f -= *xp;         /* else deduct codes from patterns */
231             }
232         }
233         z = 1 << j;             /* table entries for j-bit table */
234
235         /* allocate new table */
236         if (*hn + z > MANY)     /* (note: doesn't matter for fixed) */
237           return Z_MEM_ERROR;   /* not enough memory */
238         u[h] = q = hp + *hn;
239         *hn += z;
240
241         /* connect to last table, if there is one */
242         if (h)
243         {
244           x[h] = i;             /* save pattern for backing up */
245           r.bits = (Byte)l;     /* bits to dump before this table */
246           r.exop = (Byte)j;     /* bits in this table */
247           j = i >> (w - l);
248           r.base = (uInt)(q - u[h-1] - j);   /* offset to this table */
249           u[h-1][j] = r;        /* connect to last table */
250         }
251         else
252           *t = q;               /* first table is returned result */
253       }
254
255       /* set up table entry in r */
256       r.bits = (Byte)(k - w);
257       if (p >= v + n)
258         r.exop = 128 + 64;      /* out of values--invalid code */
259       else if (*p < s)
260       {
261         r.exop = (Byte)(*p < 256 ? 0 : 32 + 64);     /* 256 is end-of-block */
262         r.base = *p++;          /* simple code is just the value */
263       }
264       else
265       {
266         r.exop = (Byte)(e[*p - s] + 16 + 64);/* non-simple--look up in lists */
267         r.base = d[*p++ - s];
268       }
269
270       /* fill code-like entries with r */
271       f = 1 << (k - w);
272       for (j = i >> w; j < z; j += f)
273         q[j] = r;
274
275       /* backwards increment the k-bit code i */
276       for (j = 1 << (k - 1); i & j; j >>= 1)
277         i ^= j;
278       i ^= j;
279
280       /* backup over finished tables */
281       mask = (1 << w) - 1;      /* needed on HP, cc -O bug */
282       while ((i & mask) != x[h])
283       {
284         h--;                    /* don't need to update q */
285         w -= l;
286         mask = (1 << w) - 1;
287       }
288     }
289   }
290
291
292   /* Return Z_BUF_ERROR if we were given an incomplete table */
293   return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK;
294 }
295
296
297 int inflate_trees_bits(c, bb, tb, hp, z)
298 uIntf *c;               /* 19 code lengths */
299 uIntf *bb;              /* bits tree desired/actual depth */
300 inflate_huft * FAR *tb; /* bits tree result */
301 inflate_huft *hp;       /* space for trees */
302 z_streamp z;            /* for messages */
303 {
304   int r;
305   uInt hn = 0;          /* hufts used in space */
306   uIntf *v;             /* work area for huft_build */
307
308   if ((v = (uIntf*)ZALLOC(z, 19, sizeof(uInt))) == Z_NULL)
309     return Z_MEM_ERROR;
310   r = huft_build(c, 19, 19, (uIntf*)Z_NULL, (uIntf*)Z_NULL,
311                  tb, bb, hp, &hn, v);
312   if (r == Z_DATA_ERROR)
313     z->msg = (char*)"oversubscribed dynamic bit lengths tree";
314   else if (r == Z_BUF_ERROR || *bb == 0)
315   {
316     z->msg = (char*)"incomplete dynamic bit lengths tree";
317     r = Z_DATA_ERROR;
318   }
319   ZFREE(z, v);
320   return r;
321 }
322
323
324 int inflate_trees_dynamic(nl, nd, c, bl, bd, tl, td, hp, z)
325 uInt nl;                /* number of literal/length codes */
326 uInt nd;                /* number of distance codes */
327 uIntf *c;               /* that many (total) code lengths */
328 uIntf *bl;              /* literal desired/actual bit depth */
329 uIntf *bd;              /* distance desired/actual bit depth */
330 inflate_huft * FAR *tl; /* literal/length tree result */
331 inflate_huft * FAR *td; /* distance tree result */
332 inflate_huft *hp;       /* space for trees */
333 z_streamp z;            /* for messages */
334 {
335   int r;
336   uInt hn = 0;          /* hufts used in space */
337   uIntf *v;             /* work area for huft_build */
338
339   /* allocate work area */
340   if ((v = (uIntf*)ZALLOC(z, 288, sizeof(uInt))) == Z_NULL)
341     return Z_MEM_ERROR;
342
343   /* build literal/length tree */
344   r = huft_build(c, nl, 257, cplens, cplext, tl, bl, hp, &hn, v);
345   if (r != Z_OK || *bl == 0)
346   {
347     if (r == Z_DATA_ERROR)
348       z->msg = (char*)"oversubscribed literal/length tree";
349     else if (r != Z_MEM_ERROR)
350     {
351       z->msg = (char*)"incomplete literal/length tree";
352       r = Z_DATA_ERROR;
353     }
354     ZFREE(z, v);
355     return r;
356   }
357
358   /* build distance tree */
359   r = huft_build(c + nl, nd, 0, cpdist, cpdext, td, bd, hp, &hn, v);
360   if (r != Z_OK || (*bd == 0 && nl > 257))
361   {
362     if (r == Z_DATA_ERROR)
363       z->msg = (char*)"oversubscribed distance tree";
364     else if (r == Z_BUF_ERROR) {
365 #ifdef PKZIP_BUG_WORKAROUND
366       r = Z_OK;
367     }
368 #else
369       z->msg = (char*)"incomplete distance tree";
370       r = Z_DATA_ERROR;
371     }
372     else if (r != Z_MEM_ERROR)
373     {
374       z->msg = (char*)"empty distance tree with lengths";
375       r = Z_DATA_ERROR;
376     }
377     ZFREE(z, v);
378     return r;
379 #endif
380   }
381
382   /* done */
383   ZFREE(z, v);
384   return Z_OK;
385 }
386
387
388 /* build fixed tables only once--keep them here */
389 #ifdef BUILDFIXED
390 local int fixed_built = 0;
391 #define FIXEDH 544      /* number of hufts used by fixed tables */
392 local inflate_huft fixed_mem[FIXEDH];
393 local uInt fixed_bl;
394 local uInt fixed_bd;
395 local inflate_huft *fixed_tl;
396 local inflate_huft *fixed_td;
397 #else
398 #include "inffixed.h"
399 #endif
400
401
402 int inflate_trees_fixed(bl, bd, tl, td, z)
403 uIntf *bl;               /* literal desired/actual bit depth */
404 uIntf *bd;               /* distance desired/actual bit depth */
405 inflate_huft * FAR *tl;  /* literal/length tree result */
406 inflate_huft * FAR *td;  /* distance tree result */
407 z_streamp z;             /* for memory allocation */
408 {
409 #ifdef BUILDFIXED
410   /* build fixed tables if not already */
411   if (!fixed_built)
412   {
413     int k;              /* temporary variable */
414     uInt f = 0;         /* number of hufts used in fixed_mem */
415     uIntf *c;           /* length list for huft_build */
416     uIntf *v;           /* work area for huft_build */
417
418     /* allocate memory */
419     if ((c = (uIntf*)ZALLOC(z, 288, sizeof(uInt))) == Z_NULL)
420       return Z_MEM_ERROR;
421     if ((v = (uIntf*)ZALLOC(z, 288, sizeof(uInt))) == Z_NULL)
422     {
423       ZFREE(z, c);
424       return Z_MEM_ERROR;
425     }
426
427     /* literal table */
428     for (k = 0; k < 144; k++)
429       c[k] = 8;
430     for (; k < 256; k++)
431       c[k] = 9;
432     for (; k < 280; k++)
433       c[k] = 7;
434     for (; k < 288; k++)
435       c[k] = 8;
436     fixed_bl = 9;
437     huft_build(c, 288, 257, cplens, cplext, &fixed_tl, &fixed_bl,
438                fixed_mem, &f, v);
439
440     /* distance table */
441     for (k = 0; k < 30; k++)
442       c[k] = 5;
443     fixed_bd = 5;
444     huft_build(c, 30, 0, cpdist, cpdext, &fixed_td, &fixed_bd,
445                fixed_mem, &f, v);
446
447     /* done */
448     ZFREE(z, v);
449     ZFREE(z, c);
450     fixed_built = 1;
451   }
452 #endif
453   *bl = fixed_bl;
454   *bd = fixed_bd;
455   *tl = fixed_tl;
456   *td = fixed_td;
457   return Z_OK;
458 }