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
//! ZEX encoder — native algorithm + optional AEAD encryption.
//!
//! Pipeline:
//! 1. Build [`ZexHeader`]
//! 2. Compress blocks with [`crate::algorithms::zex_native`]
//! 3. End + optional CRC over **plaintext**
//! 4. If encryption key set → ChaCha20-Poly1305 seal of body

use alloc::vec::Vec;

use crate::Result;
use crate::algorithms::{turbo, zex_native};
use crate::core::dictionary::Dictionary;
use crate::format::block::{BlockHeader, BlockType};
use crate::format::header::{
    CompressionMode, DEFAULT_BLOCK_SIZE, HEADER_SIZE, HeaderFlags, ZexHeader,
};
use crate::utils::crc::crc32;
use crate::utils::security::SecurityPolicy;
#[cfg(feature = "std")]
use rayon::prelude::*;
#[cfg(feature = "std")]
use std::io::Write;

#[cfg(feature = "encryption")]
use crate::crypto::{
    EncryptionKey, NONCE_LEN, SALT_LEN, derive_key_from_password, encrypt_body, fill_random,
};

/// Compression options (library API).
#[derive(Debug, Clone)]
pub struct CompressOptions {
    /// Profile: turbo / balanced / max.
    pub mode: CompressionMode,
    /// Level 1–22.
    pub level: u8,
    /// Max uncompressed block size.
    pub block_size: u32,
    /// CRC32 over plaintext (default true).
    pub checksum: bool,
    /// Compress blocks in parallel.
    pub threads: bool,
    /// Independent blocks.
    pub independent: bool,
    /// Optional dictionary.
    pub dictionary: Option<Dictionary>,
    /// Security policy.
    pub security: SecurityPolicy,
    /// Optional AEAD key (feature `encryption`).
    #[cfg(feature = "encryption")]
    pub encryption: Option<EncryptionKey>,
}

impl Default for CompressOptions {
    fn default() -> Self {
        Self {
            mode: CompressionMode::Balanced,
            level: 3,
            block_size: DEFAULT_BLOCK_SIZE,
            checksum: true,
            threads: true,
            independent: true,
            dictionary: None,
            security: SecurityPolicy::default(),
            #[cfg(feature = "encryption")]
            encryption: None,
        }
    }
}

impl CompressOptions {
    /// Builder: profile.
    pub fn mode(mut self, mode: CompressionMode) -> Self {
        self.mode = mode;
        self
    }
    /// Builder: level 1–22.
    pub fn level(mut self, level: u8) -> Self {
        self.level = level.clamp(1, 22);
        self
    }
    /// Builder: block size.
    pub fn block_size(mut self, size: u32) -> Self {
        self.block_size = size.clamp(1024, 16 * 1024 * 1024);
        self
    }
    /// Builder: checksum.
    pub fn checksum(mut self, on: bool) -> Self {
        self.checksum = on;
        self
    }
    /// Builder: threads.
    pub fn threads(mut self, on: bool) -> Self {
        self.threads = on;
        self
    }
    /// Builder: dictionary.
    pub fn dictionary(mut self, dict: Dictionary) -> Self {
        self.dictionary = Some(dict);
        self
    }
    /// Builder: strict security.
    pub fn secure(mut self) -> Self {
        self.security = SecurityPolicy::strict();
        self.checksum = true;
        self.independent = true;
        self
    }

    /// Builder: encrypt with key/password (`encryption` feature).
    #[cfg(feature = "encryption")]
    pub fn encrypt(mut self, key: EncryptionKey) -> Self {
        self.encryption = Some(key);
        self
    }
}

/// Streaming / reusable encoder.
pub struct Encoder {
    opts: CompressOptions,
}

impl Encoder {
    /// Create with options.
    pub fn new(opts: CompressOptions) -> Self {
        Self { opts }
    }

    /// Compress full buffer → `.zex` bytes — `no_std`-safe, no I/O trait
    /// needed.
    pub fn compress(&self, src: &[u8]) -> Result<Vec<u8>> {
        let mut out = Vec::with_capacity(src.len() / 2 + HEADER_SIZE + 64);
        self.compress_into(src, &mut out)?;
        Ok(out)
    }

    /// Compress and write to any `Write` (`std`-only convenience — the
    /// `no_std` core path always builds a `Vec<u8>`; see [`Self::compress`]).
    #[cfg(feature = "std")]
    pub fn compress_to_writer<W: Write>(&self, src: &[u8], out: &mut W) -> Result<()> {
        out.write_all(&self.compress(src)?)?;
        Ok(())
    }

