summaryrefslogtreecommitdiffstats
path: root/cpukit/zlib/examples
diff options
context:
space:
mode:
Diffstat (limited to 'cpukit/zlib/examples')
-rw-r--r--cpukit/zlib/examples/enough.c569
-rw-r--r--cpukit/zlib/examples/gun.c701
-rw-r--r--cpukit/zlib/examples/zran.c404
3 files changed, 0 insertions, 1674 deletions
diff --git a/cpukit/zlib/examples/enough.c b/cpukit/zlib/examples/enough.c
deleted file mode 100644
index c40410bade..0000000000
--- a/cpukit/zlib/examples/enough.c
+++ /dev/null
@@ -1,569 +0,0 @@
-/* enough.c -- determine the maximum size of inflate's Huffman code tables over
- * all possible valid and complete Huffman codes, subject to a length limit.
- * Copyright (C) 2007, 2008 Mark Adler
- * Version 1.3 17 February 2008 Mark Adler
- */
-
-/* Version history:
- 1.0 3 Jan 2007 First version (derived from codecount.c version 1.4)
- 1.1 4 Jan 2007 Use faster incremental table usage computation
- Prune examine() search on previously visited states
- 1.2 5 Jan 2007 Comments clean up
- As inflate does, decrease root for short codes
- Refuse cases where inflate would increase root
- 1.3 17 Feb 2008 Add argument for initial root table size
- Fix bug for initial root table size == max - 1
- Use a macro to compute the history index
- */
-
-/*
- Examine all possible Huffman codes for a given number of symbols and a
- maximum code length in bits to determine the maximum table size for zilb's
- inflate. Only complete Huffman codes are counted.
-
- Two codes are considered distinct if the vectors of the number of codes per
- length are not identical. So permutations of the symbol assignments result
- in the same code for the counting, as do permutations of the assignments of
- the bit values to the codes (i.e. only canonical codes are counted).
-
- We build a code from shorter to longer lengths, determining how many symbols
- are coded at each length. At each step, we have how many symbols remain to
- be coded, what the last code length used was, and how many bit patterns of
- that length remain unused. Then we add one to the code length and double the
- number of unused patterns to graduate to the next code length. We then
- assign all portions of the remaining symbols to that code length that
- preserve the properties of a correct and eventually complete code. Those
- properties are: we cannot use more bit patterns than are available; and when
- all the symbols are used, there are exactly zero possible bit patterns
- remaining.
-
- The inflate Huffman decoding algorithm uses two-level lookup tables for
- speed. There is a single first-level table to decode codes up to root bits
- in length (root == 9 in the current inflate implementation). The table
- has 1 << root entries and is indexed by the next root bits of input. Codes
- shorter than root bits have replicated table entries, so that the correct
- entry is pointed to regardless of the bits that follow the short code. If
- the code is longer than root bits, then the table entry points to a second-
- level table. The size of that table is determined by the longest code with
- that root-bit prefix. If that longest code has length len, then the table
- has size 1 << (len - root), to index the remaining bits in that set of
- codes. Each subsequent root-bit prefix then has its own sub-table. The
- total number of table entries required by the code is calculated
- incrementally as the number of codes at each bit length is populated. When
- all of the codes are shorter than root bits, then root is reduced to the
- longest code length, resulting in a single, smaller, one-level table.
-
- The inflate algorithm also provides for small values of root (relative to
- the log2 of the number of symbols), where the shortest code has more bits
- than root. In that case, root is increased to the length of the shortest
- code. This program, by design, does not handle that case, so it is verified
- that the number of symbols is less than 2^(root + 1).
-
- In order to speed up the examination (by about ten orders of magnitude for
- the default arguments), the intermediate states in the build-up of a code
- are remembered and previously visited branches are pruned. The memory
- required for this will increase rapidly with the total number of symbols and
- the maximum code length in bits. However this is a very small price to pay
- for the vast speedup.
-
- First, all of the possible Huffman codes are counted, and reachable
- intermediate states are noted by a non-zero count in a saved-results array.
- Second, the intermediate states that lead to (root + 1) bit or longer codes
- are used to look at all sub-codes from those junctures for their inflate
- memory usage. (The amount of memory used is not affected by the number of
- codes of root bits or less in length.) Third, the visited states in the
- construction of those sub-codes and the associated calculation of the table
- size is recalled in order to avoid recalculating from the same juncture.
- Beginning the code examination at (root + 1) bit codes, which is enabled by
- identifying the reachable nodes, accounts for about six of the orders of
- magnitude of improvement for the default arguments. About another four
- orders of magnitude come from not revisiting previous states. Out of
- approximately 2x10^16 possible Huffman codes, only about 2x10^6 sub-codes
- need to be examined to cover all of the possible table memory usage cases
- for the default arguments of 286 symbols limited to 15-bit codes.
-
- Note that an unsigned long long type is used for counting. It is quite easy
- to exceed the capacity of an eight-byte integer with a large number of
- symbols and a large maximum code length, so multiple-precision arithmetic
- would need to replace the unsigned long long arithmetic in that case. This
- program will abort if an overflow occurs. The big_t type identifies where
- the counting takes place.
-
- An unsigned long long type is also used for calculating the number of
- possible codes remaining at the maximum length. This limits the maximum
- code length to the number of bits in a long long minus the number of bits
- needed to represent the symbols in a flat code. The code_t type identifies
- where the bit pattern counting takes place.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <assert.h>
-
-#define local static
-
-/* special data types */
-typedef unsigned long long big_t; /* type for code counting */
-typedef unsigned long long code_t; /* type for bit pattern counting */
-struct tab { /* type for been here check */
- size_t len; /* length of bit vector in char's */
- char *vec; /* allocated bit vector */
-};
-
-/* The array for saving results, num[], is indexed with this triplet:
-
- syms: number of symbols remaining to code
- left: number of available bit patterns at length len
- len: number of bits in the codes currently being assigned
-
- Those indices are constrained thusly when saving results:
-
- syms: 3..totsym (totsym == total symbols to code)
- left: 2..syms - 1, but only the evens (so syms == 8 -> 2, 4, 6)
- len: 1..max - 1 (max == maximum code length in bits)
-
- syms == 2 is not saved since that immediately leads to a single code. left
- must be even, since it represents the number of available bit patterns at
- the current length, which is double the number at the previous length.
- left ends at syms-1 since left == syms immediately results in a single code.
- (left > sym is not allowed since that would result in an incomplete code.)
- len is less than max, since the code completes immediately when len == max.
-
- The offset into the array is calculated for the three indices with the
- first one (syms) being outermost, and the last one (len) being innermost.
- We build the array with length max-1 lists for the len index, with syms-3
- of those for each symbol. There are totsym-2 of those, with each one
- varying in length as a function of sym. See the calculation of index in
- count() for the index, and the calculation of size in main() for the size
- of the array.
-
- For the deflate example of 286 symbols limited to 15-bit codes, the array
- has 284,284 entries, taking up 2.17 MB for an 8-byte big_t. More than
- half of the space allocated for saved results is actually used -- not all
- possible triplets are reached in the generation of valid Huffman codes.
- */
-
-/* The array for tracking visited states, done[], is itself indexed identically
- to the num[] array as described above for the (syms, left, len) triplet.
- Each element in the array is further indexed by the (mem, rem) doublet,
- where mem is the amount of inflate table space used so far, and rem is the
- remaining unused entries in the current inflate sub-table. Each indexed
- element is simply one bit indicating whether the state has been visited or
- not. Since the ranges for mem and rem are not known a priori, each bit
- vector is of a variable size, and grows as needed to accommodate the visited
- states. mem and rem are used to calculate a single index in a triangular
- array. Since the range of mem is expected in the default case to be about
- ten times larger than the range of rem, the array is skewed to reduce the
- memory usage, with eight times the range for mem than for rem. See the
- calculations for offset and bit in beenhere() for the details.
-
- For the deflate example of 286 symbols limited to 15-bit codes, the bit
- vectors grow to total approximately 21 MB, in addition to the 4.3 MB done[]
- array itself.
- */
-
-/* Globals to avoid propagating constants or constant pointers recursively */
-local int max; /* maximum allowed bit length for the codes */
-local int root; /* size of base code table in bits */
-local int large; /* largest code table so far */
-local size_t size; /* number of elements in num and done */
-local int *code; /* number of symbols assigned to each bit length */
-local big_t *num; /* saved results array for code counting */
-local struct tab *done; /* states already evaluated array */
-
-/* Index function for num[] and done[] */
-#define INDEX(i,j,k) (((size_t)((i-1)>>1)*((i-2)>>1)+(j>>1)-1)*(max-1)+k-1)
-
-/* Free allocated space. Uses globals code, num, and done. */
-local void cleanup(void)
-{
- size_t n;
-
- if (done != NULL) {
- for (n = 0; n < size; n++)
- if (done[n].len)
- free(done[n].vec);
- free(done);
- }
- if (num != NULL)
- free(num);
- if (code != NULL)
- free(code);
-}
-
-/* Return the number of possible Huffman codes using bit patterns of lengths
- len through max inclusive, coding syms symbols, with left bit patterns of
- length len unused -- return -1 if there is an overflow in the counting.
- Keep a record of previous results in num to prevent repeating the same
- calculation. Uses the globals max and num. */
-local big_t count(int syms, int len, int left)
-{
- big_t sum; /* number of possible codes from this juncture */
- big_t got; /* value returned from count() */
- int least; /* least number of syms to use at this juncture */
- int most; /* most number of syms to use at this juncture */
- int use; /* number of bit patterns to use in next call */
- size_t index; /* index of this case in *num */
-
- /* see if only one possible code */
- if (syms == left)
- return 1;
-
- /* note and verify the expected state */
- assert(syms > left && left > 0 && len < max);
-
- /* see if we've done this one already */
- index = INDEX(syms, left, len);
- got = num[index];
- if (got)
- return got; /* we have -- return the saved result */
-
- /* we need to use at least this many bit patterns so that the code won't be
- incomplete at the next length (more bit patterns than symbols) */
- least = (left << 1) - syms;
- if (least < 0)
- least = 0;
-
- /* we can use at most this many bit patterns, lest there not be enough
- available for the remaining symbols at the maximum length (if there were
- no limit to the code length, this would become: most = left - 1) */
- most = (((code_t)left << (max - len)) - syms) /
- (((code_t)1 << (max - len)) - 1);
-
- /* count all possible codes from this juncture and add them up */
- sum = 0;
- for (use = least; use <= most; use++) {
- got = count(syms - use, len + 1, (left - use) << 1);
- sum += got;
- if (got == -1 || sum < got) /* overflow */
- return -1;
- }
-
- /* verify that all recursive calls are productive */
- assert(sum != 0);
-
- /* save the result and return it */
- num[index] = sum;
- return sum;
-}
-
-/* Return true if we've been here before, set to true if not. Set a bit in a
- bit vector to indicate visiting this state. Each (syms,len,left) state
- has a variable size bit vector indexed by (mem,rem). The bit vector is
- lengthened if needed to allow setting the (mem,rem) bit. */
-local int beenhere(int syms, int len, int left, int mem, int rem)
-{
- size_t index; /* index for this state's bit vector */
- size_t offset; /* offset in this state's bit vector */
- int bit; /* mask for this state's bit */
- size_t length; /* length of the bit vector in bytes */
- char *vector; /* new or enlarged bit vector */
-
- /* point to vector for (syms,left,len), bit in vector for (mem,rem) */
- index = INDEX(syms, left, len);
- mem -= 1 << root;
- offset = (mem >> 3) + rem;
- offset = ((offset * (offset + 1)) >> 1) + rem;
- bit = 1 << (mem & 7);
-
- /* see if we've been here */
- length = done[index].len;
- if (offset < length && (done[index].vec[offset] & bit) != 0)
- return 1; /* done this! */
-
- /* we haven't been here before -- set the bit to show we have now */
-
- /* see if we need to lengthen the vector in order to set the bit */
- if (length <= offset) {
- /* if we have one already, enlarge it, zero out the appended space */
- if (length) {
- do {
- length <<= 1;
- } while (length <= offset);
- vector = realloc(done[index].vec, length);
- if (vector != NULL)
- memset(vector + done[index].len, 0, length - done[index].len);
- }
-
- /* otherwise we need to make a new vector and zero it out */
- else {
- length = 1 << (len - root);
- while (length <= offset)
- length <<= 1;
- vector = calloc(length, sizeof(char));
- }
-
- /* in either case, bail if we can't get the memory */
- if (vector == NULL) {
- fputs("abort: unable to allocate enough memory\n", stderr);
- cleanup();
- exit(1);
- }
-
- /* install the new vector */
- done[index].len = length;
- done[index].vec = vector;
- }
-
- /* set the bit */
- done[index].vec[offset] |= bit;
- return 0;
-}
-
-/* Examine all possible codes from the given node (syms, len, left). Compute
- the amount of memory required to build inflate's decoding tables, where the
- number of code structures used so far is mem, and the number remaining in
- the current sub-table is rem. Uses the globals max, code, root, large, and
- done. */
-local void examine(int syms, int len, int left, int mem, int rem)
-{
- int least; /* least number of syms to use at this juncture */
- int most; /* most number of syms to use at this juncture */
- int use; /* number of bit patterns to use in next call */
-
- /* see if we have a complete code */
- if (syms == left) {
- /* set the last code entry */
- code[len] = left;
-
- /* complete computation of memory used by this code */
- while (rem < left) {
- left -= rem;
- rem = 1 << (len - root);
- mem += rem;
- }
- assert(rem == left);
-
- /* if this is a new maximum, show the entries used and the sub-code */
- if (mem > large) {
- large = mem;
- printf("max %d: ", mem);
- for (use = root + 1; use <= max; use++)
- if (code[use])
- printf("%d[%d] ", code[use], use);
- putchar('\n');
- fflush(stdout);
- }
-
- /* remove entries as we drop back down in the recursion */
- code[len] = 0;
- return;
- }
-
- /* prune the tree if we can */
- if (beenhere(syms, len, left, mem, rem))
- return;
-
- /* we need to use at least this many bit patterns so that the code won't be
- incomplete at the next length (more bit patterns than symbols) */
- least = (left << 1) - syms;
- if (least < 0)
- least = 0;
-
- /* we can use at most this many bit patterns, lest there not be enough
- available for the remaining symbols at the maximum length (if there were
- no limit to the code length, this would become: most = left - 1) */
- most = (((code_t)left << (max - len)) - syms) /
- (((code_t)1 << (max - len)) - 1);
-
- /* occupy least table spaces, creating new sub-tables as needed */
- use = least;
- while (rem < use) {
- use -= rem;
- rem = 1 << (len - root);
- mem += rem;
- }
- rem -= use;
-
- /* examine codes from here, updating table space as we go */
- for (use = least; use <= most; use++) {
- code[len] = use;
- examine(syms - use, len + 1, (left - use) << 1,
- mem + (rem ? 1 << (len - root) : 0), rem << 1);
- if (rem == 0) {
- rem = 1 << (len - root);
- mem += rem;
- }
- rem--;
- }
-
- /* remove entries as we drop back down in the recursion */
- code[len] = 0;
-}
-
-/* Look at all sub-codes starting with root + 1 bits. Look at only the valid
- intermediate code states (syms, left, len). For each completed code,
- calculate the amount of memory required by inflate to build the decoding
- tables. Find the maximum amount of memory required and show the code that
- requires that maximum. Uses the globals max, root, and num. */
-local void enough(int syms)
-{
- int n; /* number of remaing symbols for this node */
- int left; /* number of unused bit patterns at this length */
- size_t index; /* index of this case in *num */
-
- /* clear code */
- for (n = 0; n <= max; n++)
- code[n] = 0;
-
- /* look at all (root + 1) bit and longer codes */
- large = 1 << root; /* base table */
- if (root < max) /* otherwise, there's only a base table */
- for (n = 3; n <= syms; n++)
- for (left = 2; left < n; left += 2)
- {
- /* look at all reachable (root + 1) bit nodes, and the
- resulting codes (complete at root + 2 or more) */
- index = INDEX(n, left, root + 1);
- if (root + 1 < max && num[index]) /* reachable node */
- examine(n, root + 1, left, 1 << root, 0);
-
- /* also look at root bit codes with completions at root + 1
- bits (not saved in num, since complete), just in case */
- if (num[index - 1] && n <= left << 1)
- examine((n - left) << 1, root + 1, (n - left) << 1,
- 1 << root, 0);
- }
-
- /* done */
- printf("done: maximum of %d table entries\n", large);
-}
-
-/*
- Examine and show the total number of possible Huffman codes for a given
- maximum number of symbols, initial root table size, and maximum code length
- in bits -- those are the command arguments in that order. The default
- values are 286, 9, and 15 respectively, for the deflate literal/length code.
- The possible codes are counted for each number of coded symbols from two to
- the maximum. The counts for each of those and the total number of codes are
- shown. The maximum number of inflate table entires is then calculated
- across all possible codes. Each new maximum number of table entries and the
- associated sub-code (starting at root + 1 == 10 bits) is shown.
-
- To count and examine Huffman codes that are not length-limited, provide a
- maximum length equal to the number of symbols minus one.
-
- For the deflate literal/length code, use "enough". For the deflate distance
- code, use "enough 30 6".
-
- This uses the %llu printf format to print big_t numbers, which assumes that
- big_t is an unsigned long long. If the big_t type is changed (for example
- to a multiple precision type), the method of printing will also need to be
- updated.
- */
-int main(int argc, char **argv)
-{
- int syms; /* total number of symbols to code */
- int n; /* number of symbols to code for this run */
- big_t got; /* return value of count() */
- big_t sum; /* accumulated number of codes over n */
-
- /* set up globals for cleanup() */
- code = NULL;
- num = NULL;
- done = NULL;
-
- /* get arguments -- default to the deflate literal/length code */
- syms = 286;
- root = 9;
- max = 15;
- if (argc > 1) {
- syms = atoi(argv[1]);
- if (argc > 2) {
- root = atoi(argv[2]);
- if (argc > 3)
- max = atoi(argv[3]);
- }
- }
- if (argc > 4 || syms < 2 || root < 1 || max < 1) {
- fputs("invalid arguments, need: [sym >= 2 [root >= 1 [max >= 1]]]\n",
- stderr);
- return 1;
- }
-
- /* if not restricting the code length, the longest is syms - 1 */
- if (max > syms - 1)
- max = syms - 1;
-
- /* determine the number of bits in a code_t */
- n = 0;
- while (((code_t)1 << n) != 0)
- n++;
-
- /* make sure that the calculation of most will not overflow */
- if (max > n || syms - 2 >= (((code_t)0 - 1) >> (max - 1))) {
- fputs("abort: code length too long for internal types\n", stderr);
- return 1;
- }
-
- /* reject impossible code requests */
- if (syms - 1 > ((code_t)1 << max) - 1) {
- fprintf(stderr, "%d symbols cannot be coded in %d bits\n",
- syms, max);
- return 1;
- }
-
- /* allocate code vector */
- code = calloc(max + 1, sizeof(int));
- if (code == NULL) {
- fputs("abort: unable to allocate enough memory\n", stderr);
- return 1;
- }
-
- /* determine size of saved results array, checking for overflows,
- allocate and clear the array (set all to zero with calloc()) */
- if (syms == 2) /* iff max == 1 */
- num = NULL; /* won't be saving any results */
- else {
- size = syms >> 1;
- if (size > ((size_t)0 - 1) / (n = (syms - 1) >> 1) ||
- (size *= n, size > ((size_t)0 - 1) / (n = max - 1)) ||
- (size *= n, size > ((size_t)0 - 1) / sizeof(big_t)) ||
- (num = calloc(size, sizeof(big_t))) == NULL) {
- fputs("abort: unable to allocate enough memory\n", stderr);
- cleanup();
- return 1;
- }
- }
-
- /* count possible codes for all numbers of symbols, add up counts */
- sum = 0;
- for (n = 2; n <= syms; n++) {
- got = count(n, 1, 2);
- sum += got;
- if (got == -1 || sum < got) { /* overflow */
- fputs("abort: can't count that high!\n", stderr);
- cleanup();
- return 1;
- }
- printf("%llu %d-codes\n", got, n);
- }
- printf("%llu total codes for 2 to %d symbols", sum, syms);
- if (max < syms - 1)
- printf(" (%d-bit length limit)\n", max);
- else
- puts(" (no length limit)");
-
- /* allocate and clear done array for beenhere() */
- if (syms == 2)
- done = NULL;
- else if (size > ((size_t)0 - 1) / sizeof(struct tab) ||
- (done = calloc(size, sizeof(struct tab))) == NULL) {
- fputs("abort: unable to allocate enough memory\n", stderr);
- cleanup();
- return 1;
- }
-
- /* find and show maximum inflate table usage */
- if (root > max) /* reduce root to max length */
- root = max;
- if (syms < ((code_t)1 << (root + 1)))
- enough(syms);
- else
- puts("cannot handle minimum code lengths > root");
-
- /* done */
- cleanup();
- return 0;
-}
diff --git a/cpukit/zlib/examples/gun.c b/cpukit/zlib/examples/gun.c
deleted file mode 100644
index 72b0882ab8..0000000000
--- a/cpukit/zlib/examples/gun.c
+++ /dev/null
@@ -1,701 +0,0 @@
-/* gun.c -- simple gunzip to give an example of the use of inflateBack()
- * Copyright (C) 2003, 2005, 2008, 2010 Mark Adler
- * For conditions of distribution and use, see copyright notice in zlib.h
- Version 1.6 17 January 2010 Mark Adler */
-
-/* Version history:
- 1.0 16 Feb 2003 First version for testing of inflateBack()
- 1.1 21 Feb 2005 Decompress concatenated gzip streams
- Remove use of "this" variable (C++ keyword)
- Fix return value for in()
- Improve allocation failure checking
- Add typecasting for void * structures
- Add -h option for command version and usage
- Add a bunch of comments
- 1.2 20 Mar 2005 Add Unix compress (LZW) decompression
- Copy file attributes from input file to output file
- 1.3 12 Jun 2005 Add casts for error messages [Oberhumer]
- 1.4 8 Dec 2006 LZW decompression speed improvements
- 1.5 9 Feb 2008 Avoid warning in latest version of gcc
- 1.6 17 Jan 2010 Avoid signed/unsigned comparison warnings
- */
-
-/*
- gun [ -t ] [ name ... ]
-
- decompresses the data in the named gzip files. If no arguments are given,
- gun will decompress from stdin to stdout. The names must end in .gz, -gz,
- .z, -z, _z, or .Z. The uncompressed data will be written to a file name
- with the suffix stripped. On success, the original file is deleted. On
- failure, the output file is deleted. For most failures, the command will
- continue to process the remaining names on the command line. A memory
- allocation failure will abort the command. If -t is specified, then the
- listed files or stdin will be tested as gzip files for integrity (without
- checking for a proper suffix), no output will be written, and no files
- will be deleted.
-
- Like gzip, gun allows concatenated gzip streams and will decompress them,
- writing all of the uncompressed data to the output. Unlike gzip, gun allows
- an empty file on input, and will produce no error writing an empty output
- file.
-
- gun will also decompress files made by Unix compress, which uses LZW
- compression. These files are automatically detected by virtue of their
- magic header bytes. Since the end of Unix compress stream is marked by the
- end-of-file, they cannot be concantenated. If a Unix compress stream is
- encountered in an input file, it is the last stream in that file.
-
- Like gunzip and uncompress, the file attributes of the orignal compressed
- file are maintained in the final uncompressed file, to the extent that the
- user permissions allow it.
-
- On my Mac OS X PowerPC G4, gun is almost twice as fast as gunzip (version
- 1.2.4) is on the same file, when gun is linked with zlib 1.2.2. Also the
- LZW decompression provided by gun is about twice as fast as the standard
- Unix uncompress command.
- */
-
-/* external functions and related types and constants */
-#include <stdio.h> /* fprintf() */
-#include <stdlib.h> /* malloc(), free() */
-#include <string.h> /* strerror(), strcmp(), strlen(), memcpy() */
-#include <errno.h> /* errno */
-#include <fcntl.h> /* open() */
-#include <unistd.h> /* read(), write(), close(), chown(), unlink() */
-#include <sys/types.h>
-#include <sys/stat.h> /* stat(), chmod() */
-#include <utime.h> /* utime() */
-#include "zlib.h" /* inflateBackInit(), inflateBack(), */
- /* inflateBackEnd(), crc32() */
-
-/* function declaration */
-#define local static
-
-/* buffer constants */
-#define SIZE 32768U /* input and output buffer sizes */
-#define PIECE 16384 /* limits i/o chunks for 16-bit int case */
-
-/* structure for infback() to pass to input function in() -- it maintains the
- input file and a buffer of size SIZE */
-struct ind {
- int infile;
- unsigned char *inbuf;
-};
-
-/* Load input buffer, assumed to be empty, and return bytes loaded and a
- pointer to them. read() is called until the buffer is full, or until it
- returns end-of-file or error. Return 0 on error. */
-local unsigned in(void *in_desc, unsigned char **buf)
-{
- int ret;
- unsigned len;
- unsigned char *next;
- struct ind *me = (struct ind *)in_desc;
-
- next = me->inbuf;
- *buf = next;
- len = 0;
- do {
- ret = PIECE;
- if ((unsigned)ret > SIZE - len)
- ret = (int)(SIZE - len);
- ret = (int)read(me->infile, next, ret);
- if (ret == -1) {
- len = 0;
- break;
- }
- next += ret;
- len += ret;
- } while (ret != 0 && len < SIZE);
- return len;
-}
-
-/* structure for infback() to pass to output function out() -- it maintains the
- output file, a running CRC-32 check on the output and the total number of
- bytes output, both for checking against the gzip trailer. (The length in
- the gzip trailer is stored modulo 2^32, so it's ok if a long is 32 bits and
- the output is greater than 4 GB.) */
-struct outd {
- int outfile;
- int check; /* true if checking crc and total */
- unsigned long crc;
- unsigned long total;
-};
-
-/* Write output buffer and update the CRC-32 and total bytes written. write()
- is called until all of the output is written or an error is encountered.
- On success out() returns 0. For a write failure, out() returns 1. If the
- output file descriptor is -1, then nothing is written.
- */
-local int out(void *out_desc, unsigned char *buf, unsigned len)
-{
- int ret;
- struct outd *me = (struct outd *)out_desc;
-
- if (me->check) {
- me->crc = crc32(me->crc, buf, len);
- me->total += len;
- }
- if (me->outfile != -1)
- do {
- ret = PIECE;
- if ((unsigned)ret > len)
- ret = (int)len;
- ret = (int)write(me->outfile, buf, ret);
- if (ret == -1)
- return 1;
- buf += ret;
- len -= ret;
- } while (len != 0);
- return 0;
-}
-
-/* next input byte macro for use inside lunpipe() and gunpipe() */
-#define NEXT() (have ? 0 : (have = in(indp, &next)), \
- last = have ? (have--, (int)(*next++)) : -1)
-
-/* memory for gunpipe() and lunpipe() --
- the first 256 entries of prefix[] and suffix[] are never used, could
- have offset the index, but it's faster to waste the memory */
-unsigned char inbuf[SIZE]; /* input buffer */
-unsigned char outbuf[SIZE]; /* output buffer */
-unsigned short prefix[65536]; /* index to LZW prefix string */
-unsigned char suffix[65536]; /* one-character LZW suffix */
-unsigned char match[65280 + 2]; /* buffer for reversed match or gzip
- 32K sliding window */
-
-/* throw out what's left in the current bits byte buffer (this is a vestigial
- aspect of the compressed data format derived from an implementation that
- made use of a special VAX machine instruction!) */
-#define FLUSHCODE() \
- do { \
- left = 0; \
- rem = 0; \
- if (chunk > have) { \
- chunk -= have; \
- have = 0; \
- if (NEXT() == -1) \
- break; \
- chunk--; \
- if (chunk > have) { \
- chunk = have = 0; \
- break; \
- } \
- } \
- have -= chunk; \
- next += chunk; \
- chunk = 0; \
- } while (0)
-
-/* Decompress a compress (LZW) file from indp to outfile. The compress magic
- header (two bytes) has already been read and verified. There are have bytes
- of buffered input at next. strm is used for passing error information back
- to gunpipe().
-
- lunpipe() will return Z_OK on success, Z_BUF_ERROR for an unexpected end of
- file, read error, or write error (a write error indicated by strm->next_in
- not equal to Z_NULL), or Z_DATA_ERROR for invalid input.
- */
-local int lunpipe(unsigned have, unsigned char *next, struct ind *indp,
- int outfile, z_stream *strm)
-{
- int last; /* last byte read by NEXT(), or -1 if EOF */
- unsigned chunk; /* bytes left in current chunk */
- int left; /* bits left in rem */
- unsigned rem; /* unused bits from input */
- int bits; /* current bits per code */
- unsigned code; /* code, table traversal index */
- unsigned mask; /* mask for current bits codes */
- int max; /* maximum bits per code for this stream */
- unsigned flags; /* compress flags, then block compress flag */
- unsigned end; /* last valid entry in prefix/suffix tables */
- unsigned temp; /* current code */
- unsigned prev; /* previous code */
- unsigned final; /* last character written for previous code */
- unsigned stack; /* next position for reversed string */
- unsigned outcnt; /* bytes in output buffer */
- struct outd outd; /* output structure */
- unsigned char *p;
-
- /* set up output */
- outd.outfile = outfile;
- outd.check = 0;
-
- /* process remainder of compress header -- a flags byte */
- flags = NEXT();
- if (last == -1)
- return Z_BUF_ERROR;
- if (flags & 0x60) {
- strm->msg = (char *)"unknown lzw flags set";
- return Z_DATA_ERROR;
- }
- max = flags & 0x1f;
- if (max < 9 || max > 16) {
- strm->msg = (char *)"lzw bits out of range";
- return Z_DATA_ERROR;
- }
- if (max == 9) /* 9 doesn't really mean 9 */
- max = 10;
- flags &= 0x80; /* true if block compress */
-
- /* clear table */
- bits = 9;
- mask = 0x1ff;
- end = flags ? 256 : 255;
-
- /* set up: get first 9-bit code, which is the first decompressed byte, but
- don't create a table entry until the next code */
- if (NEXT() == -1) /* no compressed data is ok */
- return Z_OK;
- final = prev = (unsigned)last; /* low 8 bits of code */
- if (NEXT() == -1) /* missing a bit */
- return Z_BUF_ERROR;
- if (last & 1) { /* code must be < 256 */
- strm->msg = (char *)"invalid lzw code";
- return Z_DATA_ERROR;
- }
- rem = (unsigned)last >> 1; /* remaining 7 bits */
- left = 7;
- chunk = bits - 2; /* 7 bytes left in this chunk */
- outbuf[0] = (unsigned char)final; /* write first decompressed byte */
- outcnt = 1;
-
- /* decode codes */
- stack = 0;
- for (;;) {
- /* if the table will be full after this, increment the code size */
- if (end >= mask && bits < max) {
- FLUSHCODE();
- bits++;
- mask <<= 1;
- mask++;
- }
-
- /* get a code of length bits */
- if (chunk == 0) /* decrement chunk modulo bits */
- chunk = bits;
- code = rem; /* low bits of code */
- if (NEXT() == -1) { /* EOF is end of compressed data */
- /* write remaining buffered output */
- if (outcnt && out(&outd, outbuf, outcnt)) {
- strm->next_in = outbuf; /* signal write error */
- return Z_BUF_ERROR;
- }
- return Z_OK;
- }
- code += (unsigned)last << left; /* middle (or high) bits of code */
- left += 8;
- chunk--;
- if (bits > left) { /* need more bits */
- if (NEXT() == -1) /* can't end in middle of code */
- return Z_BUF_ERROR;
- code += (unsigned)last << left; /* high bits of code */
- left += 8;
- chunk--;
- }
- code &= mask; /* mask to current code length */
- left -= bits; /* number of unused bits */
- rem = (unsigned)last >> (8 - left); /* unused bits from last byte */
-
- /* process clear code (256) */
- if (code == 256 && flags) {
- FLUSHCODE();
- bits = 9; /* initialize bits and mask */
- mask = 0x1ff;
- end = 255; /* empty table */
- continue; /* get next code */
- }
-
- /* special code to reuse last match */
- temp = code; /* save the current code */
- if (code > end) {
- /* Be picky on the allowed code here, and make sure that the code
- we drop through (prev) will be a valid index so that random
- input does not cause an exception. The code != end + 1 check is
- empirically derived, and not checked in the original uncompress
- code. If this ever causes a problem, that check could be safely
- removed. Leaving this check in greatly improves gun's ability
- to detect random or corrupted input after a compress header.
- In any case, the prev > end check must be retained. */
- if (code != end + 1 || prev > end) {
- strm->msg = (char *)"invalid lzw code";
- return Z_DATA_ERROR;
- }
- match[stack++] = (unsigned char)final;
- code = prev;
- }
-
- /* walk through linked list to generate output in reverse order */
- p = match + stack;
- while (code >= 256) {
- *p++ = suffix[code];
- code = prefix[code];
- }
- stack = p - match;
- match[stack++] = (unsigned char)code;
- final = code;
-
- /* link new table entry */
- if (end < mask) {
- end++;
- prefix[end] = (unsigned short)prev;
- suffix[end] = (unsigned char)final;
- }
-
- /* set previous code for next iteration */
- prev = temp;
-
- /* write output in forward order */
- while (stack > SIZE - outcnt) {
- while (outcnt < SIZE)
- outbuf[outcnt++] = match[--stack];
- if (out(&outd, outbuf, outcnt)) {
- strm->next_in = outbuf; /* signal write error */
- return Z_BUF_ERROR;
- }
- outcnt = 0;
- }
- p = match + stack;
- do {
- outbuf[outcnt++] = *--p;
- } while (p > match);
- stack = 0;
-
- /* loop for next code with final and prev as the last match, rem and
- left provide the first 0..7 bits of the next code, end is the last
- valid table entry */
- }
-}
-
-/* Decompress a gzip file from infile to outfile. strm is assumed to have been
- successfully initialized with inflateBackInit(). The input file may consist
- of a series of gzip streams, in which case all of them will be decompressed
- to the output file. If outfile is -1, then the gzip stream(s) integrity is
- checked and nothing is written.
-
- The return value is a zlib error code: Z_MEM_ERROR if out of memory,
- Z_DATA_ERROR if the header or the compressed data is invalid, or if the
- trailer CRC-32 check or length doesn't match, Z_BUF_ERROR if the input ends
- prematurely or a write error occurs, or Z_ERRNO if junk (not a another gzip
- stream) follows a valid gzip stream.
- */
-local int gunpipe(z_stream *strm, int infile, int outfile)
-{
- int ret, first, last;
- unsigned have, flags, len;
- unsigned char *next = NULL;
- struct ind ind, *indp;
- struct outd outd;
-
- /* setup input buffer */
- ind.infile = infile;
- ind.inbuf = inbuf;
- indp = &ind;
-
- /* decompress concatenated gzip streams */
- have = 0; /* no input data read in yet */
- first = 1; /* looking for first gzip header */
- strm->next_in = Z_NULL; /* so Z_BUF_ERROR means EOF */
- for (;;) {
- /* look for the two magic header bytes for a gzip stream */
- if (NEXT() == -1) {
- ret = Z_OK;
- break; /* empty gzip stream is ok */
- }
- if (last != 31 || (NEXT() != 139 && last != 157)) {
- strm->msg = (char *)"incorrect header check";
- ret = first ? Z_DATA_ERROR : Z_ERRNO;
- break; /* not a gzip or compress header */
- }
- first = 0; /* next non-header is junk */
-
- /* process a compress (LZW) file -- can't be concatenated after this */
- if (last == 157) {
- ret = lunpipe(have, next, indp, outfile, strm);
- break;
- }
-
- /* process remainder of gzip header */
- ret = Z_BUF_ERROR;
- if (NEXT() != 8) { /* only deflate method allowed */
- if (last == -1) break;
- strm->msg = (char *)"unknown compression method";
- ret = Z_DATA_ERROR;
- break;
- }
- flags = NEXT(); /* header flags */
- NEXT(); /* discard mod time, xflgs, os */
- NEXT();
- NEXT();
- NEXT();
- NEXT();
- NEXT();
- if (last == -1) break;
- if (flags & 0xe0) {
- strm->msg = (char *)"unknown header flags set";
- ret = Z_DATA_ERROR;
- break;
- }
- if (flags & 4) { /* extra field */
- len = NEXT();
- len += (unsigned)(NEXT()) << 8;
- if (last == -1) break;
- while (len > have) {
- len -= have;
- have = 0;
- if (NEXT() == -1) break;
- len--;
- }
- if (last == -1) break;
- have -= len;
- next += len;
- }
- if (flags & 8) /* file name */
- while (NEXT() != 0 && last != -1)
- ;
- if (flags & 16) /* comment */
- while (NEXT() != 0 && last != -1)
- ;
- if (flags & 2) { /* header crc */
- NEXT();
- NEXT();
- }
- if (last == -1) break;
-
- /* set up output */
- outd.outfile = outfile;
- outd.check = 1;
- outd.crc = crc32(0L, Z_NULL, 0);
- outd.total = 0;
-
- /* decompress data to output */
- strm->next_in = next;
- strm->avail_in = have;
- ret = inflateBack(strm, in, indp, out, &outd);
- if (ret != Z_STREAM_END) break;
- next = strm->next_in;
- have = strm->avail_in;
- strm->next_in = Z_NULL; /* so Z_BUF_ERROR means EOF */
-
- /* check trailer */
- ret = Z_BUF_ERROR;
- if (NEXT() != (int)(outd.crc & 0xff) ||
- NEXT() != (int)((outd.crc >> 8) & 0xff) ||
- NEXT() != (int)((outd.crc >> 16) & 0xff) ||
- NEXT() != (int)((outd.crc >> 24) & 0xff)) {
- /* crc error */
- if (last != -1) {
- strm->msg = (char *)"incorrect data check";
- ret = Z_DATA_ERROR;
- }
- break;
- }
- if (NEXT() != (int)(outd.total & 0xff) ||
- NEXT() != (int)((outd.total >> 8) & 0xff) ||
- NEXT() != (int)((outd.total >> 16) & 0xff) ||
- NEXT() != (int)((outd.total >> 24) & 0xff)) {
- /* length error */
- if (last != -1) {
- strm->msg = (char *)"incorrect length check";
- ret = Z_DATA_ERROR;
- }
- break;
- }
-
- /* go back and look for another gzip stream */
- }
-
- /* clean up and return */
- return ret;
-}
-
-/* Copy file attributes, from -> to, as best we can. This is best effort, so
- no errors are reported. The mode bits, including suid, sgid, and the sticky
- bit are copied (if allowed), the owner's user id and group id are copied
- (again if allowed), and the access and modify times are copied. */
-local void copymeta(char *from, char *to)
-{
- struct stat was;
- struct utimbuf when;
-
- /* get all of from's Unix meta data, return if not a regular file */
- if (stat(from, &was) != 0 || (was.st_mode & S_IFMT) != S_IFREG)
- return;
-
- /* set to's mode bits, ignore errors */
- (void)chmod(to, was.st_mode & 07777);
-
- /* copy owner's user and group, ignore errors */
- (void)chown(to, was.st_uid, was.st_gid);
-
- /* copy access and modify times, ignore errors */
- when.actime = was.st_atime;
- when.modtime = was.st_mtime;
- (void)utime(to, &when);
-}
-
-/* Decompress the file inname to the file outnname, of if test is true, just
- decompress without writing and check the gzip trailer for integrity. If
- inname is NULL or an empty string, read from stdin. If outname is NULL or
- an empty string, write to stdout. strm is a pre-initialized inflateBack
- structure. When appropriate, copy the file attributes from inname to
- outname.
-
- gunzip() returns 1 if there is an out-of-memory error or an unexpected
- return code from gunpipe(). Otherwise it returns 0.
- */
-local int gunzip(z_stream *strm, char *inname, char *outname, int test)
-{
- int ret;
- int infile, outfile;
-
- /* open files */
- if (inname == NULL || *inname == 0) {
- inname = "-";
- infile = 0; /* stdin */
- }
- else {
- infile = open(inname, O_RDONLY, 0);
- if (infile == -1) {
- fprintf(stderr, "gun cannot open %s\n", inname);
- return 0;
- }
- }
- if (test)
- outfile = -1;
- else if (outname == NULL || *outname == 0) {
- outname = "-";
- outfile = 1; /* stdout */
- }
- else {
- outfile = open(outname, O_CREAT | O_TRUNC | O_WRONLY, 0666);
- if (outfile == -1) {
- close(infile);
- fprintf(stderr, "gun cannot create %s\n", outname);
- return 0;
- }
- }
- errno = 0;
-
- /* decompress */
- ret = gunpipe(strm, infile, outfile);
- if (outfile > 2) close(outfile);
- if (infile > 2) close(infile);
-
- /* interpret result */
- switch (ret) {
- case Z_OK:
- case Z_ERRNO:
- if (infile > 2 && outfile > 2) {
- copymeta(inname, outname); /* copy attributes */
- unlink(inname);
- }
- if (ret == Z_ERRNO)
- fprintf(stderr, "gun warning: trailing garbage ignored in %s\n",
- inname);
- break;
- case Z_DATA_ERROR:
- if (outfile > 2) unlink(outname);
- fprintf(stderr, "gun data error on %s: %s\n", inname, strm->msg);
- break;
- case Z_MEM_ERROR:
- if (outfile > 2) unlink(outname);
- fprintf(stderr, "gun out of memory error--aborting\n");
- return 1;
- case Z_BUF_ERROR:
- if (outfile > 2) unlink(outname);
- if (strm->next_in != Z_NULL) {
- fprintf(stderr, "gun write error on %s: %s\n",
- outname, strerror(errno));
- }
- else if (errno) {
- fprintf(stderr, "gun read error on %s: %s\n",
- inname, strerror(errno));
- }
- else {
- fprintf(stderr, "gun unexpected end of file on %s\n",
- inname);
- }
- break;
- default:
- if (outfile > 2) unlink(outname);
- fprintf(stderr, "gun internal error--aborting\n");
- return 1;
- }
- return 0;
-}
-
-/* Process the gun command line arguments. See the command syntax near the
- beginning of this source file. */
-int main(int argc, char **argv)
-{
- int ret, len, test;
- char *outname;
- unsigned char *window;
- z_stream strm;
-
- /* initialize inflateBack state for repeated use */
- window = match; /* reuse LZW match buffer */
- strm.zalloc = Z_NULL;
- strm.zfree = Z_NULL;
- strm.opaque = Z_NULL;
- ret = inflateBackInit(&strm, 15, window);
- if (ret != Z_OK) {
- fprintf(stderr, "gun out of memory error--aborting\n");
- return 1;
- }
-
- /* decompress each file to the same name with the suffix removed */
- argc--;
- argv++;
- test = 0;
- if (argc && strcmp(*argv, "-h") == 0) {
- fprintf(stderr, "gun 1.6 (17 Jan 2010)\n");
- fprintf(stderr, "Copyright (C) 2003-2010 Mark Adler\n");
- fprintf(stderr, "usage: gun [-t] [file1.gz [file2.Z ...]]\n");
- return 0;
- }
- if (argc && strcmp(*argv, "-t") == 0) {
- test = 1;
- argc--;
- argv++;
- }
- if (argc)
- do {
- if (test)
- outname = NULL;
- else {
- len = (int)strlen(*argv);
- if (strcmp(*argv + len - 3, ".gz") == 0 ||
- strcmp(*argv + len - 3, "-gz") == 0)
- len -= 3;
- else if (strcmp(*argv + len - 2, ".z") == 0 ||
- strcmp(*argv + len - 2, "-z") == 0 ||
- strcmp(*argv + len - 2, "_z") == 0 ||
- strcmp(*argv + len - 2, ".Z") == 0)
- len -= 2;
- else {
- fprintf(stderr, "gun error: no gz type on %s--skipping\n",
- *argv);
- continue;
- }
- outname = malloc(len + 1);
- if (outname == NULL) {
- fprintf(stderr, "gun out of memory error--aborting\n");
- ret = 1;
- break;
- }
- memcpy(outname, *argv, len);
- outname[len] = 0;
- }
- ret = gunzip(&strm, *argv, outname, test);
- if (outname != NULL) free(outname);
- if (ret) break;
- } while (argv++, --argc);
- else
- ret = gunzip(&strm, NULL, NULL, test);
-
- /* clean up */
- inflateBackEnd(&strm);
- return ret;
-}
diff --git a/cpukit/zlib/examples/zran.c b/cpukit/zlib/examples/zran.c
deleted file mode 100644
index 617a13086f..0000000000
--- a/cpukit/zlib/examples/zran.c
+++ /dev/null
@@ -1,404 +0,0 @@
-/* zran.c -- example of zlib/gzip stream indexing and random access
- * Copyright (C) 2005 Mark Adler
- * For conditions of distribution and use, see copyright notice in zlib.h
- Version 1.0 29 May 2005 Mark Adler */
-
-/* Illustrate the use of Z_BLOCK, inflatePrime(), and inflateSetDictionary()
- for random access of a compressed file. A file containing a zlib or gzip
- stream is provided on the command line. The compressed stream is decoded in
- its entirety, and an index built with access points about every SPAN bytes
- in the uncompressed output. The compressed file is left open, and can then
- be read randomly, having to decompress on the average SPAN/2 uncompressed
- bytes before getting to the desired block of data.
-
- An access point can be created at the start of any deflate block, by saving
- the starting file offset and bit of that block, and the 32K bytes of
- uncompressed data that precede that block. Also the uncompressed offset of
- that block is saved to provide a referece for locating a desired starting
- point in the uncompressed stream. build_index() works by decompressing the
- input zlib or gzip stream a block at a time, and at the end of each block
- deciding if enough uncompressed data has gone by to justify the creation of
- a new access point. If so, that point is saved in a data structure that
- grows as needed to accommodate the points.
-
- To use the index, an offset in the uncompressed data is provided, for which
- the latest accees point at or preceding that offset is located in the index.
- The input file is positioned to the specified location in the index, and if
- necessary the first few bits of the compressed data is read from the file.
- inflate is initialized with those bits and the 32K of uncompressed data, and
- the decompression then proceeds until the desired offset in the file is
- reached. Then the decompression continues to read the desired uncompressed
- data from the file.
-
- Another approach would be to generate the index on demand. In that case,
- requests for random access reads from the compressed data would try to use
- the index, but if a read far enough past the end of the index is required,
- then further index entries would be generated and added.
-
- There is some fair bit of overhead to starting inflation for the random
- access, mainly copying the 32K byte dictionary. So if small pieces of the
- file are being accessed, it would make sense to implement a cache to hold
- some lookahead and avoid many calls to extract() for small lengths.
-
- Another way to build an index would be to use inflateCopy(). That would
- not be constrained to have access points at block boundaries, but requires
- more memory per access point, and also cannot be saved to file due to the
- use of pointers in the state. The approach here allows for storage of the
- index in a file.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include "zlib.h"
-
-#define local static
-
-#define SPAN 1048576L /* desired distance between access points */
-#define WINSIZE 32768U /* sliding window size */
-#define CHUNK 16384 /* file input buffer size */
-
-/* access point entry */
-struct point {
- off_t out; /* corresponding offset in uncompressed data */
- off_t in; /* offset in input file of first full byte */
- int bits; /* number of bits (1-7) from byte at in - 1, or 0 */
- unsigned char window[WINSIZE]; /* preceding 32K of uncompressed data */
-};
-
-/* access point list */
-struct access {
- int have; /* number of list entries filled in */
- int size; /* number of list entries allocated */
- struct point *list; /* allocated list */
-};
-
-/* Deallocate an index built by build_index() */
-local void free_index(struct access *index)
-{
- if (index != NULL) {
- free(index->list);
- free(index);
- }
-}
-
-/* Add an entry to the access point list. If out of memory, deallocate the
- existing list and return NULL. */
-local struct access *addpoint(struct access *index, int bits,
- off_t in, off_t out, unsigned left, unsigned char *window)
-{
- struct point *next;
-
- /* if list is empty, create it (start with eight points) */
- if (index == NULL) {
- index = malloc(sizeof(struct access));
- if (index == NULL) return NULL;
- index->list = malloc(sizeof(struct point) << 3);
- if (index->list == NULL) {
- free(index);
- return NULL;
- }
- index->size = 8;
- index->have = 0;
- }
-
- /* if list is full, make it bigger */
- else if (index->have == index->size) {
- index->size <<= 1;
- next = realloc(index->list, sizeof(struct point) * index->size);
- if (next == NULL) {
- free_index(index);
- return NULL;
- }
- index->list = next;
- }
-
- /* fill in entry and increment how many we have */
- next = index->list + index->have;
- next->bits = bits;
- next->in = in;
- next->out = out;
- if (left)
- memcpy(next->window, window + WINSIZE - left, left);
- if (left < WINSIZE)
- memcpy(next->window + left, window, WINSIZE - left);
- index->have++;
-
- /* return list, possibly reallocated */
- return index;
-}
-
-/* Make one entire pass through the compressed stream and build an index, with
- access points about every span bytes of uncompressed output -- span is
- chosen to balance the speed of random access against the memory requirements
- of the list, about 32K bytes per access point. Note that data after the end
- of the first zlib or gzip stream in the file is ignored. build_index()
- returns the number of access points on success (>= 1), Z_MEM_ERROR for out
- of memory, Z_DATA_ERROR for an error in the input file, or Z_ERRNO for a
- file read error. On success, *built points to the resulting index. */
-local int build_index(FILE *in, off_t span, struct access **built)
-{
- int ret;
- off_t totin, totout; /* our own total counters to avoid 4GB limit */
- off_t last; /* totout value of last access point */
- struct access *index; /* access points being generated */
- z_stream strm;
- unsigned char input[CHUNK];
- unsigned char window[WINSIZE];
-
- /* initialize inflate */
- strm.zalloc = Z_NULL;
- strm.zfree = Z_NULL;
- strm.opaque = Z_NULL;
- strm.avail_in = 0;
- strm.next_in = Z_NULL;
- ret = inflateInit2(&strm, 47); /* automatic zlib or gzip decoding */
- if (ret != Z_OK)
- return ret;
-
- /* inflate the input, maintain a sliding window, and build an index -- this
- also validates the integrity of the compressed data using the check
- information at the end of the gzip or zlib stream */
- totin = totout = last = 0;
- index = NULL; /* will be allocated by first addpoint() */
- strm.avail_out = 0;
- do {
- /* get some compressed data from input file */
- strm.avail_in = fread(input, 1, CHUNK, in);
- if (ferror(in)) {
- ret = Z_ERRNO;
- goto build_index_error;
- }
- if (strm.avail_in == 0) {
- ret = Z_DATA_ERROR;
- goto build_index_error;
- }
- strm.next_in = input;
-
- /* process all of that, or until end of stream */
- do {
- /* reset sliding window if necessary */
- if (strm.avail_out == 0) {
- strm.avail_out = WINSIZE;
- strm.next_out = window;
- }
-
- /* inflate until out of input, output, or at end of block --
- update the total input and output counters */
- totin += strm.avail_in;
- totout += strm.avail_out;
- ret = inflate(&strm, Z_BLOCK); /* return at end of block */
- totin -= strm.avail_in;
- totout -= strm.avail_out;
- if (ret == Z_NEED_DICT)
- ret = Z_DATA_ERROR;
- if (ret == Z_MEM_ERROR || ret == Z_DATA_ERROR)
- goto build_index_error;
- if (ret == Z_STREAM_END)
- break;
-
- /* if at end of block, consider adding an index entry (note that if
- data_type indicates an end-of-block, then all of the
- uncompressed data from that block has been delivered, and none
- of the compressed data after that block has been consumed,
- except for up to seven bits) -- the totout == 0 provides an
- entry point after the zlib or gzip header, and assures that the
- index always has at least one access point; we avoid creating an
- access point after the last block by checking bit 6 of data_type
- */
- if ((strm.data_type & 128) && !(strm.data_type & 64) &&
- (totout == 0 || totout - last > span)) {
- index = addpoint(index, strm.data_type & 7, totin,
- totout, strm.avail_out, window);
- if (index == NULL) {
- ret = Z_MEM_ERROR;
- goto build_index_error;
- }
- last = totout;
- }
- } while (strm.avail_in != 0);
- } while (ret != Z_STREAM_END);
-
- /* clean up and return index (release unused entries in list) */
- (void)inflateEnd(&strm);
- index = realloc(index, sizeof(struct point) * index->have);
- index->size = index->have;
- *built = index;
- return index->size;
-
- /* return error */
- build_index_error:
- (void)inflateEnd(&strm);
- if (index != NULL)
- free_index(index);
- return ret;
-}
-
-/* Use the index to read len bytes from offset into buf, return bytes read or
- negative for error (Z_DATA_ERROR or Z_MEM_ERROR). If data is requested past
- the end of the uncompressed data, then extract() will return a value less
- than len, indicating how much as actually read into buf. This function
- should not return a data error unless the file was modified since the index
- was generated. extract() may also return Z_ERRNO if there is an error on
- reading or seeking the input file. */
-local int extract(FILE *in, struct access *index, off_t offset,
- unsigned char *buf, int len)
-{
- int ret, skip;
- z_stream strm;
- struct point *here;
- unsigned char input[CHUNK];
- unsigned char discard[WINSIZE];
-
- /* proceed only if something reasonable to do */
- if (len < 0)
- return 0;
-
- /* find where in stream to start */
- here = index->list;
- ret = index->have;
- while (--ret && here[1].out <= offset)
- here++;
-
- /* initialize file and inflate state to start there */
- strm.zalloc = Z_NULL;
- strm.zfree = Z_NULL;
- strm.opaque = Z_NULL;
- strm.avail_in = 0;
- strm.next_in = Z_NULL;
- ret = inflateInit2(&strm, -15); /* raw inflate */
- if (ret != Z_OK)
- return ret;
- ret = fseeko(in, here->in - (here->bits ? 1 : 0), SEEK_SET);
- if (ret == -1)
- goto extract_ret;
- if (here->bits) {
- ret = getc(in);
- if (ret == -1) {
- ret = ferror(in) ? Z_ERRNO : Z_DATA_ERROR;
- goto extract_ret;
- }
- (void)inflatePrime(&strm, here->bits, ret >> (8 - here->bits));
- }
- (void)inflateSetDictionary(&strm, here->window, WINSIZE);
-
- /* skip uncompressed bytes until offset reached, then satisfy request */
- offset -= here->out;
- strm.avail_in = 0;
- skip = 1; /* while skipping to offset */
- do {
- /* define where to put uncompressed data, and how much */
- if (offset == 0 && skip) { /* at offset now */
- strm.avail_out = len;
- strm.next_out = buf;
- skip = 0; /* only do this once */
- }
- if (offset > WINSIZE) { /* skip WINSIZE bytes */
- strm.avail_out = WINSIZE;
- strm.next_out = discard;
- offset -= WINSIZE;
- }
- else if (offset != 0) { /* last skip */
- strm.avail_out = (unsigned)offset;
- strm.next_out = discard;
- offset = 0;
- }
-
- /* uncompress until avail_out filled, or end of stream */
- do {
- if (strm.avail_in == 0) {
- strm.avail_in = fread(input, 1, CHUNK, in);
- if (ferror(in)) {
- ret = Z_ERRNO;
- goto extract_ret;
- }
- if (strm.avail_in == 0) {
- ret = Z_DATA_ERROR;
- goto extract_ret;
- }
- strm.next_in = input;
- }
- ret = inflate(&strm, Z_NO_FLUSH); /* normal inflate */
- if (ret == Z_NEED_DICT)
- ret = Z_DATA_ERROR;
- if (ret == Z_MEM_ERROR || ret == Z_DATA_ERROR)
- goto extract_ret;
- if (ret == Z_STREAM_END)
- break;
- } while (strm.avail_out != 0);
-
- /* if reach end of stream, then don't keep trying to get more */
- if (ret == Z_STREAM_END)
- break;
-
- /* do until offset reached and requested data read, or stream ends */
- } while (skip);
-
- /* compute number of uncompressed bytes read after offset */
- ret = skip ? 0 : len - strm.avail_out;
-
- /* clean up and return bytes read or error */
- extract_ret:
- (void)inflateEnd(&strm);
- return ret;
-}
-
-/* Demonstrate the use of build_index() and extract() by processing the file
- provided on the command line, and the extracting 16K from about 2/3rds of
- the way through the uncompressed output, and writing that to stdout. */
-int main(int argc, char **argv)
-{
- int len;
- off_t offset;
- FILE *in;
- struct access *index = NULL;
- unsigned char buf[CHUNK];
-
- /* open input file */
- if (argc != 2) {
- fprintf(stderr, "usage: zran file.gz\n");
- return 1;
- }
- in = fopen(argv[1], "rb");
- if (in == NULL) {
- fprintf(stderr, "zran: could not open %s for reading\n", argv[1]);
- return 1;
- }
-
- /* build index */
- len = build_index(in, SPAN, &index);
- if (len < 0) {
- fclose(in);
- switch (len) {
- case Z_MEM_ERROR:
- fprintf(stderr, "zran: out of memory\n");
- break;
- case Z_DATA_ERROR:
- fprintf(stderr, "zran: compressed data error in %s\n", argv[1]);
- break;
- case Z_ERRNO:
- fprintf(stderr, "zran: read error on %s\n", argv[1]);
- break;
- default:
- fprintf(stderr, "zran: error %d while building index\n", len);
- }
- return 1;
- }
- fprintf(stderr, "zran: built index with %d access points\n", len);
-
- /* use index by reading some bytes from an arbitrary offset */
- offset = (index->list[index->have - 1].out << 1) / 3;
- len = extract(in, index, offset, buf, CHUNK);
- if (len < 0)
- fprintf(stderr, "zran: extraction failed: %s error\n",
- len == Z_MEM_ERROR ? "out of memory" : "input corrupted");
- else {
- fwrite(buf, 1, len, stdout);
- fprintf(stderr, "zran: extracted %d bytes at %llu\n", len, offset);
- }
-
- /* clean up and exit */
- free_index(index);
- fclose(in);
- return 0;
-}