parx-rs 0.1.0

Parx format Rust library
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
/*
 * Copyright 2026 PARX Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/// Magic bytes identifying a PARX file: "PARX" in ASCII.
pub const MAGIC: [u8; 4] = *b"PARX";

/// Current major version of the PARX format.
pub const VERSION_MAJOR: u8 = 1;

/// Current minor version of the PARX format.
pub const VERSION_MINOR: u8 = 0;

/// Size of the PARX header in bytes.
pub const HEADER_SIZE: usize = 16;

/// Size of the PARX trailer in bytes.
pub const TRAILER_SIZE: usize = 12;

/// Minimum valid PARX file size (header + trailer, no payload).
pub const MIN_FILE_SIZE: usize = HEADER_SIZE + TRAILER_SIZE;

/// Bit 1: Footer payload is compressed.
pub const FLAG_FOOTER_COMPRESSED: u16 = 0x0002;

/// Bits 2-3: Compression algorithm mask (when `FLAG_FOOTER_COMPRESSED` is set).
pub const FLAG_COMPRESSION_MASK: u16 = 0x000C;

/// Compression algorithm: Zstd (bits 2-3 = 00).
pub const FLAG_COMPRESSION_ZSTD: u16 = 0x0000;

/// Compression algorithm: LZ4 (bits 2-3 = 01).
pub const FLAG_COMPRESSION_LZ4: u16 = 0x0004;

/// Compression algorithm: Gzip (bits 2-3 = 10).
pub const FLAG_COMPRESSION_GZIP: u16 = 0x0008;

/// Compression algorithm used for footer data.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Compression {
    Zstd,
    Lz4,
    Gzip,
}

impl Compression {
    /// Get the corresponding flag bits for this compression algorithm.
    #[inline]
    pub const fn to_flag_bits(self) -> u16 {
        match self {
            Self::Zstd => FLAG_COMPRESSION_ZSTD,
            Self::Lz4 => FLAG_COMPRESSION_LZ4,
            Self::Gzip => FLAG_COMPRESSION_GZIP,
        }
    }

    #[inline]
    pub const fn from_flag_bits(bits: u16) -> Option<Self> {
        match bits & FLAG_COMPRESSION_MASK {
            FLAG_COMPRESSION_ZSTD => Some(Self::Zstd),
            FLAG_COMPRESSION_LZ4 => Some(Self::Lz4),
            FLAG_COMPRESSION_GZIP => Some(Self::Gzip),
            _ => None,
        }
    }

    #[inline]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Zstd => "zstd",
            Self::Lz4 => "lz4",
            Self::Gzip => "gzip",
        }
    }
}

impl std::fmt::Display for Compression {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.name())
    }
}

impl std::str::FromStr for Compression {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "zstd" | "zstandard" => Ok(Self::Zstd),
            "lz4" => Ok(Self::Lz4),
            "gzip" | "gz" => Ok(Self::Gzip),
            _ => Err(format!(
                "unknown compression: {s}. Valid options: zstd, lz4, gzip"
            )),
        }
    }
}

/// PARX file header structure (16 bytes total).
///
/// Layout:
/// - bytes 0-3: magic ("PARX")
/// - byte 4: version_major
/// - byte 5: version_minor
/// - bytes 6-7: flags (little-endian)
/// - bytes 8-15: reserved
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Header {
    pub magic: [u8; 4],
    pub version_major: u8,
    pub version_minor: u8,
    pub flags: u16,
}

impl Header {
    /// Create a new header
    #[inline]
    pub const fn new() -> Self {
        Self {
            magic: MAGIC,
            version_major: VERSION_MAJOR,
            version_minor: VERSION_MINOR,
            flags: 0,
        }
    }

    /// Parse header from bytes.
    #[inline]
    pub const fn from_bytes(bytes: &[u8; HEADER_SIZE]) -> Self {
        let magic = [bytes[0], bytes[1], bytes[2], bytes[3]];
        let version_major = bytes[4];
        let version_minor = bytes[5];
        let flags = u16::from_le_bytes([bytes[6], bytes[7]]);

        Self {
            magic,
            version_major,
            version_minor,
            flags,
        }
    }

    /// Serialize header to bytes.
    #[inline]
    pub fn to_bytes(&self) -> [u8; HEADER_SIZE] {
        let mut bytes = [0u8; HEADER_SIZE];
        bytes[0..4].copy_from_slice(&self.magic);
        bytes[4] = self.version_major;
        bytes[5] = self.version_minor;
        bytes[6..8].copy_from_slice(&self.flags.to_le_bytes());
        // bytes 8-15 are reserved (zeros)
        bytes
    }

    /// Check if magic matches expected value.
    #[inline]
    pub fn is_magic_valid(&self, expected_magic: [u8; 4]) -> bool {
        self.magic == expected_magic
    }

    /// Check if version is supported.
    #[inline]
    pub const fn is_version_supported(&self) -> bool {
        self.version_major == VERSION_MAJOR
    }

    /// Check if the footer is compressed.
    #[inline]
    pub const fn is_footer_compressed(&self) -> bool {
        self.flags & FLAG_FOOTER_COMPRESSED != 0
    }

    /// Get the compression algorithm, if footer is compressed.
    #[inline]
    pub const fn compression_algorithm(&self) -> Option<Compression> {
        if !self.is_footer_compressed() {
            return None;
        }
        Compression::from_flag_bits(self.flags)
    }

    /// Set the compression algorithm (also sets the compressed flag).
    #[inline]
    pub fn set_compression(&mut self, compression: Compression) {
        self.flags |= FLAG_FOOTER_COMPRESSED;
        self.flags &= !FLAG_COMPRESSION_MASK;
        self.flags |= compression.to_flag_bits();
    }

    /// Clear compression (footer is uncompressed).
    #[inline]
    pub fn clear_compression(&mut self) {
        self.flags &= !FLAG_FOOTER_COMPRESSED;
        self.flags &= !FLAG_COMPRESSION_MASK;
    }
}

impl Default for Header {
    fn default() -> Self {
        Self::new()
    }
}

/// PARX file trailer (12 bytes, at EOF).
///
/// Layout:
/// - bytes 0-3: manifest_len (u32 LE)
/// - bytes 4-7: manifest_crc32c (u32 LE)
/// - bytes 8-11: magic ("PARX")
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Trailer {
    pub manifest_len: u32,
    pub manifest_crc32c: u32,
    pub magic: [u8; 4],
}

impl Trailer {
    /// Create a new trailer.
    #[inline]
    pub const fn new(manifest_len: u32, manifest_crc32c: u32, magic: [u8; 4]) -> Self {
        Self {
            manifest_len,
            manifest_crc32c,
            magic,
        }
    }

    /// Parse trailer from bytes.
    #[inline]
    pub const fn from_bytes(bytes: &[u8; TRAILER_SIZE]) -> Self {
        let manifest_len = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
        let manifest_crc32c = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
        let magic = [bytes[8], bytes[9], bytes[10], bytes[11]];

        Self {
            manifest_len,
            manifest_crc32c,
            magic,
        }
    }

    /// Serialize trailer to bytes.
    #[inline]
    pub fn to_bytes(&self) -> [u8; TRAILER_SIZE] {
        let mut bytes = [0u8; TRAILER_SIZE];
        bytes[0..4].copy_from_slice(&self.manifest_len.to_le_bytes());
        bytes[4..8].copy_from_slice(&self.manifest_crc32c.to_le_bytes());
        bytes[8..12].copy_from_slice(&self.magic);
        bytes
    }

    /// Check if magic matches expected value.
    #[inline]
    pub fn is_magic_valid(&self, expected_magic: [u8; 4]) -> bool {
        self.magic == expected_magic
    }
}

/// Magic bytes identifying a PARX bundle file: "PRXB" in ASCII.
pub const BUNDLE_MAGIC: [u8; 4] = *b"PRXB";

/// Size of the PARX bundle header in bytes.
pub const BUNDLE_HEADER_SIZE: usize = 24;

/// Bundle header (24 bytes).
///
/// Layout:
/// - bytes 0-3: magic ("PRXB")
/// - byte 4: version_major
/// - byte 5: version_minor
/// - bytes 6-7: flags (little-endian)
/// - bytes 8-15: entry_count (u64 LE)
/// - bytes 16-23: reserved
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BundleHeader {
    pub magic: [u8; 4],
    pub version_major: u8,
    pub version_minor: u8,
    pub flags: u16,
    pub entry_count: u64,
}

impl BundleHeader {
    /// Create a new bundle header.
    #[inline]
    pub const fn new(entry_count: u64) -> Self {
        Self {
            magic: BUNDLE_MAGIC,
            version_major: VERSION_MAJOR,
            version_minor: VERSION_MINOR,
            flags: 0,
            entry_count,
        }
    }

    /// Parse bundle header from bytes
    #[inline]
    pub const fn from_bytes(bytes: &[u8; BUNDLE_HEADER_SIZE]) -> Self {
        let magic = [bytes[0], bytes[1], bytes[2], bytes[3]];
        let version_major = bytes[4];
        let version_minor = bytes[5];
        let flags = u16::from_le_bytes([bytes[6], bytes[7]]);
        let entry_count = u64::from_le_bytes([
            bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15],
        ]);

        Self {
            magic,
            version_major,
            version_minor,
            flags,
            entry_count,
        }
    }

    /// Serialize bundle header to bytes.
    #[inline]
    pub fn to_bytes(&self) -> [u8; BUNDLE_HEADER_SIZE] {
        let mut bytes = [0u8; BUNDLE_HEADER_SIZE];
        bytes[0..4].copy_from_slice(&self.magic);
        bytes[4] = self.version_major;
        bytes[5] = self.version_minor;
        bytes[6..8].copy_from_slice(&self.flags.to_le_bytes());
        bytes[8..16].copy_from_slice(&self.entry_count.to_le_bytes());
        // bytes 16-23 are reserved (zeros)
        bytes
    }

    /// Check if magic is valid.
    #[inline]
    pub fn is_magic_valid(&self) -> bool {
        self.magic == BUNDLE_MAGIC
    }

    /// Check if version is supported.
    #[inline]
    pub const fn is_version_supported(&self) -> bool {
        self.version_major == VERSION_MAJOR
    }
}

impl Default for BundleHeader {
    fn default() -> Self {
        Self::new(0)
    }
}

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

    #[test]
    fn test_header_roundtrip() {
        let header = Header::new();
        let bytes = header.to_bytes();
        let parsed = Header::from_bytes(&bytes);
        assert_eq!(header, parsed);
    }

    #[test]
    fn test_trailer_roundtrip() {
        let trailer = Trailer::new(1234, 0xDEAD_BEEF, MAGIC);
        let bytes = trailer.to_bytes();
        let parsed = Trailer::from_bytes(&bytes);
        assert_eq!(trailer, parsed);
    }

    #[test]
    fn test_magic_validation() {
        let header = Header::new();
        assert!(header.is_magic_valid(MAGIC));

        let mut bad_header = header;
        bad_header.magic = *b"NOPE";
        assert!(!bad_header.is_magic_valid(MAGIC));
    }

    #[test]
    fn test_compression_flag() {
        let mut header = Header::new();
        assert!(!header.is_footer_compressed());
        assert!(header.compression_algorithm().is_none());

        header.set_compression(Compression::Zstd);
        assert!(header.is_footer_compressed());
        assert_eq!(header.compression_algorithm(), Some(Compression::Zstd));

        header.set_compression(Compression::Lz4);
        assert!(header.is_footer_compressed());
        assert_eq!(header.compression_algorithm(), Some(Compression::Lz4));

        header.set_compression(Compression::Gzip);
        assert!(header.is_footer_compressed());
        assert_eq!(header.compression_algorithm(), Some(Compression::Gzip));

        header.clear_compression();
        assert!(!header.is_footer_compressed());
        assert!(header.compression_algorithm().is_none());
    }

    #[test]
    fn test_header_flags_roundtrip() {
        let mut header = Header::new();
        header.set_compression(Compression::Lz4);

        let bytes = header.to_bytes();
        let parsed = Header::from_bytes(&bytes);

        assert_eq!(parsed.flags, header.flags);
        assert_eq!(parsed.compression_algorithm(), Some(Compression::Lz4));
    }

    #[test]
    fn test_bundle_header_roundtrip() {
        let header = BundleHeader::new(42);
        let bytes = header.to_bytes();
        let parsed = BundleHeader::from_bytes(&bytes);
        assert_eq!(header, parsed);
        assert_eq!(parsed.entry_count, 42);
    }

    #[test]
    fn test_compression_from_str() {
        assert_eq!("zstd".parse::<Compression>().unwrap(), Compression::Zstd);
        assert_eq!("ZSTD".parse::<Compression>().unwrap(), Compression::Zstd);
        assert_eq!("lz4".parse::<Compression>().unwrap(), Compression::Lz4);
        assert_eq!("gzip".parse::<Compression>().unwrap(), Compression::Gzip);
        assert_eq!("gz".parse::<Compression>().unwrap(), Compression::Gzip);
        assert!("invalid".parse::<Compression>().is_err());
    }

    #[test]
    fn test_compression_display() {
        assert_eq!(Compression::Zstd.to_string(), "zstd");
        assert_eq!(Compression::Lz4.to_string(), "lz4");
        assert_eq!(Compression::Gzip.to_string(), "gzip");
    }
}