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