    fn compress_into(&self, src: &[u8], out: &mut Vec<u8>) -> Result<()> {
        let opts = &self.opts;
        let level = opts.mode.effective_level(opts.level);
        let block_size = (opts.block_size as usize).min(opts.security.max_block_uncompressed);

        let mut header = ZexHeader::new(src.len() as u64, opts.mode, level);
        header.block_size = block_size as u32;
        header.flags.set(HeaderFlags::CHECKSUM, opts.checksum);
        header.flags.set(HeaderFlags::INDEPENDENT, opts.independent);
        header.flags.set(
            HeaderFlags::MULTITHREAD,
            opts.threads && src.len() > block_size,
        );
        header.flags.set(
            HeaderFlags::SECURE,
            opts.security.max_output <= 512 * 1024 * 1024,
        );
        if let Some(ref d) = opts.dictionary {
            header.dictionary_id = d.id;
            header.flags.insert(HeaderFlags::DICTIONARY);
        }

        #[cfg(feature = "encryption")]
        let want_enc = opts.encryption.is_some();
        #[cfg(not(feature = "encryption"))]
        let want_enc = false;

        if want_enc {
            header.flags.insert(HeaderFlags::ENCRYPTED);
        }

        // Build plaintext body (blocks + end + crc)
        let mut body = Vec::with_capacity(src.len() / 2 + 128);
        let chunks: Vec<&[u8]> = if src.is_empty() {
            vec![src]
        } else {
            src.chunks(block_size).collect()
        };

        let dict_bytes: Option<&[u8]> = opts.dictionary.as_ref().map(|d| d.data.as_slice());

        #[cfg(feature = "std")]
        let compressed: Vec<(BlockType, Vec<u8>, u32)> = if opts.threads && chunks.len() > 1 {
            chunks
                .par_iter()
                .map(|chunk| compress_one_block(chunk, level, dict_bytes))
                .collect::<Result<Vec<_>>>()?
        } else {
            chunks
                .iter()
                .map(|chunk| compress_one_block(chunk, level, dict_bytes))
                .collect::<Result<Vec<_>>>()?
        };
        // `no_std`: always sequential — no thread pool available.
        #[cfg(not(feature = "std"))]
        let compressed: Vec<(BlockType, Vec<u8>, u32)> = chunks
            .iter()
            .map(|chunk| compress_one_block(chunk, level, dict_bytes))
            .collect::<Result<Vec<_>>>()?;

        for (ty, payload, unc) in compressed {
            opts.security.check_block(payload.len(), unc as usize)?;
            let bh = BlockHeader {
                block_type: ty,
                uncompressed_size: unc,
                compressed_size: payload.len() as u32,
            };
            body.extend_from_slice(&bh.to_bytes());
            body.extend_from_slice(&payload);
        }
        body.extend_from_slice(&BlockHeader::end().to_bytes());
        if opts.checksum {
            body.extend_from_slice(&crc32(src).to_le_bytes());
        }

        out.extend_from_slice(&header.to_bytes());

        #[cfg(feature = "encryption")]
        if let Some(ref ek) = opts.encryption {
            let mut salt = [0u8; SALT_LEN];
            let mut nonce = [0u8; NONCE_LEN];
            fill_random(&mut salt)?;
            fill_random(&mut nonce)?;

            let key = match ek {
                EncryptionKey::Raw(k) => {
                    salt = [0u8; SALT_LEN]; // mark raw-key mode
                    *k
                }
                EncryptionKey::Password(pw) => derive_key_from_password(pw, &salt)?,
            };

            let ct = encrypt_body(&key, &nonce, &body)?;
            out.extend_from_slice(&salt);
            out.extend_from_slice(&nonce);
            out.extend_from_slice(&ct);
            return Ok(());
        }

        let _ = want_enc;
        out.extend_from_slice(&body);
        Ok(())
    }
}

