deflateCopy
Create an independent compressor with the same compression progress.
Full chapter and shared rules ↗int ZEXPORT deflateCopy(z_streamp dest, z_streamp source);
Create an independent compressor with the same compression progress.
Return values and next calls
Return type. int — zlib status code
The result says whether the destination gained independent compression state. Failure cleanup covers this call’s new allocations and leaves the source unchanged.
deflateCopy()| Returned value | Meaning and conditions | Caller’s next step |
|---|---|---|
Z_OKIndependent state copied |
The source is live and the destination satisfies the distinct empty-record preconditions; the destination gains five allocations and equivalent progress with relocated internal pointers, while the source is unchanged. | Each stream needs its own deflateEnd; assign separate output room before continuing both. Copied I/O pointers initially coincide and the retained header remains shared caller-owned storage. |
Z_MEM_ERRORAllocation failed and cleaned up |
Any new allocation fails; every new block is released, dest->state is cleared, other destination fields and the source are unchanged, and no new live destination exists. | Do not end the failed destination; after addressing memory pressure, retry under copy preconditions. The source can continue legally or end. |
Z_STREAM_ERRORNull destination |
dest is NULL and copying does not begin. | Provide a writable destination distinct from the source and owning no state, then follow the copy preconditions. |
Z_STREAM_ERRORSource check failed |
The destination is non-NULL but the source check fails; dest->state is cleared and no copy allocations occur. | Establish a live source and use only a distinct destination owning no state; this result does not mean any arbitrary preexisting destination state was freed. |
Calling conditions and effects
Domain Restricted domain. Effect: allocate and copy owned state.
Pre source is live. dest is a different writable z_stream with no owned state,
separate from the source's memory. Source buffers and any retained header satisfy their lifetimes.
Proof goals.
- Goal.
Goal.deflateCopy_safety(Safety/Copy.lean); required. Theorem:Zlib.Deflate.Universal.deflate_copy_safety(public-deflate-copy.lean). The goal has four clauses: the refusal of a NULLdest; the refusal of a NULLsource; the copy from a reachable source (the main clause); the refusal of asourcethat is a refused stream.Goal.deflate_refusal(Safety/Refusals.lean), also required, states the refusal of a refused source too. - Applies when. The refusal of a NULL
desthas no condition. The refusal of a NULLsourceasks thatdestpoints to a readable stream record. The refusal of a refusedsourceasks thatdestpoints to a readable stream record, and thatsourceis not NULL and is a refused stream (RefusedDeflate); it does not ask thatdestandsourcediffer. The main clause asks:sourceis a reachable stream (StreamReachable). The statement also takes its invariant and default allocator as hypotheses (DGood,DefAlloc); every reachable stream has them (Goal.deflate_sequence_safety, first clause);destpoints to a readable stream record that is not thesourcerecord (source ≠ dest). The platform size bound is not asked.
- Covered without condition. Every content of the
destrecord; every allocation outcome. In the refusals: every content of thedestrecord, every refusedsource, and, whendestis NULL, everysourcepointer. Ifdestwas a live stream, its old state stays allocated and the record no longer points to it. - Guarantees.
- Returns. With a NULL
dest, a NULLsourceor a refusedsource, the call returnsZ_STREAM_ERROR. From a reachable source the call returns, withZ_OKorZ_MEM_ERROR.Z_MEM_ERRORis returned only after an allocation failed (AllocationFailed). - State. From a reachable source: the
sourcerecord and its state are unchanged. WithZ_OK,destsatisfies the stream invariant (StreamInvariant), and is a reachable stream by the definition ofStreamReachable. WithZ_MEM_ERROR,dest->stateis NULL and the other fields ofdestare unchanged. - Writes. With a NULL
dest, nothing: the heap is unchanged. With a NULL or refusedsource, onlydest->state, which is set to NULL; the other fields ofdestand the rest of the heap are unchanged. From a reachable source, only thedestrecord and blocks the call itself allocates. - Allocations. In the three refusals nothing is allocated and nothing is freed. From a reachable source: with
Z_OK, the new blocks are exactly five: the new state record and its four buffers (window,prev,head,pending_buf). Nothing is freed. The safety goal does not say thatdest->statepoints to this record; the functional goalGoal.deflateCopydoes. WithZ_MEM_ERRORthe allocated blocks are the same as before the call.
- Returns. With a NULL
- Not in this goal. A
sourcerecord withzallocandzfreeset whosestateis a garbage pointer, points to a freed state, or points to an inflate state: no goal covers a copy from such a source (deviations).dest == sourcewith a reachable source: the Czmemcpy(dest, source, sizeof(z_stream))then copies the record onto itself, which is undefined behaviour, and no goal covers this call (deviations, row "Copy destination"). What the copy contains: functional goalGoal.deflateCopy(not planned; a theorem proves it).
Complete return conditions and boundaries
Post Z_OK gives dest five new owned allocations containing equivalent compression
state; the source is unchanged. The copied stream fields include totals, allocator fields,
I/O pointers and retained header pointer. Internal owned pointers are relocated to the new
allocations. Both streams require their own deflateEnd and can continue independently.
Their copied caller I/O pointers initially refer to the same buffers; assign separate output
room before continuing both. The header remains shared caller-owned storage.
Z_MEM_ERROR frees every new allocation, clears dest->state and leaves other destination
fields and the source unchanged. There is no new live state to release.
Outside focused scope: NULL destination gives Z_STREAM_ERROR; a failed source check
also clears a non-NULL destination's state. The functional goal Goal.deflateCopy has the
same source ≠ dest premise for a reachable source.
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.deflateCopy_safety
State: done · Status of the results
/-- **Safety of `deflateCopy`** (the safety content of `Goal.deflateCopy`). Null arguments are
refused. From every reachable source (`StreamInvariant .deflate` is `DGood` with the default
allocator) into a distinct, readable destination record, the call returns without a fault, with
`Z_OK` or `Z_MEM_ERROR`. It leaves the source record and its state unchanged and writes only the
destination record and new blocks. On `Z_MEM_ERROR` an allocation really failed, the destination
state is cleared and the live blocks are unchanged (no leak). On `Z_OK` the destination satisfies
the stream invariant (`StreamInvariant .deflate`, written out) and the live blocks grow by exactly the five new blocks it owns. The copied
contents (`copiedDeflate` and the prefix clauses) are left to `Goal.deflateCopy`. The last clause is
zlib.h's refusal of an inconsistent source ("such as zalloc being Z_NULL"): a source the state check
refuses (`RefusedDeflate`: a null `zalloc` or `zfree`, no state, or a live state with a wrong back
pointer or status) is refused with `Z_STREAM_ERROR`, and the destination state is cleared. -/
def Goal.deflateCopy_safety : Prop :=
(∀ h source, C.run (Zlib.Deflate.deflateCopy none source) h = .ok (Z_STREAM_ERROR, h)) ∧
(∀ h dest z, dest.get h = some z →
C.run (Zlib.Deflate.deflateCopy (some dest) none) h =
.ok (Z_STREAM_ERROR, dest.put h { z with state := none })) ∧
(∀ h source i z s dest oldDest,
StreamReachable .deflate h source → Zlib.Deflate.Spec.DGood h source i z s →
Zlib.Deflate.Spec.DefAlloc z → source ≠ dest → dest.get h = some oldDest →
∃ rc after,
C.run (Zlib.Deflate.deflateCopy (some dest) (some source)) h = .ok (rc, after) ∧
source.get after = some z ∧ after.dstates i = some s ∧ Frame h after (StreamRoot dest) ∧
((rc = Z_MEM_ERROR ∧ AllocationFailed h after ∧
dest.get after = some { oldDest with state := none } ∧
LiveChange h after (fun _ => False) (fun _ => False)) ∨
(rc = Z_OK ∧ (∃ i' z' s', Zlib.Deflate.Spec.DGood after dest i' z' s' ∧ Zlib.Deflate.Spec.DefAlloc z') ∧
∃ copied,
after.dstates h.nextBlk = some copied ∧
(∀ b, DeflateOwned h.nextBlk copied b ↔ h.nextBlk ≤ b ∧ b < h.nextBlk + 5) ∧
LiveChange h after (DeflateOwned h.nextBlk copied) (fun _ => False)))) ∧
(∀ h source dest oldDest, dest.get h = some oldDest → RefusedDeflate h (some source) →
C.run (Zlib.Deflate.deflateCopy (some dest) (some source)) h =
.ok (Z_STREAM_ERROR, dest.put h { oldDest with state := none }))Related definitions and source ↗Functional contract (beyond safety)
ZlibF.Spec.Public.Goal.deflateCopy
State: done · Status of the results
/-- `int deflateCopy(z_streamp dest, z_streamp source)`.
Copy the initialized window, hash entries, pending bytes and symbols. Relocate the owned
buffers and tree descriptors. A failure clears destination state and releases every new block. -/
def Goal.deflateCopy : Prop :=
(∀ h source, C.run (Zlib.Deflate.deflateCopy none source) h = .ok (Z_STREAM_ERROR, h)) ∧
(∀ h dest z, dest.get h = some z →
C.run (Zlib.Deflate.deflateCopy (some dest) none) h =
.ok (Z_STREAM_ERROR, dest.put h { z with state := none })) ∧
(∀ h source i z s dest oldDest,
StreamReachable .deflate h source → Zlib.Deflate.Spec.DGood h source i z s →
Zlib.Deflate.Spec.DefAlloc z → source ≠ dest → dest.get h = some oldDest →
∃ rc after,
C.run (Zlib.Deflate.deflateCopy (some dest) (some source)) h = .ok (rc, after) ∧
source.get after = some z ∧ after.dstates i = some s ∧ Frame h after (StreamRoot dest) ∧
((rc = Z_MEM_ERROR ∧ AllocationFailed h after ∧
dest.get after = some { oldDest with state := none } ∧
LiveChange h after (fun _ => False) (fun _ => False)) ∨
(rc = Z_OK ∧ ∃ copied,
Zlib.Deflate.Spec.DGood after dest h.nextBlk
{ z with state := some (.deflate h.nextBlk) } copied ∧
copied = copiedDeflate dest h.nextBlk s copied ∧
SameBytePrefix h after s.window copied.window s.high_water.toNat ∧
SameWordPrefix h after s.head copied.head s.hash_size.toNat ∧
SameWordPrefix h after s.prev copied.prev
(if s.slid ≠ 0 ∨ s.strstart - s.insert > s.w_size then s.w_size.toNat
else (s.strstart - s.insert).toNat) ∧
SameBytePrefix h after s.pending_out copied.pending_out s.pending.toNat ∧
SameBytePrefix h after s.sym_buf copied.sym_buf s.sym_next.toNat ∧
(∀ b, DeflateOwned h.nextBlk copied b ↔ h.nextBlk ≤ b ∧ b < h.nextBlk + 5) ∧
LiveChange h after (DeflateOwned h.nextBlk copied) (fun _ => False))))Related definitions and source ↗