zexc 1.2.1

zex native lossless compressor — CLI zexc, library zexc, files *.zex
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
//! Streaming compress / decompress (`std::io::Write` / `Read`).
//!
//! ## Encoder
//!
//! ```ignore
//! use std::io::Write;
//! use zexc::{StreamEncoder, CompressOptions};
//!
//! let file = std::fs::File::create("out.zex")?;
//! let mut enc = StreamEncoder::new(file, CompressOptions::default());
//! enc.write_all(b"chunk 1")?;
//! enc.write_all(b"chunk 2")?;
//! let file = enc.finish()?; // writes End + CRC, returns inner writer
//! ```
//!
//! ## Decoder
//!
//! ```ignore
//! use std::io::Read;
//! use zexc::StreamDecoder;
//!
//! let file = std::fs::File::open("out.zex")?;
//! let mut dec = StreamDecoder::new(file);
//! let mut out = Vec::new();
//! dec.read_to_end(&mut out)?;
//! ```
//!
//! ## Limits
//!
//! - **Independent blocks** only (safe, MT-friendly).
//! - **Content size** is written as unknown (`u64::MAX`) — true streaming.
//! - **Encryption** is not supported on the stream path (AEAD needs the full
//!   body). Use one-shot [`crate::compress`] with a key for encrypted frames.
//! - Checksum (CRC32) is computed over all plaintext written/read.

use crate::algorithms::zex_native;
use crate::format::block::{BlockHeader, BlockType};
use crate::format::header::{HEADER_SIZE, HeaderFlags, ZexHeader};
use crate::utils::crc::Crc32;
use crate::utils::security::SecurityPolicy;
use crate::{Error, Result};
use std::io::{self, Read, Write};

use super::encoder::CompressOptions;

// ─── Shared block helper ─────────────────────────────────────────────────────

fn encode_block(chunk: &[u8], level: u8, dict: Option<&[u8]>) -> Result<(BlockType, Vec<u8>)> {
    use crate::algorithms::turbo;
    if chunk.is_empty() {
        return Ok((BlockType::Raw, Vec::new()));
    }
    if chunk.len() < 16 && dict.is_none() {
        return Ok((BlockType::Raw, chunk.to_vec()));
    }
    if turbo::should_use_turbo(level) && dict.is_none() && turbo::looks_incompressible(chunk) {
        return Ok((BlockType::Raw, chunk.to_vec()));
    }
    let payload = if turbo::should_use_turbo(level) {
        let mut buf = Vec::new();
        turbo::compress_into_level(chunk, &mut buf, dict, level)?;
        buf
    } else {
        zex_native::compress_with_history(chunk, level, dict)?
    };
    if payload.len() >= chunk.len() {
        Ok((BlockType::Raw, chunk.to_vec()))
    } else {
        Ok((BlockType::Zex, payload))
    }
}

fn write_block<W: Write>(out: &mut W, ty: BlockType, unc: u32, payload: &[u8]) -> Result<()> {
    let bh = BlockHeader {
        block_type: ty,
        uncompressed_size: unc,
        compressed_size: payload.len() as u32,
    };
    bh.write_to(out)?;
    out.write_all(payload)?;
    Ok(())
}

// ─── Stream encoder ──────────────────────────────────────────────────────────

/// Incremental compressor implementing [`Write`].
///
/// Call [`StreamEncoder::finish`] (not just `drop`) to emit the End block and CRC.
pub struct StreamEncoder<W: Write> {
    writer: Option<W>,
    opts: CompressOptions,
    level: u8,
    block_size: usize,
    /// Accumulates plain input until a full block.
    buf: Vec<u8>,
    header_written: bool,
    finished: bool,
    crc: Crc32,
    /// Bytes accepted from the user.
    pub bytes_in: u64,
    /// Compressed bytes written (approx, after header).
    pub bytes_out: u64,
}

