deflateInit2_
Start a compressor with a chosen wrapper and compression settings.
Full chapter and shared rules ↗int ZEXPORT deflateInit2_(z_streamp strm, int level, int method, int windowBits,
int memLevel, int strategy, const char *version, int stream_size);
Start a compressor with a chosen wrapper and compression settings.
The parameters decide different things. level trades compression speed against match-search
effort. method selects the compression method; this entry accepts DEFLATE only. memLevel sets
the memory given to the internal index and the symbol buffer. strategy adjusts which matching or
coding strategy is used. windowBits encodes both the wrapper and the window size: remove the sign
or the added constant to get an exponent b, and the window has 2^b bytes. So 15, -15 and 31 all
mean 32768 bytes, with a zlib, a raw and a gzip wrapper.
Return values and next calls
Return type. int — zlib status code
The result separates an established compressor from compatibility, argument and allocation failures. Only Z_OK establishes a live stream that needs ending.
deflateInit2_()| Returned value | Meaning and conditions | Caller’s next step |
|---|---|---|
Z_OKCompressor established |
Compatibility and parameters are valid, and all five allocations succeed; the selected wrapper and settings are installed. | Supply buffers and begin compression; eventually call deflateEnd, even if abandoning the task. |
Z_VERSION_ERRORCompatibility refused |
version is NULL, its first byte does not match, or stream_size differs from sizeof(z_stream). This check precedes the strm check and changes no stream fields. | Correct the version and structure size before initialization; this result creates no new state to release. |
Z_STREAM_ERRORNull stream |
Compatibility passes, but strm is NULL. | Provide a writable stream record satisfying initialization preconditions. |
Z_STREAM_ERRORParameters refused |
method, level, windowBits, memLevel or strategy is outside its accepted range. Refusal precedes allocation, but msg has been cleared and default allocator installation may have cleared opaque. | Correct the parameters and reinitialize under the init preconditions; there are no new allocations to end. |
Z_MEM_ERRORState allocation failed |
The initial state allocation fails; state retains its entry value and no newly allocated block remains live. | After addressing memory pressure, retry under the init preconditions; this failure needs no deflateEnd. |
Z_MEM_ERRORBuffer allocation failed and cleaned up |
After state allocation succeeds, all four buffer allocations are attempted. Any failure releases every new block, sets state to NULL and reports insufficient memory in msg. | Cleanup is complete for this call; address memory pressure before initializing again. |
Reading the result.
- Level -1 selects 6.
Calling conditions and effects
Domain Restricted domain. Effect: allocate and initialise.
Pre the stream and version conditions of deflateInit_ hold. Parameters are:
level -1 or 0..9; method == Z_DEFLATED; memLevel 1..9; strategy 0..4;
windowBits 8..15 for zlib, -15..-9 for raw, or 25..31 for gzip.
Proof goals.
- Goal.
Goal.deflateInit2__safety(Safety/Initialisation.lean); required. Theorem:ZlibF.Spec.Public.InitSafetyProof.deflateInit2__safety(public-init-safety.lean). - Applies when (
InitArguments):- the heap is a library heap (
Fresh,Uniq,LibraryGlobals); versionis NULL or its first byte is readable (VersionValue);strmis NULL, or points to a readable stream record whosezallocandzfreeare each NULL or the default function (DefaultOrNull).
- the heap is a library heap (
- Covered without condition. Every
level,method,windowBits,memLevelandstrategy, valid or not; everystream_size; every value of the first byte ofversion; every value of the other fields of the record,stateincluded; every allocation outcome. If the record was a live stream, the call still returns, but the old state stays allocated and the record no longer points to it: the account records that leak, it does not exclude it. - Guarantees (
InitResultSafe).- Returns. The call returns. With a NULL
strmthe code isZ_VERSION_ERRORorZ_STREAM_ERROR. - State. With
Z_OK,strmis a reachable stream. - Writes. With a NULL
strm, nothing: the heap is unchanged. Otherwise only the stream record and blocks the call itself allocates. - Allocations. With
Z_OK, every block the call allocated is one of the stream's own blocks, and nothing is freed (LiveChange). With any other code the allocated blocks are the same as before the call.
- Returns. The call returns. With a NULL
- Not in this goal. A stream whose
zallocorzfreeis a custom function: outside every goal (deviations). Which code each refusal and each allocation failure returns, and the field values after the call: functional goalGoal.deflateInit2_(not planned; a theorem proves it). That some call does returnZ_OK:Goal.deflate_initialisation_domain(Safety/Domains.lean), required.
Complete return conditions and boundaries
Post Z_OK establishes a live stream with five owned allocations and the selected
settings. A zlib window request of 8 becomes 9. Totals are zero, msg is NULL,
data_type is Z_UNKNOWN, and adler is 1 for raw/zlib or 0 for gzip.
I/O pointers and available counts are unchanged; no bytes are consumed or emitted.
The caller releases the state with deflateEnd.
Z_MEM_ERROR leaves no newly allocated block live. If the state allocation fails,
state retains its entry value. If a later allocation fails, state becomes NULL and
msg reports insufficient memory. Once the state allocation succeeds, all four buffer
allocations are attempted before failure cleanup.
Outside focused scope: a NULL/mismatched version first byte or wrong structure size
returns Z_VERSION_ERROR without changing the stream. With compatible version and NULL
strm, return Z_STREAM_ERROR. Other scalar parameters outside the accepted ranges
return Z_STREAM_ERROR before allocation, after clearing msg and installing default
allocator fields where needed. Installing the default allocator clears opaque.
The safety goal covers these calls: each one returns and leaves the allocated blocks as they
were. Which code each one returns is stated by the functional init goals.
Shared conditions and scope
Use a z_stream compressor when input arrives in pieces, output space is limited, or you
need a chosen wrapper, dictionary or flush boundary. A wrapper is the header, trailer and
integrity information added around the DEFLATE data; raw DEFLATE has none. Initialize once, call deflate with
successive buffers, and end the stream even if compression is abandoned. For a single buffer,
see compress and compress2.
| Task | Entries |
|---|---|
| Start or reuse | Init, configured init, reset, reset retaining history |
| Supply metadata or history | Dictionary, read history, gzip header |
| Compress and size output | Deflate, bound, pending output, last flush bits |
| Adjust or branch | Parameters, tuning, priming, copy |
| Release storage | End |
The contracts follow zlib.h and deflate.c of the pinned zlib with the
patches applied, in the default LP64 Linux build. Of the seven patches
only patches 0006 and 0007 touch deflate.c. Both change deflateBound_z, and with it the result
of deflateBound, which calls deflateBound_z: 0006 one condition, 0007 the length of the gzip extra
field in the wrapper size. The entry deflateBound_z states both changes. The
patches change no other function.
These are focused contracts: Pre describes ordinary correct use and is deliberately narrower than
what the function accepts. Cases outside Pre that the C still handles appear under Errors or
Outside focused scope. A call outside Pre is not thereby undefined, and it need not return an
error code. See how to read a contract for the domain and effect labels.
What is proved. Safety only: each call returns without undefined behaviour or a memory error, writes only what its goal names, and leaks nothing (safety). Each entry gives its goal under Proof goals, in the five items and with the fixed phrases that Reading a Proof goals paragraph defines: the goal and its theorem; the conditions under which it applies, in the order of the Lean statement; what it covers for every value; what it guarantees (returns, state, writes, allocations); and what it leaves to another goal. The proof assumes the conditions listed there, not the documentary Pre. Post, the return tables and the notes describe functional behaviour. They are read from the C, are to confirm where no theorem states them, and are not required for the safety results. Progress says which goals are done.
Shared conventions
Under each stated Pre, the documented behaviour is that the call terminates without a runtime fault and that Post holds. A call that leaves the stream live preserves its representation invariant. The part of this that is proved is the safety goal of the entry.
First, how data changes hands in one call. next_in points to the start of the input not yet read,
and avail_in is the number of bytes readable from there. next_out points to the next writable
position, and avail_out is the output room that remains, also in bytes. One call may consume only
part of the input and deliver only part of the output. Read the updated pointers and counts, take
the bytes delivered, then give the same stream more input or more output room.
- Live stream: a writable
z_streamwith a compressor state established by successful init or copy, preserved by legal calls, and not ended. The caller does not alter its internal state or allocator fields. Calls on one stream are sequential. - Buffers: input covers
avail_inreadable bytes; output coversavail_outwritable bytes. They do not overlap each other, the stream or its owned state. A non-NULL scalar result points to a writable cell separate from other results and stream memory. These separation conditions are assumptions of the contracts. Where a safety goal assumes one too, its Proof goals says so and deviations has a row. - Allocator: the default allocator/free pair is used, or both fields are NULL before init. Allocation may fail on any attempt. Custom allocator callbacks are outside this page's scope.
- Frame and ownership: calls change only their stream, its owned state and stated
output regions. Caller input is read-only. Caller buffers and header records remain caller-owned.
Only init and copy allocate; only their failure cleanup and
deflateEndfree memory. Other calls preserve the stream's allocation set. - Header lifetime: a retained gzip header and its optional fields remain readable and
unchanged while used. Non-NULL
nameandcommenthave a terminating zero;extracovers its stated length. The contracts on this page takeextra_len <= 65535. - Checked refusals: except for init and bounds, a failed stream check returns
Z_STREAM_ERRORbefore normal operation, without writes.deflateCopyadditionally clears a non-NULL destination state. Query output cells are untouched on this refusal. - Restricted domain means these explicit memory, lifetime and call-order conditions, plus the entry's Pre. It does not mean every representable pointer or integer is accepted. Error summaries cover stream records and states that the checks can read, not arbitrary invalid addresses.
- Reachable stream: the proof goals speak of a reachable stream where the contracts say live
stream (how to read a contract). A call that a goal covers extends the stream's
history: when it returns, with any code, the stream is reachable again and the goal of the next
call applies.
deflateEndends the history. - Result cells as values:
deflateGetDictionary,deflatePendinganddeflateUsedreport results through pointers (uInt *dictLength,unsigned *pending,int *bits). The translation does not model these cells as memory: each function takes only the fact that a pointer is NULL or not, and returns the values. So the goals say nothing about the address of a result cell, and a cell that overlaps another object cannot be expressed.
Safety goal
ZlibF.Spec.Public.Goal.deflateInit2__safety
State: done · Status of the results
/-- `int deflateInit2_(z_streamp strm, int level, int method, int windowBits, int memLevel,
int strategy, const char *version, int stream_size)`.
**Safety of `deflateInit2_`** (macro `deflateInit2`): for every level, method, window, memory
level and strategy, every `stream_size` and every allocation outcome, on `InitArguments` the
call is safe (`InitResultSafe`). -/
def Goal.deflateInit2__safety : Prop :=
∀ h strm version size level method wb mem strategy, InitArguments h strm version →
∃ rc after, C.run (Zlib.Deflate.deflateInit2_ strm level method wb mem strategy version size) h =
.ok (rc, after) ∧ InitResultSafe .deflate h after strm rcRelated definitions and source ↗Functional contract (beyond safety)
ZlibF.Spec.Public.Goal.deflateInit2_
State: done · Status of the results
/-- `int deflateInit2_(z_streamp strm, int level, int method, int windowBits, int memLevel,
int strategy, const char *version, int stream_size)`.
Every signed argument, source-ordered refusal, five allocations, failure cleanup and success invariant. -/
def Goal.deflateInit2_ : Prop :=
∀ level method wb mem strategy,
DeflateInitContract (fun p v size => Zlib.Deflate.deflateInit2_ p level method wb mem strategy v size)
level method wb mem strategyRelated definitions and source ↗