atlas-archive-core 1.1.0

High-performance compression library with adaptive context modeling (Loom) and .nyx archives
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
//! Poor-Compress Experimental Module
//!
//! Preprocessing transforms for hard-to-compress files:
//! - JPEG, MP3, encrypted, video
//! - Already-compressed data
//!
//! Experimental ideas:
//! - Delta coding between adjacent bytes/blocks
//! - Byte reordering (e.g., channel separation)
//! - Header detection and special handling

use alloc::vec;
use alloc::vec::Vec;

/// File type detection based on magic bytes
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum DetectedType {
    /// JPEG image (FFD8FF)
    Jpeg,
    /// PNG image (89504E47)
    Png,
    /// MP3 audio (ID3 or FFFB)
    Mp3,
    /// MP4/M4A video/audio (ftyp)
    Mp4,
    /// GIF image (GIF87a or GIF89a)
    Gif,
    /// Encrypted/random data (high entropy)
    Encrypted,
    /// ZIP archive
    Zip,
    /// PDF document (%PDF)
    Pdf,
    /// DOCX document (PK + [Content_Types].xml)
    Docx,
    /// Unknown/generic
    Unknown,
}

impl DetectedType {
    /// Detect file type from magic bytes
    pub fn detect(data: &[u8]) -> Self {
        if data.len() < 4 {
            return Self::Unknown;
        }

        // JPEG: FFD8FF
        if data[0] == 0xFF && data[1] == 0xD8 && data[2] == 0xFF {
            return Self::Jpeg;
        }

        // PNG: 89504E47
        if data[0..4] == [0x89, 0x50, 0x4E, 0x47] {
            return Self::Png;
        }

        // GIF: GIF87a or GIF89a
        if data.len() >= 6 && &data[0..6] == b"GIF87a"
            || (data.len() >= 6 && &data[0..6] == b"GIF89a")
        {
            return Self::Gif;
        }

        // MP3: ID3 or sync word
        if data[0..3] == [0x49, 0x44, 0x33] || (data[0] == 0xFF && (data[1] & 0xE0) == 0xE0) {
            return Self::Mp3;
        }

        // MP4: ftyp at offset 4
        if data.len() >= 8 && &data[4..8] == b"ftyp" {
            return Self::Mp4;
        }

        // ZIP: PK
        if data[0..2] == [0x50, 0x4B] {
            // Check for DOCX (OpenXML)
            if data.len() > 100
                && data[30..100]
                    .windows(19)
                    .any(|w| w == b"[Content_Types].xml")
            {
                return Self::Docx;
            }
            return Self::Zip;
        }

        // PDF: %PDF
        if data.len() >= 4 && &data[0..4] == b"%PDF" {
            return Self::Pdf;
        }

        // High entropy check (encrypted/random)
        if data.len() >= 512 {
            let entropy = Self::calculate_entropy(&data[..512]);
            if entropy > 7.9 {
                return Self::Encrypted;
            }
        } else if data.len() >= 64 {
            let entropy = Self::calculate_entropy(data);
            if entropy > 7.8 {
                return Self::Encrypted;
            }
        }

        Self::Unknown
    }

    /// Calculate Shannon entropy of data
    pub fn calculate_entropy(data: &[u8]) -> f64 {
        if data.is_empty() {
            return 0.0;
        }
        let mut counts = [0usize; 256];
        for &b in data {
            counts[b as usize] += 1;
        }
        let len = data.len() as f64;
        let mut entropy = 0.0;

        #[cfg(feature = "std")]
        {
            for &c in &counts {
                if c > 0 {
                    let p = c as f64 / len;
                    entropy -= p * p.log2();
                }
            }
        }
        #[cfg(not(feature = "std"))]
        {
            // Simple proxy for no_std: Fraction of unique bytes
            let unique = counts.iter().filter(|&&c| c > 0).count();
            entropy = (unique as f64 / 256.0) * 8.0;
        }
        entropy
    }
}

/// Delta coding transform: encode differences between adjacent bytes
pub struct DeltaTransform;

impl DeltaTransform {
    /// Apply delta coding: output[i] = input[i] - input[i-1]
    #[inline]
    pub fn encode(data: &[u8]) -> Vec<u8> {
        if data.is_empty() {
            return Vec::new();
        }
        let mut result = Vec::with_capacity(data.len());
        result.push(data[0]);
        // Use windows() for better optimizer visibility
        for w in data.windows(2) {
            result.push(w[1].wrapping_sub(w[0]));
        }
        result
    }

    /// Reverse delta coding
    #[inline]
    pub fn decode(data: &[u8]) -> Vec<u8> {
        if data.is_empty() {
            return Vec::new();
        }
        let mut result = Vec::with_capacity(data.len());
        result.push(data[0]);
        let mut prev = data[0];
        for &b in &data[1..] {
            prev = b.wrapping_add(prev);
            result.push(prev);
        }
        result
    }
}