impl<W: Write> StreamEncoder<W> {
    /// Create a streaming encoder writing a `.zex` frame to `writer`.
    ///
    /// Encryption in `opts` is **ignored** (see module docs).
    pub fn new(writer: W, opts: CompressOptions) -> Self {
        let level = opts.mode.effective_level(opts.level);
        let block_size = (opts.block_size as usize)
            .min(opts.security.max_block_uncompressed)
            .max(1024);
        Self {
            writer: Some(writer),
            opts,
            level,
            block_size,
            buf: Vec::with_capacity(block_size),
            header_written: false,
            finished: false,
            crc: Crc32::new(),
            bytes_in: 0,
            bytes_out: 0,
        }
    }

    /// Convenience with defaults.
    pub fn with_defaults(writer: W) -> Self {
        Self::new(writer, CompressOptions::default())
    }

    fn ensure_header(&mut self) -> io::Result<()> {
        if self.header_written {
            return Ok(());
        }
        let w = self
            .writer
            .as_mut()
            .ok_or_else(|| io::Error::other("encoder finished"))?;

        let mut header = ZexHeader::new(u64::MAX, self.opts.mode, self.level);
        header.block_size = self.block_size as u32;
        header.flags.set(HeaderFlags::CHECKSUM, self.opts.checksum);
        header.flags.set(HeaderFlags::INDEPENDENT, true);
        header.flags.set(HeaderFlags::CONTENT_SIZE, false);
        if let Some(ref d) = self.opts.dictionary {
            header.dictionary_id = d.id;
            header.flags.insert(HeaderFlags::DICTIONARY);
        }
        // Streaming never sets ENCRYPTED
        header.write_to(w).map_err(io::Error::other)?;
        self.bytes_out += HEADER_SIZE as u64;
        self.header_written = true;
        Ok(())
    }

    fn flush_full_blocks(&mut self) -> io::Result<()> {
        self.ensure_header()?;
        while self.buf.len() >= self.block_size {
            let chunk: Vec<u8> = self.buf.drain(..self.block_size).collect();
            self.emit_block(&chunk)?;
        }
        Ok(())
    }

    fn emit_block(&mut self, chunk: &[u8]) -> io::Result<()> {
        let w = self
            .writer
            .as_mut()
            .ok_or_else(|| io::Error::other("encoder finished"))?;
        let dict = self.opts.dictionary.as_ref().map(|d| d.data.as_slice());
        let (ty, payload) = encode_block(chunk, self.level, dict).map_err(io::Error::other)?;
        write_block(w, ty, chunk.len() as u32, &payload).map_err(io::Error::other)?;
        self.bytes_out += 9 + payload.len() as u64;
        Ok(())
    }

    /// Finish the frame: last partial block, End marker, optional CRC.
    /// Returns the inner writer.
    pub fn finish(mut self) -> Result<W> {
        if self.finished {
            return self
                .writer
                .take()
                .ok_or_else(|| Error::Compression("already finished".into()));
        }
        self.ensure_header().map_err(Error::Io)?;
        // Remaining buffer
        if !self.buf.is_empty() {
            let chunk = std::mem::take(&mut self.buf);
            self.emit_block(&chunk).map_err(Error::Io)?;
        } else if self.bytes_in == 0 {
            // Empty stream: one empty raw block for consistency
            self.emit_block(&[]).map_err(Error::Io)?;
        }

        let w = self
            .writer
            .as_mut()
            .ok_or_else(|| Error::Compression("encoder finished".into()))?;
        BlockHeader::end().write_to(w)?;
        self.bytes_out += 9;
        if self.opts.checksum {
            let c = self.crc.clone_finalize();
            w.write_all(&c.to_le_bytes())?;
            self.bytes_out += 4;
        }
        self.finished = true;
        self.writer
            .take()
            .ok_or_else(|| Error::Compression("encoder finished".into()))
    }

