vendor zlib instead of relying on system version (#306)

### Motivation:

Relying on the system zlib causes issues if that library (or its
headers) doesn't ship with the system.

### Modifications:

Vendor it.

### Result:

- Fewer dependencies.
- Binary size increase negligible. The _sum of the debug builds_ of all
`.o` files is less than 200kB. A linked release build will make this
even smaller:

```
$ du -k .build/arm64-apple-macosx/debug/CNIOExtrasZlib.build/*.o
12	.build/arm64-apple-macosx/debug/CNIOExtrasZlib.build/adler32.c.o
12	.build/arm64-apple-macosx/debug/CNIOExtrasZlib.build/crc32.c.o
60	.build/arm64-apple-macosx/debug/CNIOExtrasZlib.build/deflate.c.o
16	.build/arm64-apple-macosx/debug/CNIOExtrasZlib.build/inffast.c.o
40	.build/arm64-apple-macosx/debug/CNIOExtrasZlib.build/inflate.c.o
16	.build/arm64-apple-macosx/debug/CNIOExtrasZlib.build/inftrees.c.o
40	.build/arm64-apple-macosx/debug/CNIOExtrasZlib.build/trees.c.o
8	.build/arm64-apple-macosx/debug/CNIOExtrasZlib.build/zutil.c.o
```

Co-authored-by: Johannes Weiss <johannes@jweiss.io>
This commit is contained in:
Johannes WeissandJohannes Weiss authored and GitHub committed 2026-02-26 21:39:13 +00:00
1 parent 56301df3a8
commit fef304cebf
33 files changed
+20655 -87

No files matched your search

+5
View File
@@ -1,6 +1,7 @@
.gitignore
**/.gitignore
.licenseignore
.unacceptablelanguageignore
.gitattributes
.git-blame-ignore-revs
.mailfilter
@@ -38,3 +39,7 @@ dev/lldb-smoker
dev/make-single-file-spm
dev/malloc-aggregation.d
dev/update-alloc-limits-to-last-completed-ci-build
Sources/CNIOExtrasZlib/vendored-zlib.version
Sources/CNIOExtrasZlib/*.c
Sources/CNIOExtrasZlib/nioextras-*.h
Sources/CNIOExtrasZlib/include/nioextras-*.h
+3
View File
@@ -0,0 +1,3 @@
Sources/CNIOExtrasZlib/*.c
Sources/CNIOExtrasZlib/nioextras-*.h
Sources/CNIOExtrasZlib/include/nioextras-*.h
+9
View File
@@ -43,3 +43,12 @@ This product contains a derivation of "HTTP1ProxyConnectHandler.swift" and accom
* https://github.com/swift-server/async-http-client
---
This product contains a vendored copy of zlib with symbols prefixed as "cnioextras_z_".
* LICENSE (zlib License):
* https://www.zlib.net/zlib_license.html
* HOMEPAGE:
* https://www.zlib.net/
---
+2 -2
View File
@@ -110,8 +110,8 @@ var targets: [PackageDescription.Target] = [
.target(
name: "CNIOExtrasZlib",
dependencies: [],
linkerSettings: [
.linkedLibrary("z")
cSettings: [
.define("HAVE_HIDDEN")
]
),
.testTarget(
+164
View File
@@ -0,0 +1,164 @@
/* adler32.c -- compute the Adler-32 checksum of a data stream
* Copyright (C) 1995-2011, 2016 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* @(#) $Id$ */
#include "nioextras-zutil.h"
#define BASE 65521U /* largest prime smaller than 65536 */
#define NMAX 5552
/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
#define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
#define DO16(buf) DO8(buf,0); DO8(buf,8);
/* use NO_DIVIDE if your processor does not do division in hardware --
try it both ways to see which is faster */
#ifdef NO_DIVIDE
/* note that this assumes BASE is 65521, where 65536 % 65521 == 15
(thank you to John Reiser for pointing this out) */
# define CHOP(a) \
do { \
unsigned long tmp = a >> 16; \
a &= 0xffffUL; \
a += (tmp << 4) - tmp; \
} while (0)
# define MOD28(a) \
do { \
CHOP(a); \
if (a >= BASE) a -= BASE; \
} while (0)
# define MOD(a) \
do { \
CHOP(a); \
MOD28(a); \
} while (0)
# define MOD63(a) \
do { /* this assumes a is not negative */ \
cnioextras_z_off64_t tmp = a >> 32; \
a &= 0xffffffffL; \
a += (tmp << 8) - (tmp << 5) + tmp; \
tmp = a >> 16; \
a &= 0xffffL; \
a += (tmp << 4) - tmp; \
tmp = a >> 16; \
a &= 0xffffL; \
a += (tmp << 4) - tmp; \
if (a >= BASE) a -= BASE; \
} while (0)
#else
# define MOD(a) a %= BASE
# define MOD28(a) a %= BASE
# define MOD63(a) a %= BASE
#endif
/* ========================================================================= */
uLong ZEXPORT adler32_z(uLong adler, const Bytef *buf, cnioextras_z_size_t len) {
unsigned long sum2;
unsigned n;
/* split Adler-32 into component sums */
sum2 = (adler >> 16) & 0xffff;
adler &= 0xffff;
/* in case user likes doing a byte at a time, keep it fast */
if (len == 1) {
adler += buf[0];
if (adler >= BASE)
adler -= BASE;
sum2 += adler;
if (sum2 >= BASE)
sum2 -= BASE;
return adler | (sum2 << 16);
}
/* initial Adler-32 value (deferred check for len == 1 speed) */
if (buf == CNIOEXTRAS_Z_NULL)
return 1L;
/* in case short lengths are provided, keep it somewhat fast */
if (len < 16) {
while (len--) {
adler += *buf++;
sum2 += adler;
}
if (adler >= BASE)
adler -= BASE;
MOD28(sum2); /* only added so many BASE's */
return adler | (sum2 << 16);
}
/* do length NMAX blocks -- requires just one modulo operation */
while (len >= NMAX) {
len -= NMAX;
n = NMAX / 16; /* NMAX is divisible by 16 */
do {
DO16(buf); /* 16 sums unrolled */
buf += 16;
} while (--n);
MOD(adler);
MOD(sum2);
}
/* do remaining bytes (less than NMAX, still just one modulo) */
if (len) { /* avoid modulos if none remaining */
while (len >= 16) {
len -= 16;
DO16(buf);
buf += 16;
}
while (len--) {
adler += *buf++;
sum2 += adler;
}
MOD(adler);
MOD(sum2);
}
/* return recombined sums */
return adler | (sum2 << 16);
}
/* ========================================================================= */
uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len) {
return adler32_z(adler, buf, len);
}
/* ========================================================================= */
local uLong adler32_combine_(uLong adler1, uLong adler2, cnioextras_z_off64_t len2) {
unsigned long sum1;
unsigned long sum2;
unsigned rem;
/* for negative len, return invalid adler32 as a clue for debugging */
if (len2 < 0)
return 0xffffffffUL;
/* the derivation of this formula is left as an exercise for the reader */
MOD63(len2); /* assumes len2 >= 0 */
rem = (unsigned)len2;
sum1 = adler1 & 0xffff;
sum2 = rem * sum1;
MOD(sum2);
sum1 += (adler2 & 0xffff) + BASE - 1;
sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
if (sum1 >= BASE) sum1 -= BASE;
if (sum1 >= BASE) sum1 -= BASE;
if (sum2 >= ((unsigned long)BASE << 1)) sum2 -= ((unsigned long)BASE << 1);
if (sum2 >= BASE) sum2 -= BASE;
return sum1 | (sum2 << 16);
}
/* ========================================================================= */
uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, cnioextras_z_off_t len2) {
return adler32_combine_(adler1, adler2, len2);
}
uLong ZEXPORT adler32_combine64(uLong adler1, uLong adler2, cnioextras_z_off64_t len2) {
return adler32_combine_(adler1, adler2, len2);
}
+983
View File
@@ -0,0 +1,983 @@
/* crc32.c -- compute the CRC-32 of a data stream
* Copyright (C) 1995-2026 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*
* This interleaved implementation of a CRC makes use of pipelined multiple
* arithmetic-logic units, commonly found in modern CPU cores. It is due to
* Kadatch and Jenkins (2010). See doc/crc-doc.1.0.pdf in this distribution.
*/
/* @(#) $Id$ */
/*
Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
protection on the static variables used to control the first-use generation
of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
first call get_crc_table() to initialize the tables before allowing more than
one thread to use crc32().
MAKECRCH can be #defined to write out crc32.h. A main() routine is also
produced, so that this one source file can be compiled to an executable.
*/
#ifdef MAKECRCH
# include <stdio.h>
# ifndef DYNAMIC_CRC_TABLE
# define DYNAMIC_CRC_TABLE
# endif
#endif
#ifdef DYNAMIC_CRC_TABLE
# define CNIOEXTRAS_Z_ONCE
#endif
#include "nioextras-zutil.h" /* for CNIOEXTRAS_Z_U4, CNIOEXTRAS_Z_U8, cnioextras_z_crc_t, and FAR definitions */
#ifdef HAVE_S390X_VX
# include "contrib/crc32vx/crc32_vx_hooks.h"
#endif
/*
A CRC of a message is computed on N braids of words in the message, where
each word consists of W bytes (4 or 8). If N is 3, for example, then three
running sparse CRCs are calculated respectively on each braid, at these
indices in the array of words: 0, 3, 6, ..., 1, 4, 7, ..., and 2, 5, 8, ...
This is done starting at a word boundary, and continues until as many blocks
of N * W bytes as are available have been processed. The results are combined
into a single CRC at the end. For this code, N must be in the range 1..6 and
W must be 4 or 8. The upper limit on N can be increased if desired by adding
more #if blocks, extending the patterns apparent in the code. In addition,
crc32.h would need to be regenerated, if the maximum N value is increased.
N and W are chosen empirically by benchmarking the execution time on a given
processor. The choices for N and W below were based on testing on Intel Kaby
Lake i7, AMD Ryzen 7, ARM Cortex-A57, Sparc64-VII, PowerPC POWER9, and MIPS64
Octeon II processors. The Intel, AMD, and ARM processors were all fastest
with N=5, W=8. The Sparc, PowerPC, and MIPS64 were all fastest at N=5, W=4.
They were all tested with either gcc or clang, all using the -O3 optimization
level. Your mileage may vary.
*/
/* Define N */
#ifdef CNIOEXTRAS_Z_TESTN
# define N CNIOEXTRAS_Z_TESTN
#else
# define N 5
#endif
#if N < 1 || N > 6
# error N must be in 1..6
#endif
/*
cnioextras_z_crc_t must be at least 32 bits. cnioextras_z_word_t must be at least as long as
cnioextras_z_crc_t. It is assumed here that cnioextras_z_word_t is either 32 bits or 64 bits, and
that bytes are eight bits.
*/
/*
Define W and the associated cnioextras_z_word_t type. If W is not defined, then a
braided calculation is not used, and the associated tables and code are not
compiled.
*/
#ifdef CNIOEXTRAS_Z_TESTW
# if CNIOEXTRAS_Z_TESTW-1 != -1
# define W CNIOEXTRAS_Z_TESTW
# endif
#else
# ifdef MAKECRCH
# define W 8 /* required for MAKECRCH */
# else
# if defined(__x86_64__) || defined(__aarch64__)
# define W 8
# else
# define W 4
# endif
# endif
#endif
#ifdef W
# if W == 8 && defined(CNIOEXTRAS_Z_U8)
typedef CNIOEXTRAS_Z_U8 cnioextras_z_word_t;
# elif defined(CNIOEXTRAS_Z_U4)
# undef W
# define W 4
typedef CNIOEXTRAS_Z_U4 cnioextras_z_word_t;
# else
# undef W
# endif
#endif
/* If available, use the ARM processor CRC32 instruction. */
#if defined(__aarch64__) && defined(__ARM_FEATURE_CRC32) && \
defined(W) && W == 8
# define ARMCRC32
#endif
#if defined(W) && (!defined(ARMCRC32) || defined(DYNAMIC_CRC_TABLE))
/*
Swap the bytes in a cnioextras_z_word_t to convert between little and big endian. Any
self-respecting compiler will optimize this to a single machine byte-swap
instruction, if one is available. This assumes that word_t is either 32 bits
or 64 bits.
*/
local cnioextras_z_word_t byte_swap(cnioextras_z_word_t word) {
# if W == 8
return
(word & 0xff00000000000000) >> 56 |
(word & 0xff000000000000) >> 40 |
(word & 0xff0000000000) >> 24 |
(word & 0xff00000000) >> 8 |
(word & 0xff000000) << 8 |
(word & 0xff0000) << 24 |
(word & 0xff00) << 40 |
(word & 0xff) << 56;
# else /* W == 4 */
return
(word & 0xff000000) >> 24 |
(word & 0xff0000) >> 8 |
(word & 0xff00) << 8 |
(word & 0xff) << 24;
# endif
}
#endif
#ifdef DYNAMIC_CRC_TABLE
/* =========================================================================
* Table of powers of x for combining CRC-32s, filled in by make_crc_table()
* below.
*/
local cnioextras_z_crc_t FAR x2n_table[32];
#else
/* =========================================================================
* Tables for byte-wise and braided CRC-32 calculations, and a table of powers
* of x for combining CRC-32s, all made by make_crc_table().
*/
# include "nioextras-crc32.h"
#endif
/* CRC polynomial. */
#define POLY 0xedb88320 /* p(x) reflected, with x^32 implied */
/*
Return a(x) multiplied by b(x) modulo p(x), where p(x) is the CRC polynomial,
reflected. For speed, this requires that a not be zero.
*/
local uLong multmodp(uLong a, uLong b) {
uLong m, p;
m = (uLong)1 << 31;
p = 0;
for (;;) {
if (a & m) {
p ^= b;
if ((a & (m - 1)) == 0)
break;
}
m >>= 1;
b = b & 1 ? (b >> 1) ^ POLY : b >> 1;
}
return p;
}
/*
Return x^(n * 2^k) modulo p(x). Requires that x2n_table[] has been
initialized. n must not be negative.
*/
local uLong x2nmodp(cnioextras_z_off64_t n, unsigned k) {
uLong p;
p = (uLong)1 << 31; /* x^0 == 1 */
while (n) {
if (n & 1)
p = multmodp(x2n_table[k & 31], p);
n >>= 1;
k++;
}
return p;
}
#ifdef DYNAMIC_CRC_TABLE
/* =========================================================================
* Build the tables for byte-wise and braided CRC-32 calculations, and a table
* of powers of x for combining CRC-32s.
*/
local cnioextras_z_crc_t FAR crc_table[256];
#ifdef W
local cnioextras_z_word_t FAR crc_big_table[256];
local cnioextras_z_crc_t FAR crc_braid_table[W][256];
local cnioextras_z_word_t FAR crc_braid_big_table[W][256];
local void braid(cnioextras_z_crc_t [][256], cnioextras_z_word_t [][256], int, int);
#endif
#ifdef MAKECRCH
local void write_table(FILE *, const cnioextras_z_crc_t FAR *, int);
local void write_table32hi(FILE *, const cnioextras_z_word_t FAR *, int);
local void write_table64(FILE *, const cnioextras_z_word_t FAR *, int);
#endif /* MAKECRCH */
/* State for once(). */
local cnioextras_z_once_t made = CNIOEXTRAS_Z_ONCE_INIT;
/*
Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
Polynomials over GF(2) are represented in binary, one bit per coefficient,
with the lowest powers in the most significant bit. Then adding polynomials
is just exclusive-or, and multiplying a polynomial by x is a right shift by
one. If we call the above polynomial p, and represent a byte as the
polynomial q, also with the lowest power in the most significant bit (so the
byte 0xb1 is the polynomial x^7+x^3+x^2+1), then the CRC is (q*x^32) mod p,
where a mod b means the remainder after dividing a by b.
This calculation is done using the shift-register method of multiplying and
taking the remainder. The register is initialized to zero, and for each
incoming bit, x^32 is added mod p to the register if the bit is a one (where
x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by x
(which is shifting right by one and adding x^32 mod p if the bit shifted out
is a one). We start with the highest power (least significant bit) of q and
repeat for all eight bits of q.
The table is simply the CRC of all possible eight bit values. This is all the
information needed to generate CRCs on data a byte at a time for all
combinations of CRC register values and incoming bytes.
*/
local void make_crc_table(void) {
unsigned i, j, n;
cnioextras_z_crc_t p;
/* initialize the CRC of bytes tables */
for (i = 0; i < 256; i++) {
p = i;
for (j = 0; j < 8; j++)
p = p & 1 ? (p >> 1) ^ POLY : p >> 1;
crc_table[i] = p;
#ifdef W
crc_big_table[i] = byte_swap(p);
#endif
}
/* initialize the x^2^n mod p(x) table */
p = (cnioextras_z_crc_t)1 << 30; /* x^1 */
x2n_table[0] = p;
for (n = 1; n < 32; n++)
x2n_table[n] = p = (cnioextras_z_crc_t)multmodp(p, p);
#ifdef W
/* initialize the braiding tables -- needs x2n_table[] */
braid(crc_braid_table, crc_braid_big_table, N, W);
#endif
#ifdef MAKECRCH
{
/*
The crc32.h header file contains tables for both 32-bit and 64-bit
cnioextras_z_word_t's, and so requires a 64-bit type be available. In that case,
cnioextras_z_word_t must be defined to be 64-bits. This code then also generates
and writes out the tables for the case that cnioextras_z_word_t is 32 bits.
*/
#if !defined(W) || W != 8
# error Need a 64-bit integer type in order to generate crc32.h.
#endif
FILE *out;
int k, n;
cnioextras_z_crc_t ltl[8][256];
cnioextras_z_word_t big[8][256];
out = fopen("nioextras-crc32.h", "w");
if (out == NULL) return;
/* write out little-endian CRC table to crc32.h */
fprintf(out,
"/* crc32.h -- tables for rapid CRC calculation\n"
" * Generated automatically by crc32.c\n */\n"
"\n"
"local const cnioextras_z_crc_t FAR crc_table[] = {\n"
" ");
write_table(out, crc_table, 256);
fprintf(out,
"};\n");
/* write out big-endian CRC table for 64-bit cnioextras_z_word_t to crc32.h */
fprintf(out,
"\n"
"#ifdef W\n"
"\n"
"#if W == 8\n"
"\n"
"local const cnioextras_z_word_t FAR crc_big_table[] = {\n"
" ");
write_table64(out, crc_big_table, 256);
fprintf(out,
"};\n");
/* write out big-endian CRC table for 32-bit cnioextras_z_word_t to crc32.h */
fprintf(out,
"\n"
"#else /* W == 4 */\n"
"\n"
"local const cnioextras_z_word_t FAR crc_big_table[] = {\n"
" ");
write_table32hi(out, crc_big_table, 256);
fprintf(out,
"};\n"
"\n"
"#endif\n");
/* write out braid tables for each value of N */
for (n = 1; n <= 6; n++) {
fprintf(out,
"\n"
"#if N == %d\n", n);
/* compute braid tables for this N and 64-bit word_t */
braid(ltl, big, n, 8);
/* write out braid tables for 64-bit cnioextras_z_word_t to crc32.h */
fprintf(out,
"\n"
"#if W == 8\n"
"\n"
"local const cnioextras_z_crc_t FAR crc_braid_table[][256] = {\n");
for (k = 0; k < 8; k++) {
fprintf(out, " {");
write_table(out, ltl[k], 256);
fprintf(out, "}%s", k < 7 ? ",\n" : "");
}
fprintf(out,
"};\n"
"\n"
"local const cnioextras_z_word_t FAR crc_braid_big_table[][256] = {\n");
for (k = 0; k < 8; k++) {
fprintf(out, " {");
write_table64(out, big[k], 256);
fprintf(out, "}%s", k < 7 ? ",\n" : "");
}
fprintf(out,
"};\n");
/* compute braid tables for this N and 32-bit word_t */
braid(ltl, big, n, 4);
/* write out braid tables for 32-bit cnioextras_z_word_t to crc32.h */
fprintf(out,
"\n"
"#else /* W == 4 */\n"
"\n"
"local const cnioextras_z_crc_t FAR crc_braid_table[][256] = {\n");
for (k = 0; k < 4; k++) {
fprintf(out, " {");
write_table(out, ltl[k], 256);
fprintf(out, "}%s", k < 3 ? ",\n" : "");
}
fprintf(out,
"};\n"
"\n"
"local const cnioextras_z_word_t FAR crc_braid_big_table[][256] = {\n");
for (k = 0; k < 4; k++) {
fprintf(out, " {");
write_table32hi(out, big[k], 256);
fprintf(out, "}%s", k < 3 ? ",\n" : "");
}
fprintf(out,
"};\n"
"\n"
"#endif\n"
"\n"
"#endif\n");
}
fprintf(out,
"\n"
"#endif\n");
/* write out zeros operator table to crc32.h */
fprintf(out,
"\n"
"local const cnioextras_z_crc_t FAR x2n_table[] = {\n"
" ");
write_table(out, x2n_table, 32);
fprintf(out,
"};\n");
fclose(out);
}
#endif /* MAKECRCH */
}
#ifdef MAKECRCH
/*
Write the 32-bit values in table[0..k-1] to out, five per line in
hexadecimal separated by commas.
*/
local void write_table(FILE *out, const cnioextras_z_crc_t FAR *table, int k) {
int n;
for (n = 0; n < k; n++)
fprintf(out, "%s0x%08lx%s", n == 0 || n % 5 ? "" : " ",
(unsigned long)(table[n]),
n == k - 1 ? "" : (n % 5 == 4 ? ",\n" : ", "));
}
/*
Write the high 32-bits of each value in table[0..k-1] to out, five per line
in hexadecimal separated by commas.
*/
local void write_table32hi(FILE *out, const cnioextras_z_word_t FAR *table, int k) {
int n;
for (n = 0; n < k; n++)
fprintf(out, "%s0x%08lx%s", n == 0 || n % 5 ? "" : " ",
(unsigned long)(table[n] >> 32),
n == k - 1 ? "" : (n % 5 == 4 ? ",\n" : ", "));
}
/*
Write the 64-bit values in table[0..k-1] to out, three per line in
hexadecimal separated by commas. This assumes that if there is a 64-bit
type, then there is also a long long integer type, and it is at least 64
bits. If not, then the type cast and format string can be adjusted
accordingly.
*/
local void write_table64(FILE *out, const cnioextras_z_word_t FAR *table, int k) {
int n;
for (n = 0; n < k; n++)
fprintf(out, "%s0x%016llx%s", n == 0 || n % 3 ? "" : " ",
(unsigned long long)(table[n]),
n == k - 1 ? "" : (n % 3 == 2 ? ",\n" : ", "));
}
/* Actually do the deed. */
int main(void) {
make_crc_table();
return 0;
}
#endif /* MAKECRCH */
#ifdef W
/*
Generate the little and big-endian braid tables for the given n and cnioextras_z_word_t
size w. Each array must have room for w blocks of 256 elements.
*/
local void braid(cnioextras_z_crc_t ltl[][256], cnioextras_z_word_t big[][256], int n, int w) {
int k;
cnioextras_z_crc_t i, p, q;
for (k = 0; k < w; k++) {
p = (cnioextras_z_crc_t)x2nmodp((n * w + 3 - k) << 3, 0);
ltl[k][0] = 0;
big[w - 1 - k][0] = 0;
for (i = 1; i < 256; i++) {
ltl[k][i] = q = (cnioextras_z_crc_t)multmodp(i << 24, p);
big[w - 1 - k][i] = byte_swap(q);
}
}
}
#endif
#endif /* DYNAMIC_CRC_TABLE */
/* =========================================================================
* This function can be used by asm versions of crc32(), and to force the
* generation of the CRC tables in a threaded application.
*/
const cnioextras_z_crc_t FAR * ZEXPORT get_crc_table(void) {
#ifdef DYNAMIC_CRC_TABLE
cnioextras_z_once(&made, make_crc_table);
#endif /* DYNAMIC_CRC_TABLE */
return (const cnioextras_z_crc_t FAR *)crc_table;
}
/* =========================================================================
* Use ARM machine instructions if available. This will compute the CRC about
* ten times faster than the braided calculation. This code does not check for
* the presence of the CRC instruction at run time. __ARM_FEATURE_CRC32 will
* only be defined if the compilation specifies an ARM processor architecture
* that has the instructions. For example, compiling with -march=armv8.1-a or
* -march=armv8-a+crc, or -march=native if the compile machine has the crc32
* instructions.
*/
#ifdef ARMCRC32
/*
Constants empirically determined to maximize speed. These values are from
measurements on a Cortex-A57. Your mileage may vary.
*/
#define CNIOEXTRAS_Z_BATCH 3990 /* number of words in a batch */
#define CNIOEXTRAS_Z_BATCH_ZEROS 0xa10d3d0c /* computed from CNIOEXTRAS_Z_BATCH = 3990 */
#define CNIOEXTRAS_Z_BATCH_MIN 800 /* fewest words in a final batch */
uLong ZEXPORT crc32_z(uLong crc, const unsigned char FAR *buf, cnioextras_z_size_t len) {
uLong val;
cnioextras_z_word_t crc1, crc2;
const cnioextras_z_word_t *word;
cnioextras_z_word_t val0, val1, val2;
cnioextras_z_size_t last, last2, i;
cnioextras_z_size_t num;
/* Return initial CRC, if requested. */
if (buf == CNIOEXTRAS_Z_NULL) return 0;
#ifdef DYNAMIC_CRC_TABLE
cnioextras_z_once(&made, make_crc_table);
#endif /* DYNAMIC_CRC_TABLE */
/* Pre-condition the CRC */
crc = (~crc) & 0xffffffff;
/* Compute the CRC up to a word boundary. */
while (len && ((cnioextras_z_size_t)buf & 7) != 0) {
len--;
val = *buf++;
__asm__ volatile("crc32b %w0, %w0, %w1" : "+r"(crc) : "r"(val));
}
/* Prepare to compute the CRC on full 64-bit words word[0..num-1]. */
word = (cnioextras_z_word_t const *)buf;
num = len >> 3;
len &= 7;
/* Do three interleaved CRCs to realize the throughput of one crc32x
instruction per cycle. Each CRC is calculated on CNIOEXTRAS_Z_BATCH words. The
three CRCs are combined into a single CRC after each set of batches. */
while (num >= 3 * CNIOEXTRAS_Z_BATCH) {
crc1 = 0;
crc2 = 0;
for (i = 0; i < CNIOEXTRAS_Z_BATCH; i++) {
val0 = word[i];
val1 = word[i + CNIOEXTRAS_Z_BATCH];
val2 = word[i + 2 * CNIOEXTRAS_Z_BATCH];
__asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc) : "r"(val0));
__asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc1) : "r"(val1));
__asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc2) : "r"(val2));
}
word += 3 * CNIOEXTRAS_Z_BATCH;
num -= 3 * CNIOEXTRAS_Z_BATCH;
crc = multmodp(CNIOEXTRAS_Z_BATCH_ZEROS, crc) ^ crc1;
crc = multmodp(CNIOEXTRAS_Z_BATCH_ZEROS, crc) ^ crc2;
}
/* Do one last smaller batch with the remaining words, if there are enough
to pay for the combination of CRCs. */
last = num / 3;
if (last >= CNIOEXTRAS_Z_BATCH_MIN) {
last2 = last << 1;
crc1 = 0;
crc2 = 0;
for (i = 0; i < last; i++) {
val0 = word[i];
val1 = word[i + last];
val2 = word[i + last2];
__asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc) : "r"(val0));
__asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc1) : "r"(val1));
__asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc2) : "r"(val2));
}
word += 3 * last;
num -= 3 * last;
val = x2nmodp((int)last, 6);
crc = multmodp(val, crc) ^ crc1;
crc = multmodp(val, crc) ^ crc2;
}
/* Compute the CRC on any remaining words. */
for (i = 0; i < num; i++) {
val0 = word[i];
__asm__ volatile("crc32x %w0, %w0, %x1" : "+r"(crc) : "r"(val0));
}
word += num;
/* Complete the CRC on any remaining bytes. */
buf = (const unsigned char FAR *)word;
while (len) {
len--;
val = *buf++;
__asm__ volatile("crc32b %w0, %w0, %w1" : "+r"(crc) : "r"(val));
}
/* Return the CRC, post-conditioned. */
return crc ^ 0xffffffff;
}
#else
#ifdef W
/*
Return the CRC of the W bytes in the word_t data, taking the
least-significant byte of the word as the first byte of data, without any pre
or post conditioning. This is used to combine the CRCs of each braid.
*/
local cnioextras_z_crc_t crc_word(cnioextras_z_word_t data) {
int k;
for (k = 0; k < W; k++)
data = (data >> 8) ^ crc_table[data & 0xff];
return (cnioextras_z_crc_t)data;
}
local cnioextras_z_word_t crc_word_big(cnioextras_z_word_t data) {
int k;
for (k = 0; k < W; k++)
data = (data << 8) ^
crc_big_table[(data >> ((W - 1) << 3)) & 0xff];
return data;
}
#endif
/* ========================================================================= */
uLong ZEXPORT crc32_z(uLong crc, const unsigned char FAR *buf, cnioextras_z_size_t len) {
/* Return initial CRC, if requested. */
if (buf == CNIOEXTRAS_Z_NULL) return 0;
#ifdef DYNAMIC_CRC_TABLE
cnioextras_z_once(&made, make_crc_table);
#endif /* DYNAMIC_CRC_TABLE */
/* Pre-condition the CRC */
crc = (~crc) & 0xffffffff;
#ifdef W
/* If provided enough bytes, do a braided CRC calculation. */
if (len >= N * W + W - 1) {
cnioextras_z_size_t blks;
cnioextras_z_word_t const *words;
unsigned endian;
int k;
/* Compute the CRC up to a cnioextras_z_word_t boundary. */
while (len && ((cnioextras_z_size_t)buf & (W - 1)) != 0) {
len--;
crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff];
}
/* Compute the CRC on as many N cnioextras_z_word_t blocks as are available. */
blks = len / (N * W);
len -= blks * N * W;
words = (cnioextras_z_word_t const *)buf;
/* Do endian check at execution time instead of compile time, since ARM
processors can change the endianness at execution time. If the
compiler knows what the endianness will be, it can optimize out the
check and the unused branch. */
endian = 1;
if (*(unsigned char *)&endian) {
/* Little endian. */
cnioextras_z_crc_t crc0;
cnioextras_z_word_t word0;
#if N > 1
cnioextras_z_crc_t crc1;
cnioextras_z_word_t word1;
#if N > 2
cnioextras_z_crc_t crc2;
cnioextras_z_word_t word2;
#if N > 3
cnioextras_z_crc_t crc3;
cnioextras_z_word_t word3;
#if N > 4
cnioextras_z_crc_t crc4;
cnioextras_z_word_t word4;
#if N > 5
cnioextras_z_crc_t crc5;
cnioextras_z_word_t word5;
#endif
#endif
#endif
#endif
#endif
/* Initialize the CRC for each braid. */
crc0 = crc;
#if N > 1
crc1 = 0;
#if N > 2
crc2 = 0;
#if N > 3
crc3 = 0;
#if N > 4
crc4 = 0;
#if N > 5
crc5 = 0;
#endif
#endif
#endif
#endif
#endif
/*
Process the first blks-1 blocks, computing the CRCs on each braid
independently.
*/
while (--blks) {
/* Load the word for each braid into registers. */
word0 = crc0 ^ words[0];
#if N > 1
word1 = crc1 ^ words[1];
#if N > 2
word2 = crc2 ^ words[2];
#if N > 3
word3 = crc3 ^ words[3];
#if N > 4
word4 = crc4 ^ words[4];
#if N > 5
word5 = crc5 ^ words[5];
#endif
#endif
#endif
#endif
#endif
words += N;
/* Compute and update the CRC for each word. The loop should
get unrolled. */
crc0 = crc_braid_table[0][word0 & 0xff];
#if N > 1
crc1 = crc_braid_table[0][word1 & 0xff];
#if N > 2
crc2 = crc_braid_table[0][word2 & 0xff];
#if N > 3
crc3 = crc_braid_table[0][word3 & 0xff];
#if N > 4
crc4 = crc_braid_table[0][word4 & 0xff];
#if N > 5
crc5 = crc_braid_table[0][word5 & 0xff];
#endif
#endif
#endif
#endif
#endif
for (k = 1; k < W; k++) {
crc0 ^= crc_braid_table[k][(word0 >> (k << 3)) & 0xff];
#if N > 1
crc1 ^= crc_braid_table[k][(word1 >> (k << 3)) & 0xff];
#if N > 2
crc2 ^= crc_braid_table[k][(word2 >> (k << 3)) & 0xff];
#if N > 3
crc3 ^= crc_braid_table[k][(word3 >> (k << 3)) & 0xff];
#if N > 4
crc4 ^= crc_braid_table[k][(word4 >> (k << 3)) & 0xff];
#if N > 5
crc5 ^= crc_braid_table[k][(word5 >> (k << 3)) & 0xff];
#endif
#endif
#endif
#endif
#endif
}
}
/*
Process the last block, combining the CRCs of the N braids at the
same time.
*/
crc = crc_word(crc0 ^ words[0]);
#if N > 1
crc = crc_word(crc1 ^ words[1] ^ crc);
#if N > 2
crc = crc_word(crc2 ^ words[2] ^ crc);
#if N > 3
crc = crc_word(crc3 ^ words[3] ^ crc);
#if N > 4
crc = crc_word(crc4 ^ words[4] ^ crc);
#if N > 5
crc = crc_word(crc5 ^ words[5] ^ crc);
#endif
#endif
#endif
#endif
#endif
words += N;
}
else {
/* Big endian. */
cnioextras_z_word_t crc0, word0, comb;
#if N > 1
cnioextras_z_word_t crc1, word1;
#if N > 2
cnioextras_z_word_t crc2, word2;
#if N > 3
cnioextras_z_word_t crc3, word3;
#if N > 4
cnioextras_z_word_t crc4, word4;
#if N > 5
cnioextras_z_word_t crc5, word5;
#endif
#endif
#endif
#endif
#endif
/* Initialize the CRC for each braid. */
crc0 = byte_swap(crc);
#if N > 1
crc1 = 0;
#if N > 2
crc2 = 0;
#if N > 3
crc3 = 0;
#if N > 4
crc4 = 0;
#if N > 5
crc5 = 0;
#endif
#endif
#endif
#endif
#endif
/*
Process the first blks-1 blocks, computing the CRCs on each braid
independently.
*/
while (--blks) {
/* Load the word for each braid into registers. */
word0 = crc0 ^ words[0];
#if N > 1
word1 = crc1 ^ words[1];
#if N > 2
word2 = crc2 ^ words[2];
#if N > 3
word3 = crc3 ^ words[3];
#if N > 4
word4 = crc4 ^ words[4];
#if N > 5
word5 = crc5 ^ words[5];
#endif
#endif
#endif
#endif
#endif
words += N;
/* Compute and update the CRC for each word. The loop should
get unrolled. */
crc0 = crc_braid_big_table[0][word0 & 0xff];
#if N > 1
crc1 = crc_braid_big_table[0][word1 & 0xff];
#if N > 2
crc2 = crc_braid_big_table[0][word2 & 0xff];
#if N > 3
crc3 = crc_braid_big_table[0][word3 & 0xff];
#if N > 4
crc4 = crc_braid_big_table[0][word4 & 0xff];
#if N > 5
crc5 = crc_braid_big_table[0][word5 & 0xff];
#endif
#endif
#endif
#endif
#endif
for (k = 1; k < W; k++) {
crc0 ^= crc_braid_big_table[k][(word0 >> (k << 3)) & 0xff];
#if N > 1
crc1 ^= crc_braid_big_table[k][(word1 >> (k << 3)) & 0xff];
#if N > 2
crc2 ^= crc_braid_big_table[k][(word2 >> (k << 3)) & 0xff];
#if N > 3
crc3 ^= crc_braid_big_table[k][(word3 >> (k << 3)) & 0xff];
#if N > 4
crc4 ^= crc_braid_big_table[k][(word4 >> (k << 3)) & 0xff];
#if N > 5
crc5 ^= crc_braid_big_table[k][(word5 >> (k << 3)) & 0xff];
#endif
#endif
#endif
#endif
#endif
}
}
/*
Process the last block, combining the CRCs of the N braids at the
same time.
*/
comb = crc_word_big(crc0 ^ words[0]);
#if N > 1
comb = crc_word_big(crc1 ^ words[1] ^ comb);
#if N > 2
comb = crc_word_big(crc2 ^ words[2] ^ comb);
#if N > 3
comb = crc_word_big(crc3 ^ words[3] ^ comb);
#if N > 4
comb = crc_word_big(crc4 ^ words[4] ^ comb);
#if N > 5
comb = crc_word_big(crc5 ^ words[5] ^ comb);
#endif
#endif
#endif
#endif
#endif
words += N;
crc = byte_swap(comb);
}
/*
Update the pointer to the remaining bytes to process.
*/
buf = (unsigned char const *)words;
}
#endif /* W */
/* Complete the computation of the CRC on any remaining bytes. */
while (len >= 8) {
len -= 8;
crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff];
crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff];
crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff];
crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff];
crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff];
crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff];
crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff];
crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff];
}
while (len) {
len--;
crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff];
}
/* Return the CRC, post-conditioned. */
return crc ^ 0xffffffff;
}
#endif
/* ========================================================================= */
uLong ZEXPORT crc32(uLong crc, const unsigned char FAR *buf, uInt len) {
#ifdef HAVE_S390X_VX
return crc32_z_hook(crc, buf, len);
#endif
return crc32_z(crc, buf, len);
}
/* ========================================================================= */
uLong ZEXPORT crc32_combine_gen64(cnioextras_z_off64_t len2) {
if (len2 < 0)
return 0;
#ifdef DYNAMIC_CRC_TABLE
cnioextras_z_once(&made, make_crc_table);
#endif /* DYNAMIC_CRC_TABLE */
return x2nmodp(len2, 3);
}
/* ========================================================================= */
uLong ZEXPORT crc32_combine_gen(cnioextras_z_off_t len2) {
return crc32_combine_gen64((cnioextras_z_off64_t)len2);
}
/* ========================================================================= */
uLong ZEXPORT crc32_combine_op(uLong crc1, uLong crc2, uLong op) {
if (op == 0)
return 0;
return multmodp(op, crc1 & 0xffffffff) ^ (crc2 & 0xffffffff);
}
/* ========================================================================= */
uLong ZEXPORT crc32_combine64(uLong crc1, uLong crc2, cnioextras_z_off64_t len2) {
return crc32_combine_op(crc1, crc2, crc32_combine_gen64(len2));
}
/* ========================================================================= */
uLong ZEXPORT crc32_combine(uLong crc1, uLong crc2, cnioextras_z_off_t len2) {
return crc32_combine64(crc1, crc2, (cnioextras_z_off64_t)len2);
}
File diff suppressed because it is too large. Load diff
-13
View File
@@ -1,13 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
@@ -2,7 +2,7 @@
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Copyright (c) 2017-2026 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
@@ -14,23 +14,23 @@
#ifndef C_NIO_ZLIB_H
#define C_NIO_ZLIB_H
#include <zlib.h>
#include "nioextras-zlib.h"
static inline int CNIOExtrasZlib_deflateInit2(z_streamp strm,
static inline int CNIOExtrasZlib_deflateInit2(cnioextras_z_streamp strm,
int level,
int method,
int windowBits,
int memLevel,
int strategy) {
return deflateInit2(strm, level, method, windowBits, memLevel, strategy);
return cnioextras_z_deflateInit2(strm, level, method, windowBits, memLevel, strategy);
}
static inline int CNIOExtrasZlib_inflateInit2(z_streamp strm, int windowBits) {
return inflateInit2(strm, windowBits);
static inline int CNIOExtrasZlib_inflateInit2(cnioextras_z_streamp strm, int windowBits) {
return cnioextras_z_inflateInit2(strm, windowBits);
}
static inline Bytef *CNIOExtrasZlib_voidPtr_to_BytefPtr(void *in) {
return (Bytef *)in;
static inline cnioextras_z_Bytef *CNIOExtrasZlib_voidPtr_to_BytefPtr(void *in) {
return (cnioextras_z_Bytef *)in;
}
#endif
@@ -0,0 +1,551 @@
/* zconf.h -- configuration of the zlib compression library
* Copyright (C) 1995-2026 Jean-loup Gailly, Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* @(#) $Id$ */
#ifndef NIOEXTRAS_ZCONF_H
#define NIOEXTRAS_ZCONF_H
/*
* If you *really* need a unique prefix for all types and library functions,
* compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
* Even better than compiling with -DZ_PREFIX would be to use configure to set
* this permanently in zconf.h using "./configure --zprefix".
*/
#if 1 /* CNIOEXTRAS_Z_PREFIX - cnioextras_z_ */
# define CNIOEXTRAS_Z_PREFIX_SET
/* all linked symbols and init macros */
# define _dist_code cnioextras_z__dist_code
# define _length_code cnioextras_z__length_code
# define _tr_align cnioextras_z__tr_align
# define _tr_flush_bits cnioextras_z__tr_flush_bits
# define _tr_flush_block cnioextras_z__tr_flush_block
# define _tr_init cnioextras_z__tr_init
# define _tr_stored_block cnioextras_z__tr_stored_block
# define _tr_tally cnioextras_z__tr_tally
# define adler32 cnioextras_z_adler32
# define adler32_combine cnioextras_z_adler32_combine
# define adler32_combine64 cnioextras_z_adler32_combine64
# define adler32_z cnioextras_z_adler32_z
# ifndef CNIOEXTRAS_Z_SOLO
# define compress cnioextras_z_compress
# define compress2 cnioextras_z_compress2
# define compress_z cnioextras_z_compress_z
# define compress2_z cnioextras_z_compress2_z
# define compressBound cnioextras_z_compressBound
# define compressBound_z cnioextras_z_compressBound_z
# endif
# define crc32 cnioextras_z_crc32
# define crc32_combine cnioextras_z_crc32_combine
# define crc32_combine64 cnioextras_z_crc32_combine64
# define crc32_combine_gen cnioextras_z_crc32_combine_gen
# define crc32_combine_gen64 cnioextras_z_crc32_combine_gen64
# define crc32_combine_op cnioextras_z_crc32_combine_op
# define crc32_z cnioextras_z_crc32_z
# define deflate cnioextras_z_deflate
# define deflateBound cnioextras_z_deflateBound
# define deflateBound_z cnioextras_z_deflateBound_z
# define deflateCopy cnioextras_z_deflateCopy
# define deflateEnd cnioextras_z_deflateEnd
# define deflateGetDictionary cnioextras_z_deflateGetDictionary
# define deflateInit cnioextras_z_deflateInit
# define deflateInit2 cnioextras_z_deflateInit2
# define deflateInit2_ cnioextras_z_deflateInit2_
# define deflateInit_ cnioextras_z_deflateInit_
# define deflateParams cnioextras_z_deflateParams
# define deflatePending cnioextras_z_deflatePending
# define deflatePrime cnioextras_z_deflatePrime
# define deflateReset cnioextras_z_deflateReset
# define deflateResetKeep cnioextras_z_deflateResetKeep
# define deflateSetDictionary cnioextras_z_deflateSetDictionary
# define deflateSetHeader cnioextras_z_deflateSetHeader
# define deflateTune cnioextras_z_deflateTune
# define deflateUsed cnioextras_z_deflateUsed
# define deflate_copyright cnioextras_z_deflate_copyright
# define get_crc_table cnioextras_z_get_crc_table
# ifndef CNIOEXTRAS_Z_SOLO
# define gz_error cnioextras_z_gz_error
# define gz_intmax cnioextras_z_gz_intmax
# define gz_strwinerror cnioextras_z_gz_strwinerror
# define gzbuffer cnioextras_z_gzbuffer
# define gzclearerr cnioextras_z_gzclearerr
# define gzclose cnioextras_z_gzclose
# define gzclose_r cnioextras_z_gzclose_r
# define gzclose_w cnioextras_z_gzclose_w
# define gzdirect cnioextras_z_gzdirect
# define gzdopen cnioextras_z_gzdopen
# define gzeof cnioextras_z_gzeof
# define gzerror cnioextras_z_gzerror
# define gzflush cnioextras_z_gzflush
# define gzfread cnioextras_z_gzfread
# define gzfwrite cnioextras_z_gzfwrite
# define gzgetc cnioextras_z_gzgetc
# define gzgetc_ cnioextras_z_gzgetc_
# define gzgets cnioextras_z_gzgets
# define gzoffset cnioextras_z_gzoffset
# define gzoffset64 cnioextras_z_gzoffset64
# define gzopen cnioextras_z_gzopen
# define gzopen64 cnioextras_z_gzopen64
# ifdef _WIN32
# define gzopen_w cnioextras_z_gzopen_w
# endif
# define gzprintf cnioextras_z_gzprintf
# define gzputc cnioextras_z_gzputc
# define gzputs cnioextras_z_gzputs
# define gzread cnioextras_z_gzread
# define gzrewind cnioextras_z_gzrewind
# define gzseek cnioextras_z_gzseek
# define gzseek64 cnioextras_z_gzseek64
# define gzsetparams cnioextras_z_gzsetparams
# define gztell cnioextras_z_gztell
# define gztell64 cnioextras_z_gztell64
# define gzungetc cnioextras_z_gzungetc
# define gzvprintf cnioextras_z_gzvprintf
# define gzwrite cnioextras_z_gzwrite
# endif
# define inflate cnioextras_z_inflate
# define inflateBack cnioextras_z_inflateBack
# define inflateBackEnd cnioextras_z_inflateBackEnd
# define inflateBackInit cnioextras_z_inflateBackInit
# define inflateBackInit_ cnioextras_z_inflateBackInit_
# define inflateCodesUsed cnioextras_z_inflateCodesUsed
# define inflateCopy cnioextras_z_inflateCopy
# define inflateEnd cnioextras_z_inflateEnd
# define inflateGetDictionary cnioextras_z_inflateGetDictionary
# define inflateGetHeader cnioextras_z_inflateGetHeader
# define inflateInit cnioextras_z_inflateInit
# define inflateInit2 cnioextras_z_inflateInit2
# define inflateInit2_ cnioextras_z_inflateInit2_
# define inflateInit_ cnioextras_z_inflateInit_
# define inflateMark cnioextras_z_inflateMark
# define inflatePrime cnioextras_z_inflatePrime
# define inflateReset cnioextras_z_inflateReset
# define inflateReset2 cnioextras_z_inflateReset2
# define inflateResetKeep cnioextras_z_inflateResetKeep
# define inflateSetDictionary cnioextras_z_inflateSetDictionary
# define inflateSync cnioextras_z_inflateSync
# define inflateSyncPoint cnioextras_z_inflateSyncPoint
# define inflateUndermine cnioextras_z_inflateUndermine
# define inflateValidate cnioextras_z_inflateValidate
# define inflate_copyright cnioextras_z_inflate_copyright
# define inflate_fast cnioextras_z_inflate_fast
# define inflate_table cnioextras_z_inflate_table
# define inflate_fixed cnioextras_z_inflate_fixed
# ifndef CNIOEXTRAS_Z_SOLO
# define uncompress cnioextras_z_uncompress
# define uncompress2 cnioextras_z_uncompress2
# define uncompress_z cnioextras_z_uncompress_z
# define uncompress2_z cnioextras_z_uncompress2_z
# endif
# define zError cnioextras_z_zError
# ifndef CNIOEXTRAS_Z_SOLO
# define zcalloc cnioextras_z_zcalloc
# define zcfree cnioextras_z_zcfree
# endif
# define zlibCompileFlags cnioextras_z_zlibCompileFlags
# define zlibVersion cnioextras_z_zlibVersion
/* all zlib typedefs in zlib.h and zconf.h */
# define Byte cnioextras_z_Byte
# define Bytef cnioextras_z_Bytef
# define alloc_func cnioextras_z_alloc_func
# define charf cnioextras_z_charf
# define free_func cnioextras_z_free_func
# ifndef CNIOEXTRAS_Z_SOLO
# define gzFile cnioextras_z_gzFile
# endif
# define gz_header cnioextras_z_gz_header
# define gz_headerp cnioextras_z_gz_headerp
# define in_func cnioextras_z_in_func
# define intf cnioextras_z_intf
# define out_func cnioextras_z_out_func
# define uInt cnioextras_z_uInt
# define uIntf cnioextras_z_uIntf
# define uLong cnioextras_z_uLong
# define uLongf cnioextras_z_uLongf
# define voidp cnioextras_z_voidp
# define voidpc cnioextras_z_voidpc
# define voidpf cnioextras_z_voidpf
/* all zlib structs in zlib.h and zconf.h */
# define gz_header_s cnioextras_z_gz_header_s
# define internal_state cnioextras_z_internal_state
#endif
#if defined(__MSDOS__) && !defined(MSDOS)
# define MSDOS
#endif
#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
# define OS2
#endif
#if defined(_WINDOWS) && !defined(WINDOWS)
# define WINDOWS
#endif
#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
# ifndef WIN32
# define WIN32
# endif
#endif
#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
# ifndef SYS16BIT
# define SYS16BIT
# endif
# endif
#endif
/*
* Compile with -DMAXSEG_64K if the alloc function cannot allocate more
* than 64k bytes at a time (needed on systems with 16-bit int).
*/
#ifdef SYS16BIT
# define MAXSEG_64K
#endif
#ifdef MSDOS
# define UNALIGNED_OK
#endif
#ifdef __STDC_VERSION__
# ifndef STDC
# define STDC
# endif
# if __STDC_VERSION__ >= 199901L
# ifndef STDC99
# define STDC99
# endif
# endif
#endif
#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
# define STDC
#endif
#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
# define STDC
#endif
#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
# define STDC
#endif
#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
# define STDC
#endif
#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
# define STDC
#endif
#ifndef STDC
# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
# define const /* note: need a more gentle solution here */
# endif
#endif
#ifndef cnioextras_z_const
# ifdef CNIOEXTRAS_ZLIB_CONST
# define cnioextras_z_const const
# else
# define cnioextras_z_const
# endif
#endif
#ifdef CNIOEXTRAS_Z_SOLO
# ifdef _WIN64
typedef unsigned long long cnioextras_z_size_t;
# else
typedef unsigned long cnioextras_z_size_t;
# endif
#else
# define cnioextras_z_longlong long long
# if defined(NO_SIZE_T)
typedef unsigned NO_SIZE_T cnioextras_z_size_t;
# elif defined(STDC)
# include <stddef.h>
typedef size_t cnioextras_z_size_t;
# else
typedef unsigned long cnioextras_z_size_t;
# endif
# undef cnioextras_z_longlong
#endif
/* Maximum value for memLevel in deflateInit2 */
#ifndef MAX_MEM_LEVEL
# ifdef MAXSEG_64K
# define MAX_MEM_LEVEL 8
# else
# define MAX_MEM_LEVEL 9
# endif
#endif
/* Maximum value for windowBits in deflateInit2 and inflateInit2.
* WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
* created by gzip. (Files created by minigzip can still be extracted by
* gzip.)
*/
#ifndef MAX_WBITS
# define MAX_WBITS 15 /* 32K LZ77 window */
#endif
/* The memory requirements for deflate are (in bytes):
(1 << (windowBits+2)) + (1 << (memLevel+9))
that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
plus a few kilobytes for small objects. For example, if you want to reduce
the default memory requirements from 256K to 128K, compile with
make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
Of course this will generally degrade compression (there's no free lunch).
The memory requirements for inflate are (in bytes) 1 << windowBits
that is, 32K for windowBits=15 (default value) plus about 7 kilobytes
for small objects.
*/
/* Type declarations */
#ifndef OF /* function prototypes */
# ifdef STDC
# define OF(args) args
# else
# define OF(args) ()
# endif
#endif
/* The following definitions for FAR are needed only for MSDOS mixed
* model programming (small or medium model with some far allocations).
* This was tested only with MSC; for other MSDOS compilers you may have
* to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
* just define FAR to be empty.
*/
#ifdef SYS16BIT
# if defined(M_I86SM) || defined(M_I86MM)
/* MSC small or medium model */
# define SMALL_MEDIUM
# ifdef _MSC_VER
# define FAR _far
# else
# define FAR far
# endif
# endif
# if (defined(__SMALL__) || defined(__MEDIUM__))
/* Turbo C small or medium model */
# define SMALL_MEDIUM
# ifdef __BORLANDC__
# define FAR _far
# else
# define FAR far
# endif
# endif
#endif
#if defined(WINDOWS) || defined(WIN32)
/* If building or using zlib as a DLL, define CNIOEXTRAS_ZLIB_DLL.
* This is not mandatory, but it offers a little performance increase.
*/
# ifdef CNIOEXTRAS_ZLIB_DLL
# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
# ifdef CNIOEXTRAS_ZLIB_INTERNAL
# define ZEXTERN extern __declspec(dllexport)
# else
# define ZEXTERN extern __declspec(dllimport)
# endif
# endif
# endif /* CNIOEXTRAS_ZLIB_DLL */
/* If building or using zlib with the WINAPI/WINAPIV calling convention,
* define CNIOEXTRAS_ZLIB_WINAPI.
* Caution: the standard ZLIB1.DLL is NOT compiled using CNIOEXTRAS_ZLIB_WINAPI.
*/
# ifdef CNIOEXTRAS_ZLIB_WINAPI
# ifdef FAR
# undef FAR
# endif
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# include <windows.h>
/* No need for _export, use ZLIB.DEF instead. */
/* For complete Windows compatibility, use WINAPI, not __stdcall. */
# define ZEXPORT WINAPI
# ifdef WIN32
# define ZEXPORTVA WINAPIV
# else
# define ZEXPORTVA FAR CDECL
# endif
# endif
#endif
#if defined (__BEOS__)
# ifdef CNIOEXTRAS_ZLIB_DLL
# ifdef CNIOEXTRAS_ZLIB_INTERNAL
# define ZEXPORT __declspec(dllexport)
# define ZEXPORTVA __declspec(dllexport)
# else
# define ZEXPORT __declspec(dllimport)
# define ZEXPORTVA __declspec(dllimport)
# endif
# endif
#endif
#ifndef ZEXTERN
# define ZEXTERN extern
#endif
#ifndef ZEXPORT
# define ZEXPORT
#endif
#ifndef ZEXPORTVA
# define ZEXPORTVA
#endif
#ifndef FAR
# define FAR
#endif
#if !defined(__MACTYPES__)
typedef unsigned char Byte; /* 8 bits */
#endif
typedef unsigned int uInt; /* 16 bits or more */
typedef unsigned long uLong; /* 32 bits or more */
#ifdef SMALL_MEDIUM
/* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
# define Bytef Byte FAR
#else
typedef Byte FAR Bytef;
#endif
typedef char FAR charf;
typedef int FAR intf;
typedef uInt FAR uIntf;
typedef uLong FAR uLongf;
#ifdef STDC
typedef void const *voidpc;
typedef void FAR *voidpf;
typedef void *voidp;
#else
typedef Byte const *voidpc;
typedef Byte FAR *voidpf;
typedef Byte *voidp;
#endif
#if !defined(CNIOEXTRAS_Z_U4) && !defined(CNIOEXTRAS_Z_SOLO) && defined(STDC)
# include <limits.h>
# if (UINT_MAX == 0xffffffffUL)
# define CNIOEXTRAS_Z_U4 unsigned
# elif (ULONG_MAX == 0xffffffffUL)
# define CNIOEXTRAS_Z_U4 unsigned long
# elif (USHRT_MAX == 0xffffffffUL)
# define CNIOEXTRAS_Z_U4 unsigned short
# endif
#endif
#ifdef CNIOEXTRAS_Z_U4
typedef CNIOEXTRAS_Z_U4 cnioextras_z_crc_t;
#else
typedef unsigned long cnioextras_z_crc_t;
#endif
#if 1 /* was set to #if 1 by ./configure */
# define CNIOEXTRAS_Z_HAVE_UNISTD_H
#endif
#if 1 /* was set to #if 1 by ./configure */
# define CNIOEXTRAS_Z_HAVE_STDARG_H
#endif
#ifdef STDC
# ifndef CNIOEXTRAS_Z_SOLO
# include <sys/types.h> /* for off_t */
# endif
#endif
#if defined(STDC) || defined(CNIOEXTRAS_Z_HAVE_STDARG_H)
# ifndef CNIOEXTRAS_Z_SOLO
# include <stdarg.h> /* for va_list */
# endif
#endif
#ifdef _WIN32
# ifndef CNIOEXTRAS_Z_SOLO
# include <stddef.h> /* for wchar_t */
# endif
#endif
/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and
* "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even
* though the former does not conform to the LFS document), but considering
* both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as
* equivalently requesting no 64-bit operations
*/
#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1
# undef _LARGEFILE64_SOURCE
#endif
#ifndef CNIOEXTRAS_Z_HAVE_UNISTD_H
# if defined(__WATCOMC__) || defined(__GO32__) || \
(defined(_LARGEFILE64_SOURCE) && !defined(_WIN32))
# define CNIOEXTRAS_Z_HAVE_UNISTD_H
# endif
#endif
#ifndef CNIOEXTRAS_Z_SOLO
# if defined(CNIOEXTRAS_Z_HAVE_UNISTD_H)
# include <unistd.h> /* for SEEK_*, off_t, and _LFS64_LARGEFILE */
# ifdef VMS
# include <unixio.h> /* for off_t */
# endif
# ifndef cnioextras_z_off_t
# define cnioextras_z_off_t off_t
# endif
# endif
#endif
#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0
# define CNIOEXTRAS_Z_LFS64
#endif
#if defined(_LARGEFILE64_SOURCE) && defined(CNIOEXTRAS_Z_LFS64)
# define CNIOEXTRAS_Z_LARGE64
#endif
#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(CNIOEXTRAS_Z_LFS64)
# define CNIOEXTRAS_Z_WANT64
#endif
#if !defined(SEEK_SET) && !defined(CNIOEXTRAS_Z_SOLO)
# define SEEK_SET 0 /* Seek from beginning of file. */
# define SEEK_CUR 1 /* Seek from current position. */
# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
#endif
#ifndef cnioextras_z_off_t
# define cnioextras_z_off_t long long
#endif
#if !defined(_WIN32) && defined(CNIOEXTRAS_Z_LARGE64)
# define cnioextras_z_off64_t off64_t
#elif defined(__MINGW32__)
# define cnioextras_z_off64_t long long
#elif defined(_WIN32) && !defined(__GNUC__)
# define cnioextras_z_off64_t __int64
#elif defined(__GO32__)
# define cnioextras_z_off64_t offset_t
#else
# define cnioextras_z_off64_t cnioextras_z_off_t
#endif
/* MVS linker does not support external names larger than 8 bytes */
#if defined(__MVS__)
#pragma map(deflateInit_,"DEIN")
#pragma map(deflateInit2_,"DEIN2")
#pragma map(deflateEnd,"DEEND")
#pragma map(deflateBound,"DEBND")
#pragma map(inflateInit_,"ININ")
#pragma map(inflateInit2_,"ININ2")
#pragma map(inflateEnd,"INEND")
#pragma map(inflateSync,"INSY")
#pragma map(inflateSetDictionary,"INSEDI")
#pragma map(compressBound,"CMBND")
#pragma map(inflate_table,"INTABL")
#pragma map(inflate_fast,"INFA")
#pragma map(inflate_copyright,"INCOPY")
#endif
#endif /* NIOEXTRAS_ZCONF_H */
File diff suppressed because it is too large. Load diff
+321
View File
@@ -0,0 +1,321 @@
/* inffast.c -- fast decoding
* Copyright (C) 1995-2026 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
#include "nioextras-zutil.h"
#include "nioextras-inftrees.h"
#include "nioextras-inflate.h"
#include "nioextras-inffast.h"
#ifdef ASMINF
# pragma message("Assembler code may have bugs -- use at your own risk")
#else
/*
Decode literal, length, and distance codes and write out the resulting
literal and match bytes until either not enough input or output is
available, an end-of-block is encountered, or a data error is encountered.
When large enough input and output buffers are supplied to inflate(), for
example, a 16K input buffer and a 64K output buffer, more than 95% of the
inflate execution time is spent in this routine.
Entry assumptions:
state->mode == LEN
strm->avail_in >= 6
strm->avail_out >= 258
start >= strm->avail_out
state->bits < 8
On return, state->mode is one of:
LEN -- ran out of enough output space or enough available input
TYPE -- reached end of block code, inflate() to interpret next block
BAD -- error in block data
Notes:
- The maximum input bits used by a length/distance pair is 15 bits for the
length code, 5 bits for the length extra, 15 bits for the distance code,
and 13 bits for the distance extra. This totals 48 bits, or six bytes.
Therefore if strm->avail_in >= 6, then there is enough input to avoid
checking for available input while decoding.
- The maximum bytes that a single length/distance pair can output is 258
bytes, which is the maximum length that can be coded. inflate_fast()
requires strm->avail_out >= 258 for each loop to avoid checking for
output space.
*/
void CNIOEXTRAS_ZLIB_INTERNAL inflate_fast(cnioextras_z_streamp strm, unsigned start) {
struct inflate_state FAR *state;
cnioextras_z_const unsigned char FAR *in; /* local strm->next_in */
cnioextras_z_const unsigned char FAR *last; /* have enough input while in < last */
unsigned char FAR *out; /* local strm->next_out */
unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
unsigned char FAR *end; /* while out < end, enough space available */
#ifdef INFLATE_STRICT
unsigned dmax; /* maximum distance from zlib header */
#endif
unsigned wsize; /* window size or zero if not using window */
unsigned whave; /* valid bytes in the window */
unsigned wnext; /* window write index */
unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
unsigned long hold; /* local strm->hold */
unsigned bits; /* local strm->bits */
code const FAR *lcode; /* local strm->lencode */
code const FAR *dcode; /* local strm->distcode */
unsigned lmask; /* mask for first level of length codes */
unsigned dmask; /* mask for first level of distance codes */
code const *here; /* retrieved table entry */
unsigned op; /* code bits, operation, extra bits, or */
/* window position, window bytes to copy */
unsigned len; /* match length, unused bytes */
unsigned dist; /* match distance */
unsigned char FAR *from; /* where to copy match from */
/* copy state to local variables */
state = (struct inflate_state FAR *)strm->state;
in = strm->next_in;
last = in + (strm->avail_in - 5);
out = strm->next_out;
beg = out - (start - strm->avail_out);
end = out + (strm->avail_out - 257);
#ifdef INFLATE_STRICT
dmax = state->dmax;
#endif
wsize = state->wsize;
whave = state->whave;
wnext = state->wnext;
window = state->window;
hold = state->hold;
bits = state->bits;
lcode = state->lencode;
dcode = state->distcode;
lmask = (1U << state->lenbits) - 1;
dmask = (1U << state->distbits) - 1;
/* decode literals and length/distances until end-of-block or not enough
input data or output space */
do {
if (bits < 15) {
hold += (unsigned long)(*in++) << bits;
bits += 8;
hold += (unsigned long)(*in++) << bits;
bits += 8;
}
here = lcode + (hold & lmask);
dolen:
op = (unsigned)(here->bits);
hold >>= op;
bits -= op;
op = (unsigned)(here->op);
if (op == 0) { /* literal */
Tracevv((stderr, here->val >= 0x20 && here->val < 0x7f ?
"inflate: literal '%c'\n" :
"inflate: literal 0x%02x\n", here->val));
*out++ = (unsigned char)(here->val);
}
else if (op & 16) { /* length base */
len = (unsigned)(here->val);
op &= 15; /* number of extra bits */
if (op) {
if (bits < op) {
hold += (unsigned long)(*in++) << bits;
bits += 8;
}
len += (unsigned)hold & ((1U << op) - 1);
hold >>= op;
bits -= op;
}
Tracevv((stderr, "inflate: length %u\n", len));
if (bits < 15) {
hold += (unsigned long)(*in++) << bits;
bits += 8;
hold += (unsigned long)(*in++) << bits;
bits += 8;
}
here = dcode + (hold & dmask);
dodist:
op = (unsigned)(here->bits);
hold >>= op;
bits -= op;
op = (unsigned)(here->op);
if (op & 16) { /* distance base */
dist = (unsigned)(here->val);
op &= 15; /* number of extra bits */
if (bits < op) {
hold += (unsigned long)(*in++) << bits;
bits += 8;
if (bits < op) {
hold += (unsigned long)(*in++) << bits;
bits += 8;
}
}
dist += (unsigned)hold & ((1U << op) - 1);
#ifdef INFLATE_STRICT
if (dist > dmax) {
strm->msg = (cnioextras_z_const char *)
"invalid distance too far back";
state->mode = BAD;
break;
}
#endif
hold >>= op;
bits -= op;
Tracevv((stderr, "inflate: distance %u\n", dist));
op = (unsigned)(out - beg); /* max distance in output */
if (dist > op) { /* see if copy from window */
op = dist - op; /* distance back in window */
if (op > whave) {
if (state->sane) {
strm->msg = (cnioextras_z_const char *)
"invalid distance too far back";
state->mode = BAD;
break;
}
#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
if (len <= op - whave) {
do {
*out++ = 0;
} while (--len);
continue;
}
len -= op - whave;
do {
*out++ = 0;
} while (--op > whave);
if (op == 0) {
from = out - dist;
do {
*out++ = *from++;
} while (--len);
continue;
}
#endif
}
from = window;
if (wnext == 0) { /* very common case */
from += wsize - op;
if (op < len) { /* some from window */
len -= op;
do {
*out++ = *from++;
} while (--op);
from = out - dist; /* rest from output */
}
}
else if (wnext < op) { /* wrap around window */
from += wsize + wnext - op;
op -= wnext;
if (op < len) { /* some from end of window */
len -= op;
do {
*out++ = *from++;
} while (--op);
from = window;
if (wnext < len) { /* some from start of window */
op = wnext;
len -= op;
do {
*out++ = *from++;
} while (--op);
from = out - dist; /* rest from output */
}
}
}
else { /* contiguous in window */
from += wnext - op;
if (op < len) { /* some from window */
len -= op;
do {
*out++ = *from++;
} while (--op);
from = out - dist; /* rest from output */
}
}
while (len > 2) {
*out++ = *from++;
*out++ = *from++;
*out++ = *from++;
len -= 3;
}
if (len) {
*out++ = *from++;
if (len > 1)
*out++ = *from++;
}
}
else {
from = out - dist; /* copy direct from output */
do { /* minimum length is three */
*out++ = *from++;
*out++ = *from++;
*out++ = *from++;
len -= 3;
} while (len > 2);
if (len) {
*out++ = *from++;
if (len > 1)
*out++ = *from++;
}
}
}
else if ((op & 64) == 0) { /* 2nd level distance code */
here = dcode + here->val + (hold & ((1U << op) - 1));
goto dodist;
}
else {
strm->msg = (cnioextras_z_const char *)"invalid distance code";
state->mode = BAD;
break;
}
}
else if ((op & 64) == 0) { /* 2nd level length code */
here = lcode + here->val + (hold & ((1U << op) - 1));
goto dolen;
}
else if (op & 32) { /* end-of-block */
Tracevv((stderr, "inflate: end of block\n"));
state->mode = TYPE;
break;
}
else {
strm->msg = (cnioextras_z_const char *)"invalid literal/length code";
state->mode = BAD;
break;
}
} while (in < last && out < end);
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
len = bits >> 3;
in -= len;
bits -= len << 3;
hold &= (1U << bits) - 1;
/* update state and return */
strm->next_in = in;
strm->next_out = out;
strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
strm->avail_out = (unsigned)(out < end ?
257 + (end - out) : 257 - (out - end));
state->hold = hold;
state->bits = bits;
return;
}
/*
inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
- Using bit fields for code structure
- Different op definition to avoid & for extra bits (do & for table bits)
- Three separate decoding do-loops for direct, window, and wnext == 0
- Special case for distance > 1 copies to do overlapped load and store copy
- Explicit branch predictions (based on measured branch probabilities)
- Deferring match copy and interspersed it with decoding subsequent codes
- Swapping literal/length else
- Swapping window/direct else
- Larger unrolled copy loops (three is about right)
- Moving len -= 3 statement into middle of loop
*/
#endif /* !ASMINF */
File diff suppressed because it is too large. Load diff
+424
View File
@@ -0,0 +1,424 @@
/* inftrees.c -- generate Huffman trees for efficient decoding
* Copyright (C) 1995-2026 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
#ifdef MAKEFIXED
# ifndef BUILDFIXED
# define BUILDFIXED
# endif
#endif
#ifdef BUILDFIXED
# define CNIOEXTRAS_Z_ONCE
#endif
#include "nioextras-zutil.h"
#include "nioextras-inftrees.h"
#include "nioextras-inflate.h"
#ifndef NULL
# define NULL 0
#endif
#define MAXBITS 15
const char inflate_copyright[] =
" inflate 1.3.2.1 Copyright 1995-2026 Mark Adler ";
/*
If you use the zlib library in a product, an acknowledgment is welcome
in the documentation of your product. If for some reason you cannot
include such an acknowledgment, I would appreciate that you keep this
copyright string in the executable of your product.
*/
/*
Build a set of tables to decode the provided canonical Huffman code.
The code lengths are lens[0..codes-1]. The result starts at *table,
whose indices are 0..2^bits-1. work is a writable array of at least
lens shorts, which is used as a work area. type is the type of code
to be generated, CODES, LENS, or DISTS. On return, zero is success,
-1 is an invalid code, and +1 means that ENOUGH isn't enough. table
on return points to the next available entry's address. bits is the
requested root table index bits, and on return it is the actual root
table index bits. It will differ if the request is greater than the
longest code or if it is less than the shortest code.
*/
int CNIOEXTRAS_ZLIB_INTERNAL inflate_table(codetype type, unsigned short FAR *lens,
unsigned codes, code FAR * FAR *table,
unsigned FAR *bits, unsigned short FAR *work) {
unsigned len; /* a code's length in bits */
unsigned sym; /* index of code symbols */
unsigned min, max; /* minimum and maximum code lengths */
unsigned root; /* number of index bits for root table */
unsigned curr; /* number of index bits for current table */
unsigned drop; /* code bits to drop for sub-table */
int left; /* number of prefix codes available */
unsigned used; /* code entries in table used */
unsigned huff; /* Huffman code */
unsigned incr; /* for incrementing code, index */
unsigned fill; /* index for replicating entries */
unsigned low; /* low bits for current root entry */
unsigned mask; /* mask for low root bits */
code here; /* table entry for duplication */
code FAR *next; /* next available space in table */
const unsigned short FAR *base = NULL; /* base value table to use */
const unsigned short FAR *extra = NULL; /* extra bits table to use */
unsigned match = 0; /* use base and extra for symbol >= match */
unsigned short count[MAXBITS+1]; /* number of codes of each length */
unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
static const unsigned short lbase[31] = { /* Length codes 257..285 base */
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
static const unsigned short lext[31] = { /* Length codes 257..285 extra */
16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 68, 193};
static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
8193, 12289, 16385, 24577, 0, 0};
static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
28, 28, 29, 29, 64, 64};
/*
Process a set of code lengths to create a canonical Huffman code. The
code lengths are lens[0..codes-1]. Each length corresponds to the
symbols 0..codes-1. The Huffman code is generated by first sorting the
symbols by length from short to long, and retaining the symbol order
for codes with equal lengths. Then the code starts with all zero bits
for the first code of the shortest length, and the codes are integer
increments for the same length, and zeros are appended as the length
increases. For the deflate format, these bits are stored backwards
from their more natural integer increment ordering, and so when the
decoding tables are built in the large loop below, the integer codes
are incremented backwards.
This routine assumes, but does not check, that all of the entries in
lens[] are in the range 0..MAXBITS. The caller must assure this.
1..MAXBITS is interpreted as that code length. zero means that that
symbol does not occur in this code.
The codes are sorted by computing a count of codes for each length,
creating from that a table of starting indices for each length in the
sorted table, and then entering the symbols in order in the sorted
table. The sorted table is work[], with that space being provided by
the caller.
The length counts are used for other purposes as well, i.e. finding
the minimum and maximum length codes, determining if there are any
codes at all, checking for a valid set of lengths, and looking ahead
at length counts to determine sub-table sizes when building the
decoding tables.
*/
/* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
for (len = 0; len <= MAXBITS; len++)
count[len] = 0;
for (sym = 0; sym < codes; sym++)
count[lens[sym]]++;
/* bound code lengths, force root to be within code lengths */
root = *bits;
for (max = MAXBITS; max >= 1; max--)
if (count[max] != 0) break;
if (root > max) root = max;
if (max == 0) { /* no symbols to code at all */
here.op = (unsigned char)64; /* invalid code marker */
here.bits = (unsigned char)1;
here.val = (unsigned short)0;
*(*table)++ = here; /* make a table to force an error */
*(*table)++ = here;
*bits = 1;
return 0; /* no symbols, but wait for decoding to report error */
}
for (min = 1; min < max; min++)
if (count[min] != 0) break;
if (root < min) root = min;
/* check for an over-subscribed or incomplete set of lengths */
left = 1;
for (len = 1; len <= MAXBITS; len++) {
left <<= 1;
left -= count[len];
if (left < 0) return -1; /* over-subscribed */
}
if (left > 0 && (type == CODES || max != 1))
return -1; /* incomplete set */
/* generate offsets into symbol table for each length for sorting */
offs[1] = 0;
for (len = 1; len < MAXBITS; len++)
offs[len + 1] = offs[len] + count[len];
/* sort symbols by length, by symbol order within each length */
for (sym = 0; sym < codes; sym++)
if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
/*
Create and fill in decoding tables. In this loop, the table being
filled is at next and has curr index bits. The code being used is huff
with length len. That code is converted to an index by dropping drop
bits off of the bottom. For codes where len is less than drop + curr,
those top drop + curr - len bits are incremented through all values to
fill the table with replicated entries.
root is the number of index bits for the root table. When len exceeds
root, sub-tables are created pointed to by the root entry with an index
of the low root bits of huff. This is saved in low to check for when a
new sub-table should be started. drop is zero when the root table is
being filled, and drop is root when sub-tables are being filled.
When a new sub-table is needed, it is necessary to look ahead in the
code lengths to determine what size sub-table is needed. The length
counts are used for this, and so count[] is decremented as codes are
entered in the tables.
used keeps track of how many table entries have been allocated from the
provided *table space. It is checked for LENS and DIST tables against
the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
the initial root table size constants. See the comments in inftrees.h
for more information.
sym increments through all symbols, and the loop terminates when
all codes of length max, i.e. all codes, have been processed. This
routine permits incomplete codes, so another loop after this one fills
in the rest of the decoding tables with invalid code markers.
*/
/* set up for code type */
switch (type) {
case CODES:
match = 20;
break;
case LENS:
base = lbase;
extra = lext;
match = 257;
break;
case DISTS:
base = dbase;
extra = dext;
}
/* initialize state for loop */
huff = 0; /* starting code */
sym = 0; /* starting code symbol */
len = min; /* starting code length */
next = *table; /* current table to fill in */
curr = root; /* current table index bits */
drop = 0; /* current bits to drop from code for index */
low = (unsigned)(-1); /* trigger new sub-table when len > root */
used = 1U << root; /* use root table entries */
mask = used - 1; /* mask for comparing low */
/* check available table space */
if ((type == LENS && used > ENOUGH_LENS) ||
(type == DISTS && used > ENOUGH_DISTS))
return 1;
/* process all codes and make table entries */
for (;;) {
/* create table entry */
here.bits = (unsigned char)(len - drop);
if (work[sym] + 1U < match) {
here.op = (unsigned char)0;
here.val = work[sym];
}
else if (work[sym] >= match) {
here.op = (unsigned char)(extra[work[sym] - match]);
here.val = base[work[sym] - match];
}
else {
here.op = (unsigned char)(32 + 64); /* end of block */
here.val = 0;
}
/* replicate for those indices with low len bits equal to huff */
incr = 1U << (len - drop);
fill = 1U << curr;
min = fill; /* save offset to next table */
do {
fill -= incr;
next[(huff >> drop) + fill] = here;
} while (fill != 0);
/* backwards increment the len-bit code huff */
incr = 1U << (len - 1);
while (huff & incr)
incr >>= 1;
if (incr != 0) {
huff &= incr - 1;
huff += incr;
}
else
huff = 0;
/* go to next symbol, update count, len */
sym++;
if (--(count[len]) == 0) {
if (len == max) break;
len = lens[work[sym]];
}
/* create new sub-table if needed */
if (len > root && (huff & mask) != low) {
/* if first time, transition to sub-tables */
if (drop == 0)
drop = root;
/* increment past last table */
next += min; /* here min is 1 << curr */
/* determine length of next table */
curr = len - drop;
left = (int)(1 << curr);
while (curr + drop < max) {
left -= count[curr + drop];
if (left <= 0) break;
curr++;
left <<= 1;
}
/* check for enough space */
used += 1U << curr;
if ((type == LENS && used > ENOUGH_LENS) ||
(type == DISTS && used > ENOUGH_DISTS))
return 1;
/* point entry in root table to sub-table */
low = huff & mask;
(*table)[low].op = (unsigned char)curr;
(*table)[low].bits = (unsigned char)root;
(*table)[low].val = (unsigned short)(next - *table);
}
}
/* fill in remaining table entry if code is incomplete (guaranteed to have
at most one remaining entry, since if the code is incomplete, the
maximum code length that was allowed to get this far is one bit) */
if (huff != 0) {
here.op = (unsigned char)64; /* invalid code marker */
here.bits = (unsigned char)(len - drop);
here.val = (unsigned short)0;
next[huff] = here;
}
/* set return parameters */
*table += used;
*bits = root;
return 0;
}
#ifdef BUILDFIXED
/*
If this is compiled with BUILDFIXED defined, and if inflate will be used in
multiple threads, and if atomics are not available, then inflate() must be
called with a fixed block (e.g. 0x03 0x00) to initialize the tables and must
return before any other threads are allowed to call inflate.
*/
static code *lenfix, *distfix;
static code fixed[544];
/* State for cnioextras_z_once(). */
local cnioextras_z_once_t built = CNIOEXTRAS_Z_ONCE_INIT;
local void buildtables(void) {
unsigned sym, bits;
static code *next;
unsigned short lens[288], work[288];
/* literal/length table */
sym = 0;
while (sym < 144) lens[sym++] = 8;
while (sym < 256) lens[sym++] = 9;
while (sym < 280) lens[sym++] = 7;
while (sym < 288) lens[sym++] = 8;
next = fixed;
lenfix = next;
bits = 9;
inflate_table(LENS, lens, 288, &(next), &(bits), work);
/* distance table */
sym = 0;
while (sym < 32) lens[sym++] = 5;
distfix = next;
bits = 5;
inflate_table(DISTS, lens, 32, &(next), &(bits), work);
}
#else /* !BUILDFIXED */
# include "nioextras-inffixed.h"
#endif /* BUILDFIXED */
/*
Return state with length and distance decoding tables and index sizes set to
fixed code decoding. Normally this returns fixed tables from inffixed.h.
If BUILDFIXED is defined, then instead this routine builds the tables the
first time it's called, and returns those tables the first time and
thereafter. This reduces the size of the code by about 2K bytes, in
exchange for a little execution time. However, BUILDFIXED should not be
used for threaded applications if atomics are not available, as it will
not be thread-safe.
*/
void inflate_fixed(struct inflate_state FAR *state) {
#ifdef BUILDFIXED
cnioextras_z_once(&built, buildtables);
#endif /* BUILDFIXED */
state->lencode = lenfix;
state->lenbits = 9;
state->distcode = distfix;
state->distbits = 5;
}
#ifdef MAKEFIXED
#include <stdio.h>
/*
Write out the inffixed.h that will be #include'd above. Defining MAKEFIXED
also defines BUILDFIXED, so the tables are built on the fly. main() writes
those tables to stdout, which would directed to inffixed.h. Compile this
along with zutil.c:
cc -DMAKEFIXED -o fix inftrees.c zutil.c
./fix > inffixed.h
*/
int main(void) {
unsigned low, size;
struct inflate_state state;
inflate_fixed(&state);
puts("/* inffixed.h -- table for decoding fixed codes");
puts(" * Generated automatically by makefixed().");
puts(" */");
puts("");
puts("/* WARNING: this file should *not* be used by applications.");
puts(" It is part of the implementation of this library and is");
puts(" subject to change. Applications should only use zlib.h.");
puts(" */");
puts("");
size = 1U << 9;
printf("static const code lenfix[%u] = {", size);
low = 0;
for (;;) {
if ((low % 7) == 0) printf("\n ");
printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op,
state.lencode[low].bits, state.lencode[low].val);
if (++low == size) break;
putchar(',');
}
puts("\n};");
size = 1U << 5;
printf("\nstatic const code distfix[%u] = {", size);
low = 0;
for (;;) {
if ((low % 6) == 0) printf("\n ");
printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
state.distcode[low].val);
if (++low == size) break;
putchar(',');
}
puts("\n};");
return 0;
}
#endif /* MAKEFIXED */
File diff suppressed because it is too large. Load diff
+383
View File
@@ -0,0 +1,383 @@
/* deflate.h -- internal compression state
* Copyright (C) 1995-2026 Jean-loup Gailly
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* WARNING: this file should *not* be used by applications. It is
part of the implementation of the compression library and is
subject to change. Applications should only use zlib.h.
*/
/* @(#) $Id$ */
#ifndef DEFLATE_H
#define DEFLATE_H
#include "nioextras-zutil.h"
/* define NO_GZIP when compiling if you want to disable gzip header and
trailer creation by deflate(). NO_GZIP would be used to avoid linking in
the crc code when it is not needed. For shared libraries, gzip encoding
should be left enabled. */
#ifndef NO_GZIP
# define GZIP
#endif
/* define LIT_MEM to slightly increase the speed of deflate (order 1% to 2%) at
the cost of a larger memory footprint */
/* #define LIT_MEM */
/* ===========================================================================
* Internal compression state.
*/
#define LENGTH_CODES 29
/* number of length codes, not counting the special END_BLOCK code */
#define LITERALS 256
/* number of literal bytes 0..255 */
#define L_CODES (LITERALS+1+LENGTH_CODES)
/* number of Literal or Length codes, including the END_BLOCK code */
#define D_CODES 30
/* number of distance codes */
#define BL_CODES 19
/* number of codes used to transfer the bit lengths */
#define HEAP_SIZE (2*L_CODES+1)
/* maximum heap size */
#define MAX_BITS 15
/* All codes must not exceed MAX_BITS bits */
#define Buf_size 16
/* size of bit buffer in bi_buf */
#define INIT_STATE 42 /* zlib header -> BUSY_STATE */
#ifdef GZIP
# define GZIP_STATE 57 /* gzip header -> BUSY_STATE | EXTRA_STATE */
#endif
#define EXTRA_STATE 69 /* gzip extra block -> NAME_STATE */
#define NAME_STATE 73 /* gzip file name -> COMMENT_STATE */
#define COMMENT_STATE 91 /* gzip comment -> HCRC_STATE */
#define HCRC_STATE 103 /* gzip header CRC -> BUSY_STATE */
#define BUSY_STATE 113 /* deflate -> FINISH_STATE */
#define FINISH_STATE 666 /* stream complete */
/* Stream status */
/* Data structure describing a single value and its code string. */
typedef struct ct_data_s {
union {
ush freq; /* frequency count */
ush code; /* bit string */
} fc;
union {
ush dad; /* father node in Huffman tree */
ush len; /* length of bit string */
} dl;
} FAR ct_data;
#define Freq fc.freq
#define Code fc.code
#define Dad dl.dad
#define Len dl.len
typedef struct static_tree_desc_s static_tree_desc;
typedef struct tree_desc_s {
ct_data *dyn_tree; /* the dynamic tree */
int max_code; /* largest code with non zero frequency */
const static_tree_desc *stat_desc; /* the corresponding static tree */
} FAR tree_desc;
typedef ush Pos;
typedef Pos FAR Posf;
typedef unsigned IPos;
/* A Pos is an index in the character window. We use short instead of int to
* save space in the various tables. IPos is used only for parameter passing.
*/
typedef struct internal_state {
cnioextras_z_streamp strm; /* pointer back to this zlib stream */
int status; /* as the name implies */
Bytef *pending_buf; /* output still pending */
ulg pending_buf_size; /* size of pending_buf */
Bytef *pending_out; /* next pending byte to output to the stream */
ulg pending; /* nb of bytes in the pending buffer */
int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
gz_headerp gzhead; /* gzip header information to write */
ulg gzindex; /* where in extra, name, or comment */
Byte method; /* can only be DEFLATED */
int last_flush; /* value of flush param for previous deflate call */
/* used by deflate.c: */
uInt w_size; /* LZ77 window size (32K by default) */
uInt w_bits; /* log2(w_size) (8..16) */
uInt w_mask; /* w_size - 1 */
Bytef *window;
/* Sliding window. Input bytes are read into the second half of the window,
* and move to the first half later to keep a dictionary of at least wSize
* bytes. With this organization, matches are limited to a distance of
* wSize-MAX_MATCH bytes, but this ensures that IO is always
* performed with a length multiple of the block size. Also, it limits
* the window size to 64K, which is quite useful on MSDOS.
* To do: use the user input buffer as sliding window.
*/
ulg window_size;
/* Actual size of window: 2*wSize, except when the user input buffer
* is directly used as sliding window.
*/
Posf *prev;
/* Link to older string with same hash index. To limit the size of this
* array to 64K, this link is maintained only for the last 32K strings.
* An index in this array is thus a window index modulo 32K.
*/
Posf *head; /* Heads of the hash chains or NIL. */
uInt ins_h; /* hash index of string to be inserted */
uInt hash_size; /* number of elements in hash table */
uInt hash_bits; /* log2(hash_size) */
uInt hash_mask; /* hash_size-1 */
uInt hash_shift;
/* Number of bits by which ins_h must be shifted at each input
* step. It must be such that after MIN_MATCH steps, the oldest
* byte no longer takes part in the hash key, that is:
* hash_shift * MIN_MATCH >= hash_bits
*/
long block_start;
/* Window position at the beginning of the current output block. Gets
* negative when the window is moved backwards.
*/
uInt match_length; /* length of best match */
IPos prev_match; /* previous match */
int match_available; /* set if previous match exists */
uInt strstart; /* start of string to insert */
uInt match_start; /* start of matching string */
uInt lookahead; /* number of valid bytes ahead in window */
uInt prev_length;
/* Length of the best match at previous step. Matches not greater than this
* are discarded. This is used in the lazy match evaluation.
*/
uInt max_chain_length;
/* To speed up deflation, hash chains are never searched beyond this
* length. A higher limit improves compression ratio but degrades the
* speed.
*/
uInt max_lazy_match;
/* Attempt to find a better match only when the current match is strictly
* smaller than this value. This mechanism is used only for compression
* levels >= 4.
*/
# define max_insert_length max_lazy_match
/* Insert new strings in the hash table only if the match length is not
* greater than this length. This saves time but degrades compression.
* max_insert_length is used only for compression levels <= 3.
*/
int level; /* compression level (1..9) */
int strategy; /* favor or force Huffman coding*/
uInt good_match;
/* Use a faster search when the previous match is longer than this */
int nice_match; /* Stop searching when current match exceeds this */
/* used by trees.c: */
/* Didn't use ct_data typedef below to suppress compiler warning */
struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
struct tree_desc_s l_desc; /* desc. for literal tree */
struct tree_desc_s d_desc; /* desc. for distance tree */
struct tree_desc_s bl_desc; /* desc. for bit length tree */
ush bl_count[MAX_BITS+1];
/* number of codes at each bit length for an optimal tree */
int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
int heap_len; /* number of elements in the heap */
int heap_max; /* element of largest frequency */
/* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
* The same heap array is used to build all trees.
*/
uch depth[2*L_CODES+1];
/* Depth of each subtree used as tie breaker for trees of equal frequency
*/
#ifdef LIT_MEM
# define LIT_BUFS 5
ushf *d_buf; /* buffer for distances */
uchf *l_buf; /* buffer for literals/lengths */
#else
# define LIT_BUFS 4
uchf *sym_buf; /* buffer for distances and literals/lengths */
#endif
uInt lit_bufsize;
/* Size of match buffer for literals/lengths. There are 4 reasons for
* limiting lit_bufsize to 64K:
* - frequencies can be kept in 16 bit counters
* - if compression is not successful for the first block, all input
* data is still in the window so we can still emit a stored block even
* when input comes from standard input. (This can also be done for
* all blocks if lit_bufsize is not greater than 32K.)
* - if compression is not successful for a file smaller than 64K, we can
* even emit a stored file instead of a stored block (saving 5 bytes).
* This is applicable only for zip (not gzip or zlib).
* - creating new Huffman trees less frequently may not provide fast
* adaptation to changes in the input data statistics. (Take for
* example a binary file with poorly compressible code followed by
* a highly compressible string table.) Smaller buffer sizes give
* fast adaptation but have of course the overhead of transmitting
* trees more frequently.
* - I can't count above 4
*/
uInt sym_next; /* running index in symbol buffer */
uInt sym_end; /* symbol table full when sym_next reaches this */
ulg opt_len; /* bit length of current block with optimal trees */
ulg static_len; /* bit length of current block with static trees */
uInt matches; /* number of string matches in current block */
uInt insert; /* bytes at end of window left to insert */
#ifdef CNIOEXTRAS_ZLIB_DEBUG
ulg compressed_len; /* total bit length of compressed file mod 2^32 */
ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
#endif
ush bi_buf;
/* Output buffer. bits are inserted starting at the bottom (least
* significant bits).
*/
int bi_valid;
/* Number of valid bits in bi_buf. All bits above the last valid bit
* are always zero.
*/
int bi_used;
/* Last number of used bits when going to a byte boundary.
*/
ulg high_water;
/* High water mark offset in window for initialized bytes -- bytes above
* this are set to zero in order to avoid memory check warnings when
* longest match routines access bytes past the input. This is then
* updated to the new high water mark.
*/
int slid;
/* True if the hash table has been slid since it was cleared. */
} FAR deflate_state;
/* Output a byte on the stream.
* IN assertion: there is enough room in pending_buf.
*/
#define put_byte(s, c) {s->pending_buf[s->pending++] = (Bytef)(c);}
#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
/* Minimum amount of lookahead, except at the end of the input file.
* See deflate.c for comments about the MIN_MATCH+1.
*/
#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
/* In order to simplify the code, particularly on 16 bit machines, match
* distances are limited to MAX_DIST instead of WSIZE.
*/
#define WIN_INIT MAX_MATCH
/* Number of bytes after end of data in window to initialize in order to avoid
memory checker errors from longest match routines */
/* in trees.c */
void CNIOEXTRAS_ZLIB_INTERNAL _tr_init(deflate_state *s);
int CNIOEXTRAS_ZLIB_INTERNAL _tr_tally(deflate_state *s, unsigned dist, unsigned lc);
void CNIOEXTRAS_ZLIB_INTERNAL _tr_flush_block(deflate_state *s, charf *buf,
ulg stored_len, int last);
void CNIOEXTRAS_ZLIB_INTERNAL _tr_flush_bits(deflate_state *s);
void CNIOEXTRAS_ZLIB_INTERNAL _tr_align(deflate_state *s);
void CNIOEXTRAS_ZLIB_INTERNAL _tr_stored_block(deflate_state *s, charf *buf,
ulg stored_len, int last);
#define d_code(dist) \
((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
/* Mapping from a distance to a distance code. dist is the distance - 1 and
* must not have side effects. _dist_code[256] and _dist_code[257] are never
* used.
*/
#ifndef CNIOEXTRAS_ZLIB_DEBUG
/* Inline versions of _tr_tally for speed: */
#if defined(GEN_TREES_H) || !defined(STDC)
extern uch CNIOEXTRAS_ZLIB_INTERNAL _length_code[];
extern uch CNIOEXTRAS_ZLIB_INTERNAL _dist_code[];
#else
extern const uch CNIOEXTRAS_ZLIB_INTERNAL _length_code[];
extern const uch CNIOEXTRAS_ZLIB_INTERNAL _dist_code[];
#endif
#ifdef LIT_MEM
# define _tr_tally_lit(s, c, flush) \
{ uch cc = (c); \
s->d_buf[s->sym_next] = 0; \
s->l_buf[s->sym_next++] = cc; \
s->dyn_ltree[cc].Freq++; \
flush = (s->sym_next == s->sym_end); \
}
# define _tr_tally_dist(s, distance, length, flush) \
{ uch len = (uch)(length); \
ush dist = (ush)(distance); \
s->d_buf[s->sym_next] = dist; \
s->l_buf[s->sym_next++] = len; \
dist--; \
s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
s->dyn_dtree[d_code(dist)].Freq++; \
flush = (s->sym_next == s->sym_end); \
}
#else
# define _tr_tally_lit(s, c, flush) \
{ uch cc = (c); \
s->sym_buf[s->sym_next++] = 0; \
s->sym_buf[s->sym_next++] = 0; \
s->sym_buf[s->sym_next++] = cc; \
s->dyn_ltree[cc].Freq++; \
flush = (s->sym_next == s->sym_end); \
}
# define _tr_tally_dist(s, distance, length, flush) \
{ uch len = (uch)(length); \
ush dist = (ush)(distance); \
s->sym_buf[s->sym_next++] = (uch)dist; \
s->sym_buf[s->sym_next++] = (uch)(dist >> 8); \
s->sym_buf[s->sym_next++] = len; \
dist--; \
s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
s->dyn_dtree[d_code(dist)].Freq++; \
flush = (s->sym_next == s->sym_end); \
}
#endif
#else
# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
# define _tr_tally_dist(s, distance, length, flush) \
flush = _tr_tally(s, distance, length)
#endif
#endif /* DEFLATE_H */
+216
View File
@@ -0,0 +1,216 @@
/* gzguts.h -- zlib internal header definitions for gz* operations
* Copyright (C) 2004-2026 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
#ifdef _LARGEFILE64_SOURCE
# ifndef _LARGEFILE_SOURCE
# define _LARGEFILE_SOURCE 1
# endif
# undef _FILE_OFFSET_BITS
# undef _TIME_BITS
#endif
#ifdef HAVE_HIDDEN
# define CNIOEXTRAS_ZLIB_INTERNAL __attribute__((visibility ("hidden")))
#else
# define CNIOEXTRAS_ZLIB_INTERNAL
#endif
#if defined(_WIN32)
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
# ifndef _CRT_SECURE_NO_WARNINGS
# define _CRT_SECURE_NO_WARNINGS
# endif
# ifndef _CRT_NONSTDC_NO_DEPRECATE
# define _CRT_NONSTDC_NO_DEPRECATE
# endif
#endif
#include <stdio.h>
#include "nioextras-zlib.h"
#ifdef STDC
# include <string.h>
# include <stdlib.h>
# include <limits.h>
#endif
#ifndef _POSIX_C_SOURCE
# define _POSIX_C_SOURCE 200112L
#endif
#include <fcntl.h>
#ifdef _WIN32
# include <stddef.h>
#endif
#if defined(__TURBOC__) || defined(_MSC_VER) || defined(_WIN32)
# include <io.h>
# include <sys/stat.h>
#endif
#if defined(_WIN32) && !defined(WIDECHAR)
# define WIDECHAR
#endif
#ifdef NO_DEFLATE /* for compatibility with old definition */
# define NO_GZCOMPRESS
#endif
#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
# ifndef HAVE_VSNPRINTF
# define HAVE_VSNPRINTF
# endif
#endif
#if defined(__CYGWIN__)
# ifndef HAVE_VSNPRINTF
# define HAVE_VSNPRINTF
# endif
#endif
#if defined(MSDOS) && defined(__BORLANDC__) && (BORLANDC > 0x410)
# ifndef HAVE_VSNPRINTF
# define HAVE_VSNPRINTF
# endif
#endif
#ifndef HAVE_VSNPRINTF
# if !defined(NO_vsnprintf) && \
(defined(MSDOS) || defined(__TURBOC__) || defined(__SASC) || \
defined(VMS) || defined(__OS400) || defined(__MVS__))
/* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
but for now we just assume it doesn't. */
# define NO_vsnprintf
# endif
# ifdef WIN32
/* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
# if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 )
# ifndef vsnprintf
# define vsnprintf _vsnprintf
# endif
# endif
# elif !defined(__STDC_VERSION__) || __STDC_VERSION__-0 < 199901L
/* Otherwise if C89/90, assume no C99 snprintf() or vsnprintf() */
# ifndef NO_snprintf
# define NO_snprintf
# endif
# ifndef NO_vsnprintf
# define NO_vsnprintf
# endif
# endif
#endif
/* unlike snprintf (which is required in C99), _snprintf does not guarantee
null termination of the result -- however this is only used in gzlib.c where
the result is assured to fit in the space provided */
#if defined(_MSC_VER) && _MSC_VER < 1900
# define snprintf _snprintf
#endif
#ifndef local
# define local static
#endif
/* since "static" is used to mean two completely different things in C, we
define "local" for the non-static meaning of "static", for readability
(compile with -Dlocal if your debugger can't find static symbols) */
/* gz* functions always use library allocation functions */
#ifndef STDC
extern voidp malloc(uInt size);
extern void free(voidpf ptr);
#endif
/* get errno and strerror definition */
#if defined UNDER_CE
# include <windows.h>
# define zstrerror() gz_strwinerror((DWORD)GetLastError())
#else
# ifndef NO_STRERROR
# include <errno.h>
# define zstrerror() strerror(errno)
# else
# define zstrerror() "stdio error (consult errno)"
# endif
#endif
/* provide prototypes for these when building zlib without LFS */
#if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0
ZEXTERN gzFile ZEXPORT gzopen64(const char *, const char *);
ZEXTERN cnioextras_z_off64_t ZEXPORT gzseek64(gzFile, cnioextras_z_off64_t, int);
ZEXTERN cnioextras_z_off64_t ZEXPORT gztell64(gzFile);
ZEXTERN cnioextras_z_off64_t ZEXPORT gzoffset64(gzFile);
#endif
/* default memLevel */
#if MAX_MEM_LEVEL >= 8
# define DEF_MEM_LEVEL 8
#else
# define DEF_MEM_LEVEL MAX_MEM_LEVEL
#endif
/* default i/o buffer size -- double this for output when reading (this and
twice this must be able to fit in an unsigned type) */
#define GZBUFSIZE 8192
/* gzip modes, also provide a little integrity check on the passed structure */
#define GZ_NONE 0
#define GZ_READ 7247
#define GZ_WRITE 31153
#define GZ_APPEND 1 /* mode set to GZ_WRITE after the file is opened */
/* values for gz_state how */
#define LOOK 0 /* look for a gzip header */
#define COPY 1 /* copy input directly */
#define GZIP 2 /* decompress a gzip stream */
/* internal gzip file state data structure */
typedef struct {
/* exposed contents for gzgetc() macro */
struct gzFile_s x; /* "x" for exposed */
/* x.have: number of bytes available at x.next */
/* x.next: next output data to deliver or write */
/* x.pos: current position in uncompressed data */
/* used for both reading and writing */
int mode; /* see gzip modes above */
int fd; /* file descriptor */
char *path; /* path or fd for error messages */
unsigned size; /* buffer size, zero if not allocated yet */
unsigned want; /* requested buffer size, default is GZBUFSIZE */
unsigned char *in; /* input buffer (double-sized when writing) */
unsigned char *out; /* output buffer (double-sized when reading) */
int direct; /* 0 if processing gzip, 1 if transparent */
/* just for reading */
int junk; /* -1 = start, 1 = junk candidate, 0 = in gzip */
int how; /* 0: get header, 1: copy, 2: decompress */
int again; /* true if EAGAIN or EWOULDBLOCK on last i/o */
cnioextras_z_off64_t start; /* where the gzip data started, for rewinding */
int eof; /* true if end of input file reached */
int past; /* true if read requested past end */
/* just for writing */
int level; /* compression level */
int strategy; /* compression strategy */
int reset; /* true if a reset is pending after a CNIOEXTRAS_Z_FINISH */
/* seek request */
cnioextras_z_off64_t skip; /* amount to skip (already rewound if backwards) */
/* error information */
int err; /* error code */
char *msg; /* error message */
/* zlib inflate or deflate stream */
cnioextras_z_stream strm; /* stream structure in-place (not a pointer) */
} gz_state;
typedef gz_state FAR *gz_statep;
/* shared functions */
void CNIOEXTRAS_ZLIB_INTERNAL gz_error(gz_statep, int, const char *);
#if defined UNDER_CE
char CNIOEXTRAS_ZLIB_INTERNAL *gz_strwinerror(DWORD error);
#endif
/* GT_OFF(x), where x is an unsigned value, is true if x > maximum cnioextras_z_off64_t
value -- needed when comparing unsigned to cnioextras_z_off64_t, which is signed
(possible cnioextras_z_off64_t types off_t, off64_t, and long are all signed) */
unsigned CNIOEXTRAS_ZLIB_INTERNAL gz_intmax(void);
#define GT_OFF(x) (sizeof(int) == sizeof(cnioextras_z_off64_t) && (x) > gz_intmax())
@@ -0,0 +1,11 @@
/* inffast.h -- header to use inffast.c
* Copyright (C) 1995-2003, 2010 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* WARNING: this file should *not* be used by applications. It is
part of the implementation of the compression library and is
subject to change. Applications should only use zlib.h.
*/
void CNIOEXTRAS_ZLIB_INTERNAL inflate_fast(cnioextras_z_streamp strm, unsigned start);
@@ -0,0 +1,94 @@
/* inffixed.h -- table for decoding fixed codes
* Generated automatically by makefixed().
*/
/* WARNING: this file should *not* be used by applications.
It is part of the implementation of this library and is
subject to change. Applications should only use zlib.h.
*/
static const code lenfix[512] = {
{96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
{0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
{0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
{0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
{0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
{21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
{0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
{0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
{18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
{0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
{0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
{0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
{20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
{0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
{0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
{0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
{16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
{0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
{0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
{0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
{0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
{0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
{0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
{0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
{17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
{0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
{0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
{0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
{19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
{0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
{0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
{0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
{16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
{0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
{0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
{0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
{0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
{20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
{0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
{0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
{17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
{0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
{0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
{0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
{20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
{0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
{0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
{0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
{16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
{0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
{0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
{0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
{0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
{0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
{0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
{0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
{16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
{0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
{0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
{0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
{19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
{0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
{0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
{0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
{16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
{0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
{0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
{0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
{0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
{64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
{0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
{0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
{18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
{0,9,255}
};
static const code distfix[32] = {
{16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
{21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
{18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
{19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
{16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
{22,5,193},{64,5,0}
};
+126
View File
@@ -0,0 +1,126 @@
/* inflate.h -- internal inflate state definition
* Copyright (C) 1995-2019 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* WARNING: this file should *not* be used by applications. It is
part of the implementation of the compression library and is
subject to change. Applications should only use zlib.h.
*/
/* define NO_GZIP when compiling if you want to disable gzip header and
trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
the crc code when it is not needed. For shared libraries, gzip decoding
should be left enabled. */
#ifndef NO_GZIP
# define GUNZIP
#endif
/* Possible inflate modes between inflate() calls */
typedef enum {
HEAD = 16180, /* i: waiting for magic header */
FLAGS, /* i: waiting for method and flags (gzip) */
TIME, /* i: waiting for modification time (gzip) */
OS, /* i: waiting for extra flags and operating system (gzip) */
EXLEN, /* i: waiting for extra length (gzip) */
EXTRA, /* i: waiting for extra bytes (gzip) */
NAME, /* i: waiting for end of file name (gzip) */
COMMENT, /* i: waiting for end of comment (gzip) */
HCRC, /* i: waiting for header crc (gzip) */
DICTID, /* i: waiting for dictionary check value */
DICT, /* waiting for inflateSetDictionary() call */
TYPE, /* i: waiting for type bits, including last-flag bit */
TYPEDO, /* i: same, but skip check to exit inflate on new block */
STORED, /* i: waiting for stored size (length and complement) */
COPY_, /* i/o: same as COPY below, but only first time in */
COPY, /* i/o: waiting for input or output to copy stored block */
TABLE, /* i: waiting for dynamic block table lengths */
LENLENS, /* i: waiting for code length code lengths */
CODELENS, /* i: waiting for length/lit and distance code lengths */
LEN_, /* i: same as LEN below, but only first time in */
LEN, /* i: waiting for length/lit/eob code */
LENEXT, /* i: waiting for length extra bits */
DIST, /* i: waiting for distance code */
DISTEXT, /* i: waiting for distance extra bits */
MATCH, /* o: waiting for output space to copy string */
LIT, /* o: waiting for output space to write literal */
CHECK, /* i: waiting for 32-bit check value */
LENGTH, /* i: waiting for 32-bit length (gzip) */
DONE, /* finished check, done -- remain here until reset */
BAD, /* got a data error -- remain here until reset */
MEM, /* got an inflate() memory error -- remain here until reset */
SYNC /* looking for synchronization bytes to restart inflate() */
} inflate_mode;
/*
State transitions between above modes -
(most modes can go to BAD or MEM on error -- not shown for clarity)
Process header:
HEAD -> (gzip) or (zlib) or (raw)
(gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT ->
HCRC -> TYPE
(zlib) -> DICTID or TYPE
DICTID -> DICT -> TYPE
(raw) -> TYPEDO
Read deflate blocks:
TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK
STORED -> COPY_ -> COPY -> TYPE
TABLE -> LENLENS -> CODELENS -> LEN_
LEN_ -> LEN
Read deflate codes in fixed or dynamic block:
LEN -> LENEXT or LIT or TYPE
LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
LIT -> LEN
Process trailer:
CHECK -> LENGTH -> DONE
*/
/* State maintained between inflate() calls -- approximately 7K bytes, not
including the allocated sliding window, which is up to 32K bytes. */
struct inflate_state {
cnioextras_z_streamp strm; /* pointer back to this zlib stream */
inflate_mode mode; /* current inflate mode */
int last; /* true if processing last block */
int wrap; /* bit 0 true for zlib, bit 1 true for gzip,
bit 2 true to validate check value */
int havedict; /* true if dictionary provided */
int flags; /* gzip header method and flags, 0 if zlib, or
-1 if raw or no header yet */
unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
unsigned long check; /* protected copy of check value */
unsigned long total; /* protected copy of output count */
gz_headerp head; /* where to save gzip header information */
/* sliding window */
unsigned wbits; /* log base 2 of requested window size */
unsigned wsize; /* window size or zero if not using window */
unsigned whave; /* valid bytes in the window */
unsigned wnext; /* window write index */
unsigned char FAR *window; /* allocated sliding window, if needed */
/* bit accumulator */
unsigned long hold; /* input bit accumulator */
unsigned bits; /* number of bits in hold */
/* for string and stored block copying */
unsigned length; /* literal or length of data to copy */
unsigned offset; /* distance back to copy string from */
/* for table and code decoding */
unsigned extra; /* extra bits needed */
/* fixed and dynamic code tables */
code const FAR *lencode; /* starting table for length/literal codes */
code const FAR *distcode; /* starting table for distance codes */
unsigned lenbits; /* index bits for lencode */
unsigned distbits; /* index bits for distcode */
/* dynamic table building */
unsigned ncode; /* number of code length code lengths */
unsigned nlen; /* number of length code lengths */
unsigned ndist; /* number of distance code lengths */
unsigned have; /* number of code lengths in lens[] */
code FAR *next; /* next available space in codes[] */
unsigned short lens[320]; /* temporary storage for code lengths */
unsigned short work[288]; /* work area for code table building */
code codes[ENOUGH]; /* space for code tables */
int sane; /* if false, allow invalid distance too far */
int back; /* bits back of last unprocessed length/lit */
unsigned was; /* initial length of match */
};
@@ -0,0 +1,64 @@
/* inftrees.h -- header to use inftrees.c
* Copyright (C) 1995-2026 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* WARNING: this file should *not* be used by applications. It is
part of the implementation of the compression library and is
subject to change. Applications should only use zlib.h.
*/
/* Structure for decoding tables. Each entry provides either the
information needed to do the operation requested by the code that
indexed that table entry, or it provides a pointer to another
table that indexes more bits of the code. op indicates whether
the entry is a pointer to another table, a literal, a length or
distance, an end-of-block, or an invalid code. For a table
pointer, the low four bits of op is the number of index bits of
that table. For a length or distance, the low four bits of op
is the number of extra bits to get after the code. bits is
the number of bits in this code or part of the code to drop off
of the bit buffer. val is the actual byte to output in the case
of a literal, the base length or distance, or the offset from
the current table to the next table. Each entry is four bytes. */
typedef struct {
unsigned char op; /* operation, extra bits, table bits */
unsigned char bits; /* bits in this part of the code */
unsigned short val; /* offset in table or code value */
} code;
/* op values as set by inflate_table():
00000000 - literal
0000tttt - table link, tttt != 0 is the number of table index bits
0001eeee - length or distance, eeee is the number of extra bits
01100000 - end of block
01000000 - invalid code
*/
/* Maximum size of the dynamic table. The maximum number of code structures is
1444, which is the sum of 852 for literal/length codes and 592 for distance
codes. These values were found by exhaustive searches using the program
examples/enough.c found in the zlib distribution. The arguments to that
program are the number of symbols, the initial root table size, and the
maximum bit length of a code. "enough 286 9 15" for literal/length codes
returns 852, and "enough 30 6 15" for distance codes returns 592. The
initial root table size (9 or 6) is found in the fifth argument of the
inflate_table() calls in inflate.c and infback.c. If the root table size is
changed, then these maximum sizes would be need to be recalculated and
updated. */
#define ENOUGH_LENS 852
#define ENOUGH_DISTS 592
#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS)
/* Type of code to build for inflate_table() */
typedef enum {
CODES,
LENS,
DISTS
} codetype;
int CNIOEXTRAS_ZLIB_INTERNAL inflate_table(codetype type, unsigned short FAR *lens,
unsigned codes, code FAR * FAR *table,
unsigned FAR *bits, unsigned short FAR *work);
struct inflate_state;
void CNIOEXTRAS_ZLIB_INTERNAL inflate_fixed(struct inflate_state FAR *state);
+128
View File
@@ -0,0 +1,128 @@
/* header created automatically with -DGEN_TREES_H */
local const ct_data static_ltree[L_CODES+2] = {
{{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
{{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
{{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
{{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
{{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
{{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
{{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
{{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
{{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
{{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
{{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
{{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
{{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
{{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
{{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
{{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
{{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
{{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
{{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
{{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
{{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
{{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
{{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
{{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
{{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
{{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
{{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
{{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
{{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
{{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
{{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
{{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
{{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
{{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
{{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
{{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
{{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
{{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
{{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
{{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
{{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
{{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
{{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
{{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
{{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
{{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
{{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
{{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
{{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
{{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
{{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
{{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
{{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
{{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
{{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
{{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
{{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
{{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
};
local const ct_data static_dtree[D_CODES] = {
{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
};
const uch CNIOEXTRAS_ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {
0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
};
const uch CNIOEXTRAS_ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {
0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
};
local const int base_length[LENGTH_CODES] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
64, 80, 96, 112, 128, 160, 192, 224, 0
};
local const int base_dist[D_CODES] = {
0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
};
+331
View File
@@ -0,0 +1,331 @@
/* zutil.h -- internal interface and configuration of the compression library
* Copyright (C) 1995-2026 Jean-loup Gailly, Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* WARNING: this file should *not* be used by applications. It is
part of the implementation of the compression library and is
subject to change. Applications should only use zlib.h.
*/
/* @(#) $Id$ */
#ifndef ZUTIL_H
#define ZUTIL_H
#ifdef HAVE_HIDDEN
# define CNIOEXTRAS_ZLIB_INTERNAL __attribute__((visibility ("hidden")))
#else
# define CNIOEXTRAS_ZLIB_INTERNAL
#endif
#include "nioextras-zlib.h"
#if defined(STDC) && !defined(CNIOEXTRAS_Z_SOLO)
# if !(defined(_WIN32_WCE) && defined(_MSC_VER))
# include <stddef.h>
# endif
# include <string.h>
# include <stdlib.h>
#endif
#ifndef local
# define local static
#endif
/* since "static" is used to mean two completely different things in C, we
define "local" for the non-static meaning of "static", for readability
(compile with -Dlocal if your debugger can't find static symbols) */
extern const char deflate_copyright[];
extern const char inflate_copyright[];
extern const char inflate9_copyright[];
typedef unsigned char uch;
typedef uch FAR uchf;
typedef unsigned short ush;
typedef ush FAR ushf;
typedef unsigned long ulg;
#if !defined(CNIOEXTRAS_Z_U8) && !defined(CNIOEXTRAS_Z_SOLO) && defined(STDC)
# include <limits.h>
# if (ULONG_MAX == 0xffffffffffffffff)
# define CNIOEXTRAS_Z_U8 unsigned long
# elif (ULLONG_MAX == 0xffffffffffffffff)
# define CNIOEXTRAS_Z_U8 unsigned long long
# elif (ULONG_LONG_MAX == 0xffffffffffffffff)
# define CNIOEXTRAS_Z_U8 unsigned long long
# elif (UINT_MAX == 0xffffffffffffffff)
# define CNIOEXTRAS_Z_U8 unsigned
# endif
#endif
extern cnioextras_z_const char * const cnioextras_z_errmsg[10]; /* indexed by 2-zlib_error */
/* (size given to avoid silly warnings with Visual C++) */
#define ERR_MSG(err) cnioextras_z_errmsg[(err) < -6 || (err) > 2 ? 9 : 2 - (err)]
#define ERR_RETURN(strm,err) \
return (strm->msg = ERR_MSG(err), (err))
/* To be used only when the state is known to be valid */
/* common constants */
#if MAX_WBITS < 9 || MAX_WBITS > 15
# error MAX_WBITS must be in 9..15
#endif
#ifndef DEF_WBITS
# define DEF_WBITS MAX_WBITS
#endif
/* default windowBits for decompression. MAX_WBITS is for compression only */
#if MAX_MEM_LEVEL >= 8
# define DEF_MEM_LEVEL 8
#else
# define DEF_MEM_LEVEL MAX_MEM_LEVEL
#endif
/* default memLevel */
#define STORED_BLOCK 0
#define STATIC_TREES 1
#define DYN_TREES 2
/* The three kinds of block type */
#define MIN_MATCH 3
#define MAX_MATCH 258
/* The minimum and maximum match lengths */
#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
/* target dependencies */
#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
# define OS_CODE 0x00
# ifndef CNIOEXTRAS_Z_SOLO
# if defined(__TURBOC__) || defined(__BORLANDC__)
# if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
/* Allow compilation with ANSI keywords only enabled */
void _Cdecl farfree( void *block );
void *_Cdecl farmalloc( unsigned long nbytes );
# else
# include <alloc.h>
# endif
# else /* MSC or DJGPP */
# include <malloc.h>
# endif
# endif
#endif
#ifdef AMIGA
# define OS_CODE 1
#endif
#if defined(VAXC) || defined(VMS)
# define OS_CODE 2
# define F_OPEN(name, mode) \
fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
#endif
#ifdef __370__
# if __TARGET_LIB__ < 0x20000000
# define OS_CODE 4
# elif __TARGET_LIB__ < 0x40000000
# define OS_CODE 11
# else
# define OS_CODE 8
# endif
#endif
#if defined(ATARI) || defined(atarist)
# define OS_CODE 5
#endif
#ifdef OS2
# define OS_CODE 6
# if defined(M_I86) && !defined(CNIOEXTRAS_Z_SOLO)
# include <malloc.h>
# endif
#endif
#if defined(MACOS)
# define OS_CODE 7
#endif
#if defined(__acorn) || defined(__riscos)
# define OS_CODE 13
#endif
#if defined(WIN32) && !defined(__CYGWIN__)
# define OS_CODE 10
#endif
#ifdef _BEOS_
# define OS_CODE 16
#endif
#ifdef __TOS_OS400__
# define OS_CODE 18
#endif
#ifdef __APPLE__
# define OS_CODE 19
#endif
#if defined(__BORLANDC__) && !defined(MSDOS)
#pragma warn -8004
#pragma warn -8008
#pragma warn -8066
#endif
/* provide prototypes for these when building zlib without LFS */
#ifndef CNIOEXTRAS_Z_LARGE64
ZEXTERN uLong ZEXPORT adler32_combine64(uLong, uLong, cnioextras_z_off64_t);
ZEXTERN uLong ZEXPORT crc32_combine64(uLong, uLong, cnioextras_z_off64_t);
ZEXTERN uLong ZEXPORT crc32_combine_gen64(cnioextras_z_off64_t);
#endif
/* common defaults */
#ifndef OS_CODE
# define OS_CODE 3 /* assume Unix */
#endif
#ifndef F_OPEN
# define F_OPEN(name, mode) fopen((name), (mode))
#endif
/* functions */
#if defined(pyr) || defined(CNIOEXTRAS_Z_SOLO)
# define NO_MEMCPY
#endif
#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
/* Use our own functions for small and medium model with MSC <= 5.0.
* You may have to use the same strategy for Borland C (untested).
* The __SC__ check is for Symantec.
*/
# define NO_MEMCPY
#endif
#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
# define HAVE_MEMCPY
#endif
#ifdef HAVE_MEMCPY
# ifdef SMALL_MEDIUM /* MSDOS small or medium model */
# define zmemcpy _fmemcpy
# define zmemcmp _fmemcmp
# define zmemzero(dest, len) _fmemset(dest, 0, len)
# else
# define zmemcpy memcpy
# define zmemcmp memcmp
# define zmemzero(dest, len) memset(dest, 0, len)
# endif
#else
void CNIOEXTRAS_ZLIB_INTERNAL zmemcpy(void FAR *, const void FAR *, cnioextras_z_size_t);
int CNIOEXTRAS_ZLIB_INTERNAL zmemcmp(const void FAR *, const void FAR *, cnioextras_z_size_t);
void CNIOEXTRAS_ZLIB_INTERNAL zmemzero(void FAR *, cnioextras_z_size_t);
#endif
/* Diagnostic functions */
#ifdef CNIOEXTRAS_ZLIB_DEBUG
# include <stdio.h>
extern int CNIOEXTRAS_ZLIB_INTERNAL cnioextras_z_verbose;
extern void CNIOEXTRAS_ZLIB_INTERNAL cnioextras_z_error(char *m);
# define Assert(cond,msg) {if(!(cond)) cnioextras_z_error(msg);}
# define Trace(x) {if (cnioextras_z_verbose>=0) fprintf x ;}
# define Tracev(x) {if (cnioextras_z_verbose>0) fprintf x ;}
# define Tracevv(x) {if (cnioextras_z_verbose>1) fprintf x ;}
# define Tracec(c,x) {if (cnioextras_z_verbose>0 && (c)) fprintf x ;}
# define Tracecv(c,x) {if (cnioextras_z_verbose>1 && (c)) fprintf x ;}
#else
# define Assert(cond,msg)
# define Trace(x)
# define Tracev(x)
# define Tracevv(x)
# define Tracec(c,x)
# define Tracecv(c,x)
#endif
#ifndef CNIOEXTRAS_Z_SOLO
voidpf CNIOEXTRAS_ZLIB_INTERNAL zcalloc(voidpf opaque, unsigned items,
unsigned size);
void CNIOEXTRAS_ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr);
#endif
#define ZALLOC(strm, items, size) \
(*((strm)->zalloc))((strm)->opaque, (items), (size))
#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
#define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
/* Reverse the bytes in a 32-bit value */
#define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
(((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
#ifdef CNIOEXTRAS_Z_ONCE
/*
Create a local cnioextras_z_once() function depending on the availability of atomics.
*/
/* Check for the availability of atomics. */
#if defined(__STDC__) && __STDC_VERSION__ >= 201112L && \
!defined(__STDC_NO_ATOMICS__)
#include <stdatomic.h>
typedef struct {
atomic_flag begun;
atomic_int done;
} cnioextras_z_once_t;
#define CNIOEXTRAS_Z_ONCE_INIT {ATOMIC_FLAG_INIT, 0}
/*
Run the provided init() function exactly once, even if multiple threads
invoke once() at the same time. The state must be a once_t initialized with
CNIOEXTRAS_Z_ONCE_INIT.
*/
local void cnioextras_z_once(cnioextras_z_once_t *state, void (*init)(void)) {
if (!atomic_load(&state->done)) {
if (atomic_flag_test_and_set(&state->begun))
while (!atomic_load(&state->done))
;
else {
init();
atomic_store(&state->done, 1);
}
}
}
#else /* no atomics */
#warning zlib not thread-safe
typedef struct cnioextras_z_once_s {
volatile int begun;
volatile int done;
} cnioextras_z_once_t;
#define CNIOEXTRAS_Z_ONCE_INIT {0, 0}
/* Test and set. Alas, not atomic, but tries to limit the period of
vulnerability. */
local int test_and_set(int volatile *flag) {
int was;
was = *flag;
*flag = 1;
return was;
}
/* Run the provided init() function once. This is not thread-safe. */
local void cnioextras_z_once(cnioextras_z_once_t *state, void (*init)(void)) {
if (!state->done) {
if (test_and_set(&state->begun))
while (!state->done)
;
else {
init();
state->done = 1;
}
}
}
#endif /* ?atomics */
#endif /* CNIOEXTRAS_Z_ONCE */
#endif /* ZUTIL_H */
File diff suppressed because it is too large. Load diff
@@ -0,0 +1 @@
1.3.2.1-motley
+312
View File
@@ -0,0 +1,312 @@
/* zutil.c -- target dependent utility functions for the compression library
* Copyright (C) 1995-2026 Jean-loup Gailly
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* @(#) $Id$ */
#include "nioextras-zutil.h"
#ifndef CNIOEXTRAS_Z_SOLO
# include "nioextras-gzguts.h"
#endif
cnioextras_z_const char * const cnioextras_z_errmsg[10] = {
(cnioextras_z_const char *)"need dictionary", /* CNIOEXTRAS_Z_NEED_DICT 2 */
(cnioextras_z_const char *)"stream end", /* CNIOEXTRAS_Z_STREAM_END 1 */
(cnioextras_z_const char *)"", /* CNIOEXTRAS_Z_OK 0 */
(cnioextras_z_const char *)"file error", /* CNIOEXTRAS_Z_ERRNO (-1) */
(cnioextras_z_const char *)"stream error", /* CNIOEXTRAS_Z_STREAM_ERROR (-2) */
(cnioextras_z_const char *)"data error", /* CNIOEXTRAS_Z_DATA_ERROR (-3) */
(cnioextras_z_const char *)"insufficient memory", /* CNIOEXTRAS_Z_MEM_ERROR (-4) */
(cnioextras_z_const char *)"buffer error", /* CNIOEXTRAS_Z_BUF_ERROR (-5) */
(cnioextras_z_const char *)"incompatible version",/* CNIOEXTRAS_Z_VERSION_ERROR (-6) */
(cnioextras_z_const char *)""
};
const char * ZEXPORT zlibVersion(void) {
return CNIOEXTRAS_ZLIB_VERSION;
}
uLong ZEXPORT zlibCompileFlags(void) {
uLong flags;
flags = 0;
switch ((int)(sizeof(uInt))) {
case 2: break;
case 4: flags += 1; break;
case 8: flags += 2; break;
default: flags += 3;
}
switch ((int)(sizeof(uLong))) {
case 2: break;
case 4: flags += 1 << 2; break;
case 8: flags += 2 << 2; break;
default: flags += 3 << 2;
}
switch ((int)(sizeof(voidpf))) {
case 2: break;
case 4: flags += 1 << 4; break;
case 8: flags += 2 << 4; break;
default: flags += 3 << 4;
}
switch ((int)(sizeof(cnioextras_z_off_t))) {
case 2: break;
case 4: flags += 1 << 6; break;
case 8: flags += 2 << 6; break;
default: flags += 3 << 6;
}
#ifdef CNIOEXTRAS_ZLIB_DEBUG
flags += 1 << 8;
#endif
/*
#if defined(ASMV) || defined(ASMINF)
flags += 1 << 9;
#endif
*/
#ifdef CNIOEXTRAS_ZLIB_WINAPI
flags += 1 << 10;
#endif
#ifdef BUILDFIXED
flags += 1 << 12;
#endif
#ifdef DYNAMIC_CRC_TABLE
flags += 1 << 13;
#endif
#ifdef NO_GZCOMPRESS
flags += 1L << 16;
#endif
#ifdef NO_GZIP
flags += 1L << 17;
#endif
#ifdef PKZIP_BUG_WORKAROUND
flags += 1L << 20;
#endif
#ifdef FASTEST
flags += 1L << 21;
#endif
#if defined(STDC) || defined(CNIOEXTRAS_Z_HAVE_STDARG_H)
# ifdef NO_vsnprintf
# ifdef CNIOEXTRAS_ZLIB_INSECURE
flags += 1L << 25;
# else
flags += 1L << 27;
# endif
# ifdef HAS_vsprintf_void
flags += 1L << 26;
# endif
# else
# ifdef HAS_vsnprintf_void
flags += 1L << 26;
# endif
# endif
#else
flags += 1L << 24;
# ifdef NO_snprintf
# ifdef CNIOEXTRAS_ZLIB_INSECURE
flags += 1L << 25;
# else
flags += 1L << 27;
# endif
# ifdef HAS_sprintf_void
flags += 1L << 26;
# endif
# else
# ifdef HAS_snprintf_void
flags += 1L << 26;
# endif
# endif
#endif
return flags;
}
#ifdef CNIOEXTRAS_ZLIB_DEBUG
#include <stdlib.h>
# ifndef verbose
# define verbose 0
# endif
int CNIOEXTRAS_ZLIB_INTERNAL cnioextras_z_verbose = verbose;
void CNIOEXTRAS_ZLIB_INTERNAL cnioextras_z_error(char *m) {
fprintf(stderr, "%s\n", m);
exit(1);
}
#endif
/* exported to allow conversion of error code to string for compress() and
* uncompress()
*/
const char * ZEXPORT zError(int err) {
return ERR_MSG(err);
}
#if defined(_WIN32_WCE) && _WIN32_WCE < 0x800
/* The older Microsoft C Run-Time Library for Windows CE doesn't have
* errno. We define it as a global variable to simplify porting.
* Its value is always 0 and should not be used.
*/
int errno = 0;
#endif
#ifndef HAVE_MEMCPY
void CNIOEXTRAS_ZLIB_INTERNAL zmemcpy(void FAR *dst, const void FAR *src, cnioextras_z_size_t n) {
uchf *p = dst;
const uchf *q = src;
while (n) {
*p++ = *q++;
n--;
}
}
int CNIOEXTRAS_ZLIB_INTERNAL zmemcmp(const void FAR *s1, const void FAR *s2, cnioextras_z_size_t n) {
const uchf *p = s1, *q = s2;
while (n) {
if (*p++ != *q++)
return (int)p[-1] - (int)q[-1];
n--;
}
return 0;
}
void CNIOEXTRAS_ZLIB_INTERNAL zmemzero(void FAR *b, cnioextras_z_size_t len) {
uchf *p = b;
while (len) {
*p++ = 0;
len--;
}
}
#endif
#ifndef CNIOEXTRAS_Z_SOLO
#ifdef SYS16BIT
#ifdef __TURBOC__
/* Turbo C in 16-bit mode */
# define MY_ZCALLOC
/* Turbo C malloc() does not allow dynamic allocation of 64K bytes
* and farmalloc(64K) returns a pointer with an offset of 8, so we
* must fix the pointer. Warning: the pointer must be put back to its
* original form in order to free it, use zcfree().
*/
#define MAX_PTR 10
/* 10*64K = 640K */
local int next_ptr = 0;
typedef struct ptr_table_s {
voidpf org_ptr;
voidpf new_ptr;
} ptr_table;
local ptr_table table[MAX_PTR];
/* This table is used to remember the original form of pointers
* to large buffers (64K). Such pointers are normalized with a zero offset.
* Since MSDOS is not a preemptive multitasking OS, this table is not
* protected from concurrent access. This hack doesn't work anyway on
* a protected system like OS/2. Use Microsoft C instead.
*/
voidpf CNIOEXTRAS_ZLIB_INTERNAL zcalloc(voidpf opaque, unsigned items, unsigned size) {
voidpf buf;
ulg bsize = (ulg)items*size;
(void)opaque;
/* If we allocate less than 65520 bytes, we assume that farmalloc
* will return a usable pointer which doesn't have to be normalized.
*/
if (bsize < 65520L) {
buf = farmalloc(bsize);
if (*(ush*)&buf != 0) return buf;
} else {
buf = farmalloc(bsize + 16L);
}
if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
table[next_ptr].org_ptr = buf;
/* Normalize the pointer to seg:0 */
*((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
*(ush*)&buf = 0;
table[next_ptr++].new_ptr = buf;
return buf;
}
void CNIOEXTRAS_ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr) {
int n;
(void)opaque;
if (*(ush*)&ptr != 0) { /* object < 64K */
farfree(ptr);
return;
}
/* Find the original pointer */
for (n = 0; n < next_ptr; n++) {
if (ptr != table[n].new_ptr) continue;
farfree(table[n].org_ptr);
while (++n < next_ptr) {
table[n-1] = table[n];
}
next_ptr--;
return;
}
Assert(0, "zcfree: ptr not found");
}
#endif /* __TURBOC__ */
#ifdef M_I86
/* Microsoft C in 16-bit mode */
# define MY_ZCALLOC
#if (!defined(_MSC_VER) || (_MSC_VER <= 600))
# define _halloc halloc
# define _hfree hfree
#endif
voidpf CNIOEXTRAS_ZLIB_INTERNAL zcalloc(voidpf opaque, uInt items, uInt size) {
(void)opaque;
return _halloc((long)items, size);
}
void CNIOEXTRAS_ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr) {
(void)opaque;
_hfree(ptr);
}
#endif /* M_I86 */
#endif /* SYS16BIT */
#ifndef MY_ZCALLOC /* Any system without a special alloc function */
#ifndef STDC
extern voidp malloc(uInt size);
extern voidp calloc(uInt items, uInt size);
extern void free(voidpf ptr);
#endif
voidpf CNIOEXTRAS_ZLIB_INTERNAL zcalloc(voidpf opaque, unsigned items, unsigned size) {
(void)opaque;
return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
(voidpf)calloc(items, size);
}
void CNIOEXTRAS_ZLIB_INTERNAL zcfree(voidpf opaque, voidpf ptr) {
(void)opaque;
free(ptr);
}
#endif /* MY_ZCALLOC */
#endif /* !CNIOEXTRAS_Z_SOLO */
@@ -54,7 +54,7 @@ public enum NIOCompression: Sendable {
/// Data compression utility.
struct Compressor {
private var stream = z_stream()
private var stream = cnioextras_z_stream()
var isActive = false
init() {}
@@ -79,13 +79,13 @@ public enum NIOCompression: Sendable {
let rc = CNIOExtrasZlib_deflateInit2(
&stream,
Z_DEFAULT_COMPRESSION,
Z_DEFLATED,
CNIOEXTRAS_Z_DEFAULT_COMPRESSION,
CNIOEXTRAS_Z_DEFLATED,
windowBits,
8,
Z_DEFAULT_STRATEGY
CNIOEXTRAS_Z_DEFAULT_STRATEGY
)
precondition(rc == Z_OK, "Unexpected return from zlib init: \(rc)")
precondition(rc == CNIOEXTRAS_Z_OK, "Unexpected return from zlib init: \(rc)")
}
mutating func compress(
@@ -94,20 +94,20 @@ public enum NIOCompression: Sendable {
finalise: Bool
) -> ByteBuffer {
assert(isActive)
let flags = finalise ? Z_FINISH : Z_SYNC_FLUSH
let flags = finalise ? CNIOEXTRAS_Z_FINISH : CNIOEXTRAS_Z_SYNC_FLUSH
// don't compress an empty buffer if we aren't finishing the compress
guard inputBuffer.readableBytes > 0 || finalise == true else { return allocator.buffer(capacity: 0) }
// deflateBound() provides an upper limit on the number of bytes the input can
// compress to. We add 5 bytes to handle the fact that Z_SYNC_FLUSH will append
// cnioextras_z_deflateBound() provides an upper limit on the number of bytes the input can
// compress to. We add 5 bytes to handle the fact that CNIOEXTRAS_Z_SYNC_FLUSH will append
// an empty stored block that is 5 bytes long.
// From zlib docs (https://www.zlib.net/manual.html)
// If the parameter flush is set to Z_SYNC_FLUSH, all pending output is flushed to the output buffer and the output is
// If the parameter flush is set to CNIOEXTRAS_Z_SYNC_FLUSH, all pending output is flushed to the output buffer and the output is
// aligned on a byte boundary, so that the decompressor can get all input data available so far. (In particular avail_in
// is zero after the call if enough output space has been provided before the call.) Flushing may degrade compression for
// some compression algorithms and so it should be used only when necessary. This completes the current deflate block and
// follows it with an empty stored block that is three bits plus filler bits to the next byte, followed by four bytes
// (00 00 ff ff).
let bufferSize = Int(deflateBound(&stream, UInt(inputBuffer.readableBytes)))
let bufferSize = Int(cnioextras_z_deflateBound(&stream, UInt(inputBuffer.readableBytes)))
var outputBuffer = allocator.buffer(capacity: bufferSize + 5)
stream.oneShotDeflate(from: &inputBuffer, to: &outputBuffer, flag: flags)
return outputBuffer
@@ -116,19 +116,19 @@ public enum NIOCompression: Sendable {
mutating func shutdown() {
assert(isActive)
isActive = false
deflateEnd(&stream)
cnioextras_z_deflateEnd(&stream)
}
mutating func shutdownIfActive() {
if isActive {
isActive = false
deflateEnd(&stream)
cnioextras_z_deflateEnd(&stream)
}
}
}
}
extension z_stream {
extension cnioextras_z_stream {
/// Executes deflate from one buffer to another buffer. The advantage of this method is that it
/// will ensure that the stream is "safe" after each call (that is, that the stream does not have
/// pointers to byte buffers any longer).
@@ -151,7 +151,7 @@ extension z_stream {
self.next_in = typedDataPtr.baseAddress!
let rc = deflateToBuffer(buffer: &to, flag: flag)
precondition(rc == Z_OK || rc == Z_STREAM_END, "One-shot compression failed: \(rc)")
precondition(rc == CNIOEXTRAS_Z_OK || rc == CNIOEXTRAS_Z_STREAM_END, "One-shot compression failed: \(rc)")
return typedDataPtr.count - Int(self.avail_in)
}
@@ -161,7 +161,7 @@ extension z_stream {
/// This relies on having the input set by the previous caller: it will use whatever input was
/// configured.
private mutating func deflateToBuffer(buffer: inout ByteBuffer, flag: Int32) -> Int32 {
var rc = Z_OK
var rc = CNIOEXTRAS_Z_OK
buffer.writeWithUnsafeMutableBytes(minimumWritableBytes: buffer.capacity) { outputPtr in
let typedOutputPtr = UnsafeMutableBufferPointer(
@@ -170,7 +170,7 @@ extension z_stream {
)
self.avail_out = UInt32(typedOutputPtr.count)
self.next_out = typedOutputPtr.baseAddress!
rc = deflate(&self, flag)
rc = cnioextras_z_deflate(&self, flag)
return typedOutputPtr.count - Int(self.avail_out)
}
@@ -124,13 +124,13 @@ public enum NIOHTTPDecompression: Sendable {
/// or add 16 to decode only the gzip format (the zlib format will return a Z_DATA_ERROR).
/// If a gzip stream is being decoded, strm->adler is a CRC-32 instead of an Adler-32.
/// Unlike the gunzip utility and gzread() (see below), inflate() will not automatically decode concatenated gzip members.
/// inflate() will return Z_STREAM_END at the end of the gzip member.
/// inflate() will return CNIOEXTRAS_Z_STREAM_END at the end of the gzip member.
/// The state would need to be reset to continue decoding a subsequent gzip member.
/// This must be done if there is more data after a gzip member, in order for the decompression to be compliant with the gzip standard (RFC 1952).
static let windowBitsWithAutomaticCompressionFormatDetection: Int32 = 15 + 32
private let limit: NIOHTTPDecompression.DecompressionLimit
private var stream = z_stream()
private var stream = cnioextras_z_stream()
private var inflated = 0
init(limit: NIOHTTPDecompression.DecompressionLimit) {
@@ -159,18 +159,18 @@ public enum NIOHTTPDecompression: Sendable {
self.inflated = 0
let rc = CNIOExtrasZlib_inflateInit2(&self.stream, Self.windowBitsWithAutomaticCompressionFormatDetection)
guard rc == Z_OK else {
guard rc == CNIOEXTRAS_Z_OK else {
throw NIOHTTPDecompression.DecompressionError.initializationError(Int(rc))
}
}
mutating func deinitializeDecoder() {
inflateEnd(&self.stream)
cnioextras_z_inflateEnd(&self.stream)
}
}
}
extension z_stream {
extension cnioextras_z_stream {
mutating func inflatePart(input: inout ByteBuffer, output: inout ByteBuffer) throws -> InflateResult {
let minimumCapacity = input.readableBytes * 2
var inflateResult = InflateResult(written: 0, complete: false)
@@ -194,21 +194,21 @@ extension z_stream {
}
private mutating func inflatePart(to buffer: inout ByteBuffer, minimumCapacity: Int) throws -> InflateResult {
var rc = Z_OK
var rc = CNIOEXTRAS_Z_OK
let written = try buffer.writeWithUnsafeMutableBytes(minimumWritableBytes: minimumCapacity) { pointer in
self.avail_out = UInt32(pointer.count)
self.next_out = CNIOExtrasZlib_voidPtr_to_BytefPtr(pointer.baseAddress!)
rc = inflate(&self, Z_NO_FLUSH)
guard rc == Z_OK || rc == Z_STREAM_END else {
rc = cnioextras_z_inflate(&self, CNIOEXTRAS_Z_NO_FLUSH)
guard rc == CNIOEXTRAS_Z_OK || rc == CNIOEXTRAS_Z_STREAM_END else {
throw NIOHTTPDecompression.DecompressionError.inflationError(Int(rc))
}
return pointer.count - Int(self.avail_out)
}
return InflateResult(written: written, complete: rc == Z_STREAM_END)
return InflateResult(written: written, complete: rc == CNIOEXTRAS_Z_STREAM_END)
}
}
@@ -145,7 +145,7 @@ class HTTPRequestCompressorTest: XCTestCase {
_ = try write(body: [buffer], to: channel)
var result = try read(from: channel)
var uncompressedBuffer = ByteBufferAllocator().buffer(capacity: buffer.readableBytes)
z_stream.decompressGzip(compressedBytes: &result.body, outputBuffer: &uncompressedBuffer)
cnioextras_z_stream.decompressGzip(compressedBytes: &result.body, outputBuffer: &uncompressedBuffer)
XCTAssertEqual(buffer, uncompressedBuffer)
XCTAssertEqual(result.head.headers["content-encoding"].first, "gzip")
@@ -167,7 +167,7 @@ class HTTPRequestCompressorTest: XCTestCase {
try write(body: buffers, to: channel)
var result = try read(from: channel)
var uncompressedBuffer = ByteBufferAllocator().buffer(capacity: buffersConcat.readableBytes)
z_stream.decompressGzip(compressedBytes: &result.body, outputBuffer: &uncompressedBuffer)
cnioextras_z_stream.decompressGzip(compressedBytes: &result.body, outputBuffer: &uncompressedBuffer)
XCTAssertEqual(buffersConcat, uncompressedBuffer)
XCTAssertEqual(result.head.headers["content-encoding"].first, "gzip")
@@ -189,7 +189,7 @@ class HTTPRequestCompressorTest: XCTestCase {
try write(body: buffers, to: channel)
var result = try read(from: channel)
var uncompressedBuffer = ByteBufferAllocator().buffer(capacity: buffersConcat.readableBytes)
z_stream.decompressDeflate(compressedBytes: &result.body, outputBuffer: &uncompressedBuffer)
cnioextras_z_stream.decompressDeflate(compressedBytes: &result.body, outputBuffer: &uncompressedBuffer)
XCTAssertEqual(buffersConcat, uncompressedBuffer)
XCTAssertEqual(result.head.headers["content-encoding"].first, "deflate")
@@ -211,7 +211,7 @@ class HTTPRequestCompressorTest: XCTestCase {
try writeWithIntermittantFlush(body: buffers, to: channel)
var result = try read(from: channel)
var uncompressedBuffer = ByteBufferAllocator().buffer(capacity: buffersConcat.readableBytes)
z_stream.decompressGzip(compressedBytes: &result.body, outputBuffer: &uncompressedBuffer)
cnioextras_z_stream.decompressGzip(compressedBytes: &result.body, outputBuffer: &uncompressedBuffer)
XCTAssertEqual(buffersConcat, uncompressedBuffer)
XCTAssertEqual(result.head.headers["content-encoding"].first, "gzip")
@@ -240,7 +240,7 @@ class HTTPRequestCompressorTest: XCTestCase {
var result = try read(from: channel)
var uncompressedBuffer = ByteBufferAllocator().buffer(capacity: buffer.readableBytes)
z_stream.decompressGzip(compressedBytes: &result.body, outputBuffer: &uncompressedBuffer)
cnioextras_z_stream.decompressGzip(compressedBytes: &result.body, outputBuffer: &uncompressedBuffer)
XCTAssertEqual(buffer, uncompressedBuffer)
XCTAssertEqual(result.head.headers["content-encoding"].first, "gzip")
@@ -267,7 +267,7 @@ class HTTPRequestCompressorTest: XCTestCase {
var result = try read(from: channel)
var uncompressedBuffer = ByteBufferAllocator().buffer(capacity: buffer.readableBytes)
z_stream.decompressGzip(compressedBytes: &result.body, outputBuffer: &uncompressedBuffer)
cnioextras_z_stream.decompressGzip(compressedBytes: &result.body, outputBuffer: &uncompressedBuffer)
XCTAssertEqual(buffer, uncompressedBuffer)
XCTAssertEqual(result.head.headers["content-encoding"].first, "gzip")
@@ -299,7 +299,7 @@ class HTTPRequestCompressorTest: XCTestCase {
var result = try read(from: channel)
var uncompressedBuffer = ByteBufferAllocator().buffer(capacity: buffer.readableBytes)
z_stream.decompressGzip(compressedBytes: &result.body, outputBuffer: &uncompressedBuffer)
cnioextras_z_stream.decompressGzip(compressedBytes: &result.body, outputBuffer: &uncompressedBuffer)
XCTAssertEqual(buffer, uncompressedBuffer)
XCTAssertEqual(result.head.headers["content-encoding"].first, "gzip")
@@ -373,7 +373,7 @@ extension ByteBuffer {
}
}
extension z_stream {
extension cnioextras_z_stream {
fileprivate static func decompressDeflate(compressedBytes: inout ByteBuffer, outputBuffer: inout ByteBuffer) {
decompress(compressedBytes: &compressedBytes, outputBuffer: &outputBuffer, windowSize: 15)
}
@@ -386,7 +386,7 @@ extension z_stream {
{
compressedBytes.withUnsafeMutableReadableUInt8Bytes { inputPointer in
outputBuffer.writeWithUnsafeMutableUInt8Bytes { outputPointer -> Int in
var stream = z_stream()
var stream = cnioextras_z_stream()
// zlib requires we initialize next_in, avail_in, zalloc, zfree and opaque before calling inflateInit2.
stream.next_in = inputPointer.baseAddress!
@@ -398,14 +398,14 @@ extension z_stream {
stream.opaque = nil
var rc = CNIOExtrasZlib_inflateInit2(&stream, windowSize)
precondition(rc == Z_OK)
precondition(rc == CNIOEXTRAS_Z_OK)
rc = inflate(&stream, Z_FINISH)
XCTAssertEqual(rc, Z_STREAM_END)
rc = cnioextras_z_inflate(&stream, CNIOEXTRAS_Z_FINISH)
XCTAssertEqual(rc, CNIOEXTRAS_Z_STREAM_END)
XCTAssertEqual(stream.avail_in, 0)
rc = inflateEnd(&stream)
XCTAssertEqual(rc, Z_OK)
rc = cnioextras_z_inflateEnd(&stream)
XCTAssertEqual(rc, CNIOEXTRAS_Z_OK)
return outputPointer.count - Int(stream.avail_out)
}
@@ -215,7 +215,7 @@ class HTTPRequestDecompressorTest: XCTestCase {
}
private func compress(_ body: ByteBuffer, _ algorithm: String) -> ByteBuffer {
var stream = z_stream()
var stream = cnioextras_z_stream()
stream.zalloc = nil
stream.zfree = nil
@@ -236,13 +236,13 @@ class HTTPRequestDecompressorTest: XCTestCase {
let rc = CNIOExtrasZlib_deflateInit2(
&stream,
Z_DEFAULT_COMPRESSION,
Z_DEFLATED,
CNIOEXTRAS_Z_DEFAULT_COMPRESSION,
CNIOEXTRAS_Z_DEFLATED,
windowBits,
8,
Z_DEFAULT_STRATEGY
CNIOEXTRAS_Z_DEFAULT_STRATEGY
)
XCTAssertEqual(Z_OK, rc)
XCTAssertEqual(CNIOEXTRAS_Z_OK, rc)
defer {
stream.avail_in = 0
@@ -270,15 +270,15 @@ class HTTPRequestDecompressorTest: XCTestCase {
)
stream.avail_out = UInt32(typedOutputPtr.count)
stream.next_out = typedOutputPtr.baseAddress!
let rc = deflate(&stream, Z_FINISH)
XCTAssertTrue(rc == Z_OK || rc == Z_STREAM_END)
let rc = cnioextras_z_deflate(&stream, CNIOEXTRAS_Z_FINISH)
XCTAssertTrue(rc == CNIOEXTRAS_Z_OK || rc == CNIOEXTRAS_Z_STREAM_END)
return typedOutputPtr.count - Int(stream.avail_out)
}
return typedDataPtr.count - Int(stream.avail_in)
}
deflateEnd(&stream)
cnioextras_z_deflateEnd(&stream)
return buffer
}
@@ -88,7 +88,7 @@ extension ByteBuffer {
}
}
extension z_stream {
extension cnioextras_z_stream {
fileprivate static func decompressDeflate(compressedBytes: inout ByteBuffer, outputBuffer: inout ByteBuffer) {
decompress(compressedBytes: &compressedBytes, outputBuffer: &outputBuffer, windowSize: 15)
}
@@ -101,7 +101,7 @@ extension z_stream {
{
compressedBytes.withUnsafeMutableReadableUInt8Bytes { inputPointer in
outputBuffer.writeWithUnsafeMutableUInt8Bytes { outputPointer -> Int in
var stream = z_stream()
var stream = cnioextras_z_stream()
// zlib requires we initialize next_in, avail_in, zalloc, zfree and opaque before calling inflateInit2.
stream.next_in = inputPointer.baseAddress!
@@ -113,14 +113,14 @@ extension z_stream {
stream.opaque = nil
var rc = CNIOExtrasZlib_inflateInit2(&stream, windowSize)
precondition(rc == Z_OK)
precondition(rc == CNIOEXTRAS_Z_OK)
rc = inflate(&stream, Z_FINISH)
XCTAssertEqual(rc, Z_STREAM_END)
rc = cnioextras_z_inflate(&stream, CNIOEXTRAS_Z_FINISH)
XCTAssertEqual(rc, CNIOEXTRAS_Z_STREAM_END)
XCTAssertEqual(stream.avail_in, 0)
rc = inflateEnd(&stream)
XCTAssertEqual(rc, Z_OK)
rc = cnioextras_z_inflateEnd(&stream)
XCTAssertEqual(rc, CNIOEXTRAS_Z_OK)
return outputPointer.count - Int(stream.avail_out)
}
@@ -304,7 +304,7 @@ class HTTPResponseCompressorTest: XCTestCase {
responseData: &compressedBody,
expectedResponse: bodyBuffer,
allocator: channel.allocator,
decompressor: z_stream.decompressDeflate
decompressor: cnioextras_z_stream.decompressDeflate
)
}
@@ -360,7 +360,7 @@ class HTTPResponseCompressorTest: XCTestCase {
responseData: &compressedBody,
expectedResponse: bodyBuffer,
allocator: channel.allocator,
decompressor: z_stream.decompressGzip
decompressor: cnioextras_z_stream.decompressGzip
)
}
@@ -361,7 +361,7 @@ class HTTPResponseDecompressorTest: XCTestCase {
}
private func compress(_ body: ByteBuffer, _ algorithm: String) -> ByteBuffer {
var stream = z_stream()
var stream = cnioextras_z_stream()
stream.zalloc = nil
stream.zfree = nil
@@ -382,13 +382,13 @@ class HTTPResponseDecompressorTest: XCTestCase {
let rc = CNIOExtrasZlib_deflateInit2(
&stream,
Z_DEFAULT_COMPRESSION,
Z_DEFLATED,
CNIOEXTRAS_Z_DEFAULT_COMPRESSION,
CNIOEXTRAS_Z_DEFLATED,
windowBits,
8,
Z_DEFAULT_STRATEGY
CNIOEXTRAS_Z_DEFAULT_STRATEGY
)
XCTAssertEqual(Z_OK, rc)
XCTAssertEqual(CNIOEXTRAS_Z_OK, rc)
defer {
stream.avail_in = 0
@@ -416,15 +416,15 @@ class HTTPResponseDecompressorTest: XCTestCase {
)
stream.avail_out = UInt32(typedOutputPtr.count)
stream.next_out = typedOutputPtr.baseAddress!
let rc = deflate(&stream, Z_FINISH)
XCTAssertTrue(rc == Z_OK || rc == Z_STREAM_END)
let rc = cnioextras_z_deflate(&stream, CNIOEXTRAS_Z_FINISH)
XCTAssertTrue(rc == CNIOEXTRAS_Z_OK || rc == CNIOEXTRAS_Z_STREAM_END)
return typedOutputPtr.count - Int(stream.avail_out)
}
return typedDataPtr.count - Int(stream.avail_in)
}
deflateEnd(&stream)
cnioextras_z_deflateEnd(&stream)
return buffer
}
+235
View File
@@ -0,0 +1,235 @@
#!/bin/bash
##===----------------------------------------------------------------------===##
##
## This source file is part of the SwiftNIO open source project
##
## Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors
## Licensed under Apache License v2.0
##
## See LICENSE.txt for license information
## See CONTRIBUTORS.txt for the list of SwiftNIO project authors
##
## SPDX-License-Identifier: Apache-2.0
##
##===----------------------------------------------------------------------===##
# Vendors zlib into Sources/CNIOExtrasZlib with Z_PREFIX using cnioextras_ prefix.
# Usage: dev/vendor-zlib.sh <path-to-zlib-checkout>
# The zlib checkout must have had ./configure run already.
set -eu
here="$(cd "$(dirname "$0")" && pwd)"
root="$(cd "${here}/.." && pwd)"
target_dir="${root}/Sources/CNIOExtrasZlib"
include_dir="${target_dir}/include"
# --- Validate arguments ---
if [[ $# -ne 1 ]]; then
echo "Usage: $0 <path-to-zlib-checkout>"
exit 1
fi
zlib_dir="$1"
if [[ ! -f "${zlib_dir}/zlib.h" ]]; then
echo "Error: ${zlib_dir}/zlib.h not found. Is this a zlib checkout?"
exit 1
fi
if [[ ! -f "${zlib_dir}/zconf.h" ]]; then
echo "Error: ${zlib_dir}/zconf.h not found. Did you run ./configure?"
exit 1
fi
zlib_version="$(grep '#define ZLIB_VERSION' "${zlib_dir}/zlib.h" | head -1 | sed -E 's/.*"(.*)".*/\1/')"
zlib_git_desc="$(cd "${zlib_dir}" && git describe --abbrev --dirty 2>/dev/null || echo "${zlib_version}")"
echo "Vendoring zlib ${zlib_version} from ${zlib_dir}"
# --- Source files to copy ---
c_files=(
adler32.c
crc32.c
deflate.c
inffast.c
inflate.c
inftrees.c
trees.c
zutil.c
)
# Public headers (go into include/)
public_headers=(
zlib.h
zconf.h
)
# Private headers (go into source dir)
private_headers=(
zutil.h
deflate.h
inflate.h
inftrees.h
inffast.h
crc32.h
gzguts.h
trees.h
inffixed.h
)
# --- Clean old vendored files ---
echo "Cleaning old vendored files..."
# Remove old .c files
for f in "${c_files[@]}"; do
rm -f "${target_dir}/${f}"
done
# Remove old private headers
for h in "${private_headers[@]}"; do
rm -f "${target_dir}/nioextras-${h}"
done
# Remove old public headers (but keep CNIOExtrasZlib.h - we regenerate it)
for h in "${public_headers[@]}"; do
rm -f "${include_dir}/nioextras-${h}"
done
# Remove empty.c if present
rm -f "${target_dir}/empty.c"
# --- Copy C source files ---
echo "Copying source files..."
for f in "${c_files[@]}"; do
cp "${zlib_dir}/${f}" "${target_dir}/${f}"
done
# --- Copy and rename headers ---
echo "Copying and renaming headers..."
for h in "${public_headers[@]}"; do
cp "${zlib_dir}/${h}" "${include_dir}/nioextras-${h}"
done
for h in "${private_headers[@]}"; do
cp "${zlib_dir}/${h}" "${target_dir}/nioextras-${h}"
done
# --- Update #include directives ---
echo "Updating #include directives..."
all_headers=("${public_headers[@]}" "${private_headers[@]}")
all_vendored_files=()
for f in "${c_files[@]}"; do
all_vendored_files+=("${target_dir}/${f}")
done
for h in "${public_headers[@]}"; do
all_vendored_files+=("${include_dir}/nioextras-${h}")
done
for h in "${private_headers[@]}"; do
all_vendored_files+=("${target_dir}/nioextras-${h}")
done
for h in "${all_headers[@]}"; do
# Replace "header.h" -> "nioextras-header.h"
sed -i '' "s|\"${h}\"|\"nioextras-${h}\"|g" "${all_vendored_files[@]}"
# Replace <header.h> -> <nioextras-header.h>
sed -i '' "s|<${h}>|<nioextras-${h}>|g" "${all_vendored_files[@]}"
done
# --- Enable Z_PREFIX ---
echo "Enabling Z_PREFIX..."
sed -i '' 's/^#ifdef Z_PREFIX.*$/#if 1 \/* Z_PREFIX - cnioextras_z_ *\//' "${include_dir}/nioextras-zconf.h"
# --- Rename symbols with cnioextras_ prefix ---
echo "Applying cnioextras_ prefix..."
# Broad renames across all vendored files (order matters):
# 1. z_ -> cnioextras_z_ at word boundaries (types and Z_PREFIX targets)
# Uses word-boundary to avoid matching z_ inside gz_header etc.
sed -i '' -E 's/(^|[^a-zA-Z_])z_/\1cnioextras_z_/g' "${all_vendored_files[@]}"
# 2. Z_ -> CNIOEXTRAS_Z_ at word boundaries (constants like Z_OK, Z_FINISH, Z_PREFIX_SET)
sed -i '' -E 's/(^|[^a-zA-Z_])Z_/\1CNIOEXTRAS_Z_/g' "${all_vendored_files[@]}"
# 3. ZLIB_ -> CNIOEXTRAS_ZLIB_ at word boundaries (ZLIB_VERSION, ZLIB_INTERNAL, etc.)
# Also handles ZLIB_H include guard.
sed -i '' -E 's/(^|[^a-zA-Z_])ZLIB_/\1CNIOEXTRAS_ZLIB_/g' "${all_vendored_files[@]}"
# --- Rename ZCONF_H include guard (not caught by the above) ---
echo "Renaming include guards..."
sed -i '' 's/ZCONF_H/NIOEXTRAS_ZCONF_H/g' "${include_dir}/nioextras-zconf.h"
# --- Regenerate CNIOExtrasZlib.h ---
echo "Regenerating CNIOExtrasZlib.h..."
cat > "${include_dir}/CNIOExtrasZlib.h" << 'HEADER'
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2026 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#ifndef C_NIO_ZLIB_H
#define C_NIO_ZLIB_H
#include "nioextras-zlib.h"
static inline int CNIOExtrasZlib_deflateInit2(cnioextras_z_streamp strm,
int level,
int method,
int windowBits,
int memLevel,
int strategy) {
return cnioextras_z_deflateInit2(strm, level, method, windowBits, memLevel, strategy);
}
static inline int CNIOExtrasZlib_inflateInit2(cnioextras_z_streamp strm, int windowBits) {
return cnioextras_z_inflateInit2(strm, windowBits);
}
static inline cnioextras_z_Bytef *CNIOExtrasZlib_voidPtr_to_BytefPtr(void *in) {
return (cnioextras_z_Bytef *)in;
}
#endif
HEADER
# --- Write version file ---
echo "${zlib_git_desc}" > "${target_dir}/vendored-zlib.version"
# --- Validate with clang + nm ---
echo "Validating symbol prefixes..."
validation_failed=0
tmpdir="$(mktemp -d)"
trap 'rm -rf "${tmpdir}"' EXIT
for f in "${c_files[@]}"; do
if clang -c -DHAVE_HIDDEN -I"${include_dir}" -I"${target_dir}" \
"${target_dir}/${f}" -o "${tmpdir}/${f}.o" 2>/dev/null; then
bad_symbols="$(nm "${tmpdir}/${f}.o" 2>/dev/null | grep ' T ' | grep -v 'cnioextras_' || true)"
if [[ -n "${bad_symbols}" ]]; then
echo "WARNING: ${f} has unprefixed public symbols:"
echo "${bad_symbols}"
validation_failed=1
fi
else
echo "WARNING: Failed to compile ${f} for validation"
validation_failed=1
fi
done
if [[ "${validation_failed}" -eq 0 ]]; then
echo "Validation passed: all public symbols have cnioextras_ prefix"
else
echo "ERROR: Some validation checks failed (see above)"
exit 1
fi
echo "Done! zlib ${zlib_version} vendored into Sources/CNIOExtrasZlib/"