/// Predictive Delta: assumes constant velocity (d2 = d1)
pub struct PredictiveDelta;

impl PredictiveDelta {
    #[inline]
    pub fn encode(data: &[u8]) -> Vec<u8> {
        if data.len() < 2 {
            return data.to_vec();
        }
        let mut result = Vec::with_capacity(data.len());
        result.push(data[0]);
        result.push(data[1].wrapping_sub(data[0]));
        // Optimization: loop lifting
        for i in 2..data.len() {
            let pred = data[i - 1].wrapping_add(data[i - 1].wrapping_sub(data[i - 2]));
            result.push(data[i].wrapping_sub(pred));
        }
        result
    }

    #[inline]
    pub fn decode(data: &[u8]) -> Vec<u8> {
        if data.len() < 2 {
            return data.to_vec();
        }
        let mut result = Vec::with_capacity(data.len());
        result.push(data[0]);
        result.push(data[1].wrapping_add(data[0]));
        for i in 2..data.len() {
            let pred = result[i - 1].wrapping_add(result[i - 1].wrapping_sub(result[i - 2]));
            result.push(data[i].wrapping_add(pred));
        }
        result
    }
}

/// Block-based delta: delta between N-byte blocks
pub struct BlockDeltaTransform {
    pub block_size: usize,
}

impl BlockDeltaTransform {
    pub fn new(block_size: usize) -> Self {
        Self {
            block_size: block_size.max(1),
        }
    }

    /// Encode with block-based delta
    pub fn encode(&self, data: &[u8]) -> Vec<u8> {
        if data.len() <= self.block_size {
            return data.to_vec();
        }
        let mut result = Vec::with_capacity(data.len());
        // First block unchanged
        result.extend_from_slice(&data[..self.block_size]);
        // Delta for subsequent blocks
        for i in self.block_size..data.len() {
            result.push(data[i].wrapping_sub(data[i - self.block_size]));
        }
        result
    }

    /// Decode block-based delta
    pub fn decode(&self, data: &[u8]) -> Vec<u8> {
        if data.len() <= self.block_size {
            return data.to_vec();
        }
        let mut result = Vec::with_capacity(data.len());
        result.extend_from_slice(&data[..self.block_size]);
        for i in self.block_size..data.len() {
            result.push(data[i].wrapping_add(result[i - self.block_size]));
        }
        result
    }
}

/// Channel separation: reorder bytes to group similar values
/// Useful for multi-channel data (e.g., RGB, stereo audio)
pub struct ChannelSeparator {
    pub channels: usize,
}

impl ChannelSeparator {
    pub fn new(channels: usize) -> Self {
        Self {
            channels: channels.max(1),
        }
    }

    /// YUV-style separation for 3-channel data: (Y, U, V)
    /// Y = (R + 2G + B) / 4 (approx)
    pub fn separate_yuv(&self, data: &[u8]) -> Vec<u8> {
        if self.channels != 3 || data.len() % 3 != 0 {
            return self.separate(data);
        }
        let n = data.len() / 3;
        let mut result = vec![0u8; data.len()];
        for i in 0..n {
            let r = data[i * 3] as i32;
            let g = data[i * 3 + 1] as i32;
            let b = data[i * 3 + 2] as i32;
            // Simple integer YUV
            let y = (r + 2 * g + b) / 4;
            let u = r - g;
            let v = b - g;
            result[i] = y as u8;
            result[i + n] = (u + 128) as u8;
            result[i + 2 * n] = (v + 128) as u8;
        }
        result
    }

    pub fn interleave_yuv(&self, data: &[u8]) -> Vec<u8> {
        if self.channels != 3 || data.len() % 3 != 0 {
            return self.interleave(data);
        }
        let n = data.len() / 3;
        let mut result = vec![0u8; data.len()];
        for i in 0..n {
            let y = data[i] as i32;
            let u = data[i + n] as i32 - 128;
            let v = data[i + 2 * n] as i32 - 128;
            let g = y - (u + v) / 4;
            let r = u + g;
            let b = v + g;
            result[i * 3] = r.clamp(0, 255) as u8;
            result[i * 3 + 1] = g.clamp(0, 255) as u8;
            result[i * 3 + 2] = b.clamp(0, 255) as u8;
        }
        result
    }

    /// Separate interleaved channels: RGBRGBRGB -> RRRGGGBBB
    pub fn separate(&self, data: &[u8]) -> Vec<u8> {
        let len = data.len();
        if len == 0 {
            return Vec::new();
        }
        let mut result = Vec::with_capacity(len);

        for ch in 0..self.channels {
            for i in (ch..len).step_by(self.channels) {
                result.push(data[i]);
            }
        }

        result
    }

    /// Interleave separated channels: RRRGGGBBB -> RGBRGBRGB
    pub fn interleave(&self, data: &[u8]) -> Vec<u8> {
        let len = data.len();
        if len == 0 {
            return Vec::new();
        }

        let mut result = vec![0u8; len];
        let mut in_idx = 0;

        // The first 'len % channels' channels have (len / channels) + 1 bytes.
        // The rest have (len / channels) bytes.
        let base_chunk = len / self.channels;
        let rem = len % self.channels;

        for ch in 0..self.channels {
            let chunk_len = if ch < rem { base_chunk + 1 } else { base_chunk };
            for i in 0..chunk_len {
                let out_idx = i * self.channels + ch;
                if out_idx < len && in_idx < len {
                    result[out_idx] = data[in_idx];
                    in_idx += 1;
                }
            }
        }

        result
    }
}

/// Experimental: XOR with previous block (reduces patterns)
pub struct XorDeltaTransform {
    pub block_size: usize,
}

impl XorDeltaTransform {
    pub fn new(block_size: usize) -> Self {
        Self {
            block_size: block_size.max(1),
        }
    }

    #[inline]
    pub fn encode(&self, data: &[u8]) -> Vec<u8> {
        if data.len() <= self.block_size {
            return data.to_vec();
        }
        let mut result = Vec::with_capacity(data.len());
        result.extend_from_slice(&data[..self.block_size]);
        for i in self.block_size..data.len() {
            result.push(data[i] ^ data[i - self.block_size]);
        }
        result
    }

    #[inline]
    pub fn decode(&self, data: &[u8]) -> Vec<u8> {
        if data.len() <= self.block_size {
            return data.to_vec();
        }
        let mut result = Vec::with_capacity(data.len());
        result.extend_from_slice(&data[..self.block_size]);
        for i in self.block_size..data.len() {
            result.push(data[i] ^ result[i - self.block_size]);
        }
        result
    }
}

/// Multi-byte XOR: XOR with 16-bit or 32-bit words
pub struct MultiByteXor {
    pub width: usize,
}

impl MultiByteXor {
    pub fn new(width: usize) -> Self {
        Self {
            width: width.max(1),
        }
    }

    #[inline]
    pub fn encode(&self, data: &[u8]) -> Vec<u8> {
        if data.len() <= self.width {
            return data.to_vec();
        }
        let mut result = Vec::with_capacity(data.len());
        result.extend_from_slice(&data[..self.width]);
        // Hint for optimizer: use iterators for XOR
        for i in self.width..data.len() {
            result.push(data[i] ^ data[i - self.width]);
        }
        result
    }

    #[inline]
    pub fn decode(&self, data: &[u8]) -> Vec<u8> {
        if data.len() <= self.width {
            return data.to_vec();
        }
        let mut result = Vec::with_capacity(data.len());
        result.extend_from_slice(&data[..self.width]);
        for i in self.width..data.len() {
            result.push(data[i] ^ result[i - self.width]);
        }
        result
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;

    #[test]
    fn test_delta_roundtrip() {
        let data = vec![0, 1, 3, 6, 10, 15, 21, 28];
        let encoded = DeltaTransform::encode(&data);
        let decoded = DeltaTransform::decode(&encoded);
        assert_eq!(data, decoded);
    }

    #[test]
    fn test_block_delta_roundtrip() {
        let data: Vec<u8> = (0..100).map(|i| (i * 3 % 256) as u8).collect();
        let transform = BlockDeltaTransform::new(4);
        let encoded = transform.encode(&data);
        let decoded = transform.decode(&encoded);
        assert_eq!(data, decoded);
    }

    #[test]
    fn test_channel_separator_roundtrip() {
        let data: Vec<u8> = (0..90).map(|i| i as u8).collect(); // 30 RGB pixels
        let sep = ChannelSeparator::new(3);
        let separated = sep.separate(&data);
        let interleaved = sep.interleave(&separated);
        assert_eq!(data, interleaved);
    }

    #[test]
    fn test_xor_delta_roundtrip() {
        let data: Vec<u8> = (0..100).map(|i| (i * 7 % 256) as u8).collect();
        let transform = XorDeltaTransform::new(8);
        let encoded = transform.encode(&data);
        let decoded = transform.decode(&encoded);
        assert_eq!(data, decoded);
    }

    #[test]
    fn test_file_type_detection() {
        // JPEG
        let jpeg = vec![0xFF, 0xD8, 0xFF, 0xE0, 0, 0, 0, 0];
        assert_eq!(DetectedType::detect(&jpeg), DetectedType::Jpeg);

        // PNG
        let png = vec![0x89, 0x50, 0x4E, 0x47, 0, 0, 0, 0];
        assert_eq!(DetectedType::detect(&png), DetectedType::Png);

        // MP4
        let mp4 = vec![0, 0, 0, 0, b'f', b't', b'y', b'p'];
        assert_eq!(DetectedType::detect(&mp4), DetectedType::Mp4);
    }
}