    /// Access options (read-only).
    pub fn options(&self) -> &CompressOptions {
        &self.opts
    }
}

impl<W: Write> Write for StreamEncoder<W> {
    fn write(&mut self, data: &[u8]) -> io::Result<usize> {
        if self.finished || self.writer.is_none() {
            return Err(io::Error::other("stream encoder already finished"));
        }
        if data.is_empty() {
            return Ok(0);
        }
        self.crc.update(data);
        self.bytes_in += data.len() as u64;
        self.buf.extend_from_slice(data);
        self.flush_full_blocks()?;
        Ok(data.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        // Only flush full blocks + underlying writer; keep partial block.
        self.flush_full_blocks()?;
        if let Some(w) = self.writer.as_mut() {
            w.flush()?;
        }
        Ok(())
    }
}

// ─── Stream decoder ──────────────────────────────────────────────────────────

/// Incremental decompressor implementing [`Read`].
pub struct StreamDecoder<R: Read> {
    reader: R,
    header: Option<ZexHeader>,
    /// Decompressed bytes ready for the user.
    out: Vec<u8>,
    out_pos: usize,
    finished: bool,
    crc: Crc32,
    verify_checksum: bool,
    security: SecurityPolicy,
    /// Dictionary history (required if frame has dictionary_id ≠ 0).
    dictionary: Option<crate::core::dictionary::Dictionary>,
    /// Expected CRC after End (if header says so).
    pending_crc_check: bool,
}

impl<R: Read> StreamDecoder<R> {
    /// Create over an input stream.
    pub fn new(reader: R) -> Self {
        Self {
            reader,
            header: None,
            out: Vec::new(),
            out_pos: 0,
            finished: false,
            crc: Crc32::new(),
            verify_checksum: true,
            security: SecurityPolicy::default(),
            dictionary: None,
            pending_crc_check: false,
        }
    }

    /// Builder-style: security policy.
    pub fn security(mut self, policy: SecurityPolicy) -> Self {
        self.security = policy;
        self
    }

    /// Builder-style: verify CRC.
    pub fn verify_checksum(mut self, on: bool) -> Self {
        self.verify_checksum = on;
        self
    }

    /// Builder-style: dictionary for history matches.
    pub fn dictionary(mut self, dict: crate::core::dictionary::Dictionary) -> Self {
        self.dictionary = Some(dict);
        self
    }

    /// Parsed header after the first read (if available).
    pub fn header(&self) -> Option<&ZexHeader> {
        self.header.as_ref()
    }