fn compress_one_block(
    chunk: &[u8],
    level: u8,
    dict: Option<&[u8]>,
) -> Result<(BlockType, Vec<u8>, u32)> {
    let unc = chunk.len() as u32;
    if chunk.is_empty() {
        return Ok((BlockType::Raw, Vec::new(), 0));
    }
    // With a dictionary even tiny blocks can shrink via history matches.
    if chunk.len() < 16 && dict.is_none() {
        return Ok((BlockType::Raw, chunk.to_vec(), unc));
    }

    // Turbo path: skip analysis on high-entropy data; use specialized encoder
    if turbo::should_use_turbo(level) && dict.is_none() && turbo::looks_incompressible(chunk) {
        return Ok((BlockType::Raw, chunk.to_vec(), unc));
    }

    let payload = if turbo::should_use_turbo(level) {
        let mut buf = Vec::with_capacity(chunk.len() / 2 + 32);
        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(), unc))
    } else {
        Ok((BlockType::Zex, payload, unc))
    }
}

/// One-shot compress.
pub fn compress(src: &[u8], opts: &CompressOptions) -> Result<Vec<u8>> {
    Encoder::new(opts.clone()).compress(src)
}

/// Compress with dictionary.
pub fn compress_with_dict(src: &[u8], opts: &CompressOptions, dict: Dictionary) -> Result<Vec<u8>> {
    let mut o = opts.clone();
    o.dictionary = Some(dict);
    Encoder::new(o).compress(src)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::decoder::{DecompressOptions, decompress, decompress_with_options};
    use crate::core::dictionary::Dictionary;

    #[test]
    fn encode_decode_native() {
        let src = b"ZEX native encoder roundtrip. ".repeat(500);
        let opts = CompressOptions::default()
            .mode(CompressionMode::Balanced)
            .level(3);
        let c = compress(&src, &opts).unwrap();
        assert_eq!(&c[..4], b"ZEX1");
        let d = decompress(&c).unwrap();
        assert_eq!(d, src);
    }

    #[test]
    fn profiles_roundtrip() {
        let src = b"ABCDEFGHIJ".repeat(1000);
        for mode in [
            CompressionMode::Turbo,
            CompressionMode::Balanced,
            CompressionMode::Max,
        ] {
            let opts = CompressOptions::default()
                .mode(mode)
                .level(5)
                .threads(false);
            let c = compress(&src, &opts).unwrap();
            let d = decompress(&c).unwrap();
            assert_eq!(d, src, "mode {mode}");
        }
    }

    #[test]
    fn empty_input() {
        let c = compress(b"", &CompressOptions::default()).unwrap();
        let d = decompress(&c).unwrap();
        assert!(d.is_empty());
    }

    #[test]
    fn secure_preset() {
        let src = b"secure mode data ".repeat(100);
        let c = compress(&src, &CompressOptions::default().secure()).unwrap();
        assert_eq!(decompress(&c).unwrap(), src);
    }

    #[test]
    fn dictionary_history_frame_roundtrip() {
        let dict = Dictionary::from_bytes(
            b"SHARED-PREFIX-HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n".to_vec(),
        )
        .unwrap();
        let msg =
            b"SHARED-PREFIX-HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nhello dict history";

        let without = compress(msg, &CompressOptions::default().level(6).threads(false)).unwrap();
        let with = compress(
            msg,
            &CompressOptions::default()
                .level(6)
                .threads(false)
                .dictionary(dict.clone()),
        )
        .unwrap();
        assert!(
            with.len() <= without.len(),
            "dict frame {} vs plain {}",
            with.len(),
            without.len()
        );

        let h = ZexHeader::from_bytes(&with).unwrap();
        assert_eq!(h.dictionary_id, dict.id);
        assert!(h.flags.contains(HeaderFlags::DICTIONARY));

        let d = decompress_with_options(
            &with,
            &DecompressOptions {
                dictionary: Some(dict),
                ..Default::default()
            },
        )
        .unwrap();
        assert_eq!(d, msg);
    }

    #[cfg(feature = "encryption")]
    #[test]
    fn encrypt_password_roundtrip() {
        let src = b"top secret payload for ZEX AEAD test!!!!".repeat(20);
        let opts = CompressOptions::default()
            .level(4)
            .encrypt(EncryptionKey::Password("hunter2".into()));
        let c = compress(&src, &opts).unwrap();
        let h = ZexHeader::from_bytes(&c).unwrap();
        assert!(h.is_encrypted());

        let dopts = DecompressOptions {
            encryption: Some(EncryptionKey::Password("hunter2".into())),
            ..Default::default()
        };
        let d = decompress_with_options(&c, &dopts).unwrap();
        assert_eq!(d, src);

        let bad = DecompressOptions {
            encryption: Some(EncryptionKey::Password("wrong".into())),
            ..Default::default()
        };
        assert!(decompress_with_options(&c, &bad).is_err());
    }
}