    fn ensure_header(&mut self) -> io::Result<()> {
        if self.header.is_some() {
            return Ok(());
        }
        let h = ZexHeader::read_from(&mut self.reader)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
        if h.is_encrypted() {
            return Err(io::Error::new(
                io::ErrorKind::Unsupported,
                "stream decode does not support encrypted frames; use one-shot decompress",
            ));
        }
        if h.dictionary_id != 0 {
            match &self.dictionary {
                None => {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        format!("frame needs dictionary id {:#x}", h.dictionary_id),
                    ));
                }
                Some(d) if d.id != h.dictionary_id => {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "dictionary id mismatch",
                    ));
                }
                Some(_) => {}
            }
        }
        self.security
            .check_frame_size(h.content_size)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
        self.pending_crc_check = h.has_checksum() && self.verify_checksum;
        self.header = Some(h);
        Ok(())
    }

    /// Pull one compressed block → `out` buffer.
    fn pull_block(&mut self) -> io::Result<bool> {
        if self.finished {
            return Ok(false);
        }
        self.ensure_header()?;

        let bh = BlockHeader::read_from(&mut self.reader)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;

        if bh.block_type == BlockType::End {
            if self.pending_crc_check {
                let mut crc_buf = [0u8; 4];
                self.reader.read_exact(&mut crc_buf)?;
                let expected = u32::from_le_bytes(crc_buf);
                let actual = self.crc.clone_finalize();
                if actual != expected {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        format!("checksum mismatch: expected 0x{expected:08x}, got 0x{actual:08x}"),
                    ));
                }
            }
            self.finished = true;
            return Ok(false);
        }

        self.security
            .check_block(bh.compressed_size as usize, bh.uncompressed_size as usize)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;

        let mut payload = vec![0u8; bh.compressed_size as usize];
        self.reader.read_exact(&mut payload)?;

        let unc = bh.uncompressed_size as usize;
        let plain = match bh.block_type {
            BlockType::Raw => {
                if payload.len() != unc {
                    return Err(io::Error::new(
                        io::ErrorKind::InvalidData,
                        "raw block size mismatch",
                    ));
                }
                payload
            }
            BlockType::Zex => {
                let dict = self
                    .dictionary
                    .as_ref()
                    .map(|d| d.data.as_slice())
                    .filter(|_| {
                        self.header
                            .as_ref()
                            .map(|h| h.dictionary_id != 0)
                            .unwrap_or(false)
                    });
                zex_native::decompress_with_history(&payload, unc, dict)
                    .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
            }
            BlockType::End => unreachable!(),
        };

        self.crc.update(&plain);
        // Compact out buffer
        if self.out_pos > 0 {
            self.out.drain(..self.out_pos);
            self.out_pos = 0;
        }
        self.out.extend_from_slice(&plain);
        Ok(true)
    }
}

impl<R: Read> Read for StreamDecoder<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if buf.is_empty() {
            return Ok(0);
        }
        loop {
            let available = self.out.len().saturating_sub(self.out_pos);
            if available > 0 {
                let n = available.min(buf.len());
                buf[..n].copy_from_slice(&self.out[self.out_pos..self.out_pos + n]);
                self.out_pos += n;
                return Ok(n);
            }
            if self.finished {
                return Ok(0);
            }
            if !self.pull_block()? {
                return Ok(0);
            }
        }
    }
}

// ─── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::decoder::decompress;
    use crate::format::header::CompressionMode;
    use std::io::{Cursor, Read, Write};

    #[test]
    fn stream_encode_decode_roundtrip() {
        let src = b"streaming ZEX test data! ".repeat(10_000);
        let mut sink = Vec::new();
        {
            let mut enc = StreamEncoder::new(
                &mut sink,
                CompressOptions::default()
                    .mode(CompressionMode::Balanced)
                    .level(3)
                    .block_size(16 * 1024),
            );
            // Write in odd chunks
            let mut off = 0;
            while off < src.len() {
                let n = (off % 97 + 1).min(src.len() - off);
                enc.write_all(&src[off..off + n]).unwrap();
                off += n;
            }
            enc.finish().unwrap();
        }
        assert_eq!(&sink[..4], b"ZEX1");

        // One-shot decode
        let d = decompress(&sink).unwrap();
        assert_eq!(d, src);

        // Stream decode
        let mut dec = StreamDecoder::new(Cursor::new(&sink));
        let mut out = Vec::new();
        dec.read_to_end(&mut out).unwrap();
        assert_eq!(out, src);
    }

    #[test]
    fn stream_empty() {
        let mut sink = Vec::new();
        let enc = StreamEncoder::with_defaults(&mut sink);
        enc.finish().unwrap();
        let d = decompress(&sink).unwrap();
        assert!(d.is_empty());
    }

    #[test]
    fn stream_small_writes() {
        let mut sink = Vec::new();
        {
            let mut enc = StreamEncoder::with_defaults(&mut sink);
            for b in b"hello stream" {
                enc.write_all(&[*b]).unwrap();
            }
            enc.finish().unwrap();
        }
        let mut out = Vec::new();
        StreamDecoder::new(Cursor::new(&sink))
            .read_to_end(&mut out)
            .unwrap();
        assert_eq!(out, b"hello stream");
    }
}