libpna 0.31.0

PNA(Portable-Network-Archive) decoding and encoding 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
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
//! Chunk module: low-level PNA chunk primitives.
//!
//! Chunks are the basic framing unit of a PNA archive. This module provides
//! chunk types, reading/writing utilities, and CRC calculation needed to parse
//! and emit well-formed streams. Higher-level modules (archive/entry) build on
//! these primitives.
mod crc;
mod read;
mod traits;
mod types;
mod write;

use self::crc::Crc32;
pub(crate) use self::{read::*, write::*};
pub use self::{traits::*, types::*};
use std::{
    borrow::Cow,
    io::{self, prelude::*},
    mem,
};

/// The minimum size of a PNA chunk in bytes.
///
/// A chunk consists of a 4-byte length field, a 4-byte chunk type, a variable-size
/// data field, and a 4-byte CRC checksum. This constant represents the size of a
/// chunk with an empty data field.
pub const MIN_CHUNK_BYTES_SIZE: usize =
    mem::size_of::<u32>() + mem::size_of::<ChunkType>() + mem::size_of::<u32>();

/// Maximum length of chunk body in bytes.
pub(crate) const MAX_CHUNK_DATA_LENGTH: usize = u32::MAX as usize;

/// An extension trait for [`Chunk`] that provides common operations.
///
/// This trait is automatically implemented for any type that implements [`Chunk`],
/// offering a set of convenient methods for working with chunks, such as
/// calculating their total byte length, writing them to a writer, and converting
/// them to a byte vector.
pub(crate) trait ChunkExt: Chunk {
    /// Calculates the total size of the chunk in bytes.
    ///
    /// This includes the length of the data field plus the fixed sizes of the
    /// length, type, and CRC fields.
    ///
    /// # Returns
    ///
    /// The total size of the chunk in bytes.
    #[inline]
    fn bytes_len(&self) -> usize {
        MIN_CHUNK_BYTES_SIZE + self.data().len()
    }

    /// Checks if the chunk is a stream chunk.
    ///
    /// Stream chunks, such as `FDAT` (File Data) and `SDAT` (Solid Data),
    /// contain file content data.
    ///
    /// # Returns
    ///
    /// `true` if the chunk is a stream chunk, `false` otherwise.
    #[inline]
    fn is_stream_chunk(&self) -> bool {
        self.ty() == ChunkType::FDAT || self.ty() == ChunkType::SDAT
    }

    /// Writes the entire chunk to a given writer.
    ///
    /// This method serializes the chunk, including its length, type, data, and
    /// CRC, and writes the resulting bytes to the specified writer.
    ///
    /// # Arguments
    ///
    /// * `writer` - The writer to which the chunk will be written.
    ///
    /// # Returns
    ///
    /// The total number of bytes written to the writer.
    ///
    /// # Errors
    ///
    /// Returns an error if any part of the write operation fails.
    #[inline]
    fn write_chunk_in<W: Write>(&self, writer: &mut W) -> io::Result<usize> {
        writer.write_all(&self.length().to_be_bytes())?;
        writer.write_all(&self.ty().0)?;
        writer.write_all(self.data())?;
        writer.write_all(&self.crc().to_be_bytes())?;
        Ok(self.bytes_len())
    }

    /// Converts the chunk into a `Vec<u8>`.
    ///
    /// This method serializes the entire chunk into a byte vector, which can be
    /// useful for buffering or network transmission.
    ///
    /// # Returns
    ///
    /// A `Vec<u8>` containing the serialized chunk data.
    #[allow(dead_code)]
    #[inline]
    fn to_bytes(&self) -> Vec<u8> {
        let mut vec = Vec::with_capacity(self.bytes_len());
        vec.extend_from_slice(&self.length().to_be_bytes());
        vec.extend_from_slice(&self.ty().0);
        vec.extend_from_slice(self.data());
        vec.extend_from_slice(&self.crc().to_be_bytes());
        vec
    }
}

impl<T> ChunkExt for T where T: Chunk {}

/// A raw chunk in a PNA archive.
///
/// This structure represents a chunk in its most basic form, containing:
/// - `length`: The length of the chunk data in bytes
/// - `ty`: The type of the chunk (e.g., FDAT, SDAT, etc.)
/// - `data`: The actual chunk data
/// - `crc`: A CRC32 checksum of the chunk type and data
///
/// # Examples
///
/// ```rust
/// use libpna::{ChunkType, RawChunk, prelude::*};
///
/// // Create a new chunk with some data
/// let data = [0xAA, 0xBB, 0xCC, 0xDD];
/// let chunk = RawChunk::from_data(ChunkType::FDAT, data);
///
/// // Access chunk properties
/// assert_eq!(chunk.length(), 4);
/// assert_eq!(chunk.ty(), ChunkType::FDAT);
/// assert_eq!(chunk.data(), &[0xAA, 0xBB, 0xCC, 0xDD]);
/// assert_eq!(chunk.crc(), 1207118608);
/// ```
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
pub struct RawChunk<D = Vec<u8>> {
    /// The length of the chunk data in bytes
    pub(crate) length: u32,
    /// The type of the chunk
    pub(crate) ty: ChunkType,
    /// The actual chunk data
    pub(crate) data: D,
    /// The CRC32 checksum of the chunk type and data
    pub(crate) crc: u32,
}

impl<D> From<(ChunkType, D)> for RawChunk<D>
where
    (ChunkType, D): Chunk,
{
    #[inline]
    fn from(value: (ChunkType, D)) -> Self {
        Self {
            length: value.length(),
            crc: value.crc(),
            ty: value.0,
            data: value.1,
        }
    }
}

impl<'d> RawChunk<&'d [u8]> {
    pub(crate) fn from_slice(ty: ChunkType, data: &'d [u8]) -> Self {
        let chunk = (ty, data);
        Self {
            length: chunk.length(),
            crc: chunk.crc(),
            ty,
            data,
        }
    }
}

impl<'a> From<RawChunk<Cow<'a, [u8]>>> for RawChunk<Vec<u8>> {
    #[inline]
    fn from(value: RawChunk<Cow<'a, [u8]>>) -> Self {
        Self {
            length: value.length,
            ty: value.ty,
            data: value.data.into(),
            crc: value.crc,
        }
    }
}

impl<'a> From<RawChunk<&'a [u8]>> for RawChunk<Vec<u8>> {
    #[inline]
    fn from(value: RawChunk<&'a [u8]>) -> Self {
        Self {
            length: value.length,
            ty: value.ty,
            data: value.data.into(),
            crc: value.crc,
        }
    }
}

impl<const N: usize> From<RawChunk<[u8; N]>> for RawChunk<Vec<u8>> {
    #[inline]
    fn from(value: RawChunk<[u8; N]>) -> Self {
        Self {
            length: value.length,
            ty: value.ty,
            data: value.data.into(),
            crc: value.crc,
        }
    }
}

impl From<RawChunk<Vec<u8>>> for RawChunk<Cow<'_, [u8]>> {
    #[inline]
    fn from(value: RawChunk<Vec<u8>>) -> Self {
        Self {
            length: value.length,
            ty: value.ty,
            data: Cow::Owned(value.data),
            crc: value.crc,
        }
    }
}

impl<'a> From<RawChunk<&'a [u8]>> for RawChunk<Cow<'a, [u8]>> {
    #[inline]
    fn from(value: RawChunk<&'a [u8]>) -> Self {
        Self {
            length: value.length,
            ty: value.ty,
            data: Cow::Borrowed(value.data),
            crc: value.crc,
        }
    }
}

impl<D> RawChunk<D>
where
    Self: Chunk,
{
    #[inline]
    pub(crate) fn as_ref(&self) -> RawChunk<&[u8]> {
        RawChunk {
            length: self.length,
            ty: self.ty,
            data: self.data(),
            crc: self.crc,
        }
    }
}

impl<T: AsRef<[u8]>> Chunk for RawChunk<T> {
    #[inline]
    fn length(&self) -> u32 {
        self.length
    }

    #[inline]
    fn ty(&self) -> ChunkType {
        self.ty
    }

    #[inline]
    fn data(&self) -> &[u8] {
        self.data.as_ref()
    }

    #[inline]
    fn crc(&self) -> u32 {
        self.crc
    }
}

impl RawChunk {
    /// Creates a new [`RawChunk`] from the given [`ChunkType`] and bytes.
    ///
    /// # Examples
    /// ```rust
    /// use libpna::{ChunkType, RawChunk, prelude::*};
    ///
    /// let data = [0xAA, 0xBB, 0xCC, 0xDD];
    /// let chunk = RawChunk::from_data(ChunkType::FDAT, data);
    ///
    /// assert_eq!(chunk.length(), 4);
    /// assert_eq!(chunk.ty(), ChunkType::FDAT);
    /// assert_eq!(chunk.data(), &[0xAA, 0xBB, 0xCC, 0xDD]);
    /// assert_eq!(chunk.crc(), 1207118608);
    /// ```
    #[inline]
    pub fn from_data<T: Into<Vec<u8>>>(ty: ChunkType, data: T) -> Self {
        #[inline]
        fn inner(ty: ChunkType, data: Vec<u8>) -> RawChunk {
            let chunk = (ty, &data[..]);
            RawChunk {
                length: chunk.length(),
                crc: chunk.crc(),
                ty,
                data,
            }
        }
        inner(ty, data.into())
    }
}

impl<T: AsRef<[u8]>> Chunk for (ChunkType, T) {
    #[inline]
    fn ty(&self) -> ChunkType {
        self.0
    }

    #[inline]
    fn data(&self) -> &[u8] {
        self.1.as_ref()
    }
}

impl<T: Chunk> Chunk for &T {
    #[inline]
    fn ty(&self) -> ChunkType {
        T::ty(*self)
    }

    #[inline]
    fn data(&self) -> &[u8] {
        T::data(*self)
    }
}

impl<T: Chunk> Chunk for &mut T {
    #[inline]
    fn ty(&self) -> ChunkType {
        T::ty(*self)
    }

    #[inline]
    fn data(&self) -> &[u8] {
        T::data(*self)
    }
}

#[inline]
pub(crate) fn chunk_data_split(
    ty: ChunkType,
    data: &[u8],
    mid: usize,
) -> (RawChunk<&[u8]>, Option<RawChunk<&[u8]>>) {
    if let Some((first, last)) = data.split_at_checked(mid) {
        if last.is_empty() {
            (RawChunk::from_slice(ty, first), None)
        } else {
            (
                RawChunk::from_slice(ty, first),
                Some(RawChunk::from_slice(ty, last)),
            )
        }
    } else {
        (RawChunk::from_slice(ty, data), None)
    }
}

/// Reads an archive as chunks from the given reader.
///
/// Reads a PNA archive from the given reader and returns an iterator of chunks.
///
/// # Examples
///
/// ```no_run
/// # use std::{io, fs};
/// use libpna::{prelude::*, read_as_chunks};
///
/// # fn main() -> io::Result<()> {
/// let archive = fs::File::open("foo.pna")?;
/// for chunk in read_as_chunks(archive)? {
///     let chunk = chunk?;
///     println!(
///         "chunk type: {}, chunk data size: {}",
///         chunk.ty(),
///         chunk.length()
///     );
/// }
/// # Ok(())
/// # }
/// ```
///
/// # Errors
/// Returns an error if the input is not a PNA archive.
#[inline]
pub fn read_as_chunks<R: Read>(
    mut archive: R,
) -> io::Result<impl Iterator<Item = io::Result<impl Chunk>>> {
    struct Chunks<R> {
        reader: ChunkReader<R>,
        eoa: bool,
    }
    impl<R: Read> Iterator for Chunks<R> {
        type Item = io::Result<RawChunk>;
        #[inline]
        fn next(&mut self) -> Option<Self::Item> {
            if self.eoa {
                return None;
            }
            Some(self.reader.read_chunk().inspect(|chunk| {
                self.eoa = chunk.ty() == ChunkType::AEND;
            }))
        }
    }
    crate::archive::read_pna_header(&mut archive)?;

    Ok(Chunks {
        reader: ChunkReader::new(archive, None),
        eoa: false,
    })
}

/// Reads an archive as chunks from the given bytes.
///
/// Reads a PNA archive from the given byte slice and returns an iterator of chunks.
///
/// # Examples
///
/// ```rust
/// # use std::{io, fs};
/// use libpna::{prelude::*, read_chunks_from_slice};
///
/// # fn main() -> io::Result<()> {
/// let bytes = include_bytes!("../../resources/test/zstd.pna");
/// for chunk in read_chunks_from_slice(bytes)? {
///     let chunk = chunk?;
///     println!(
///         "chunk type: {}, chunk data size: {}",
///         chunk.ty(),
///         chunk.length()
///     );
/// }
/// # Ok(())
/// # }
/// ```
///
/// # Errors
/// Returns an error if the input is not a PNA archive.
#[inline]
pub fn read_chunks_from_slice<'a>(
    archive: &'a [u8],
) -> io::Result<impl Iterator<Item = io::Result<impl Chunk + 'a>>> {
    struct Chunks<'a> {
        reader: &'a [u8],
        eoa: bool,
    }
    impl<'a> Iterator for Chunks<'a> {
        type Item = io::Result<RawChunk<&'a [u8]>>;
        #[inline]
        fn next(&mut self) -> Option<Self::Item> {
            if self.eoa {
                return None;
            }
            Some(read_chunk_from_slice(self.reader).map(|(chunk, bytes)| {
                self.eoa = chunk.ty() == ChunkType::AEND;
                self.reader = bytes;
                chunk
            }))
        }
    }
    let archive = crate::archive::read_header_from_slice(archive)?;

    Ok(Chunks {
        reader: archive,
        eoa: false,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
    use wasm_bindgen_test::wasm_bindgen_test as test;

    #[test]
    fn chunk_trait_bounds() {
        fn check_impl<T: Chunk>() {}
        check_impl::<RawChunk<Vec<u8>>>();
        check_impl::<RawChunk<Cow<[u8]>>>();
        check_impl::<RawChunk<&[u8]>>();
        check_impl::<RawChunk<[u8; 1]>>();
    }

    #[test]
    fn to_bytes() {
        let data = vec![0xAA, 0xBB, 0xCC, 0xDD];
        let chunk = RawChunk::from_data(ChunkType::FDAT, data);

        let bytes = chunk.to_bytes();

        assert_eq!(
            bytes,
            vec![
                0x00, 0x00, 0x00, 0x04, // chunk length (4)
                0x46, 0x44, 0x41, 0x54, // chunk type ("FDAT")
                0xAA, 0xBB, 0xCC, 0xDD, // data bytes
                0x47, 0xf3, 0x2b, 0x10, // CRC32 (calculated from chunk type and data)
            ]
        );
    }

    #[test]
    fn data_split_at_zero() {
        let data = vec![0xAA, 0xBB, 0xCC, 0xDD];
        let chunk = RawChunk::from_data(ChunkType::FDAT, data);
        assert_eq!(
            chunk_data_split(chunk.ty, chunk.data(), 0),
            (
                RawChunk::from_slice(ChunkType::FDAT, &[]),
                Some(RawChunk::from_slice(
                    ChunkType::FDAT,
                    &[0xAA, 0xBB, 0xCC, 0xDD]
                )),
            )
        )
    }

    #[test]
    fn data_split_at_middle() {
        let data = vec![0xAA, 0xBB, 0xCC, 0xDD];
        let chunk = RawChunk::from_data(ChunkType::FDAT, data);
        assert_eq!(
            chunk_data_split(chunk.ty, chunk.data(), 2),
            (
                RawChunk::from_slice(ChunkType::FDAT, &[0xAA, 0xBB]),
                Some(RawChunk::from_slice(ChunkType::FDAT, &[0xCC, 0xDD])),
            )
        )
    }

    #[test]
    fn data_split_at_just() {
        let data = vec![0xAA, 0xBB, 0xCC, 0xDD];
        let chunk = RawChunk::from_data(ChunkType::FDAT, data);
        assert_eq!(
            chunk_data_split(chunk.ty, chunk.data(), 4),
            (
                RawChunk::from_slice(ChunkType::FDAT, &[0xAA, 0xBB, 0xCC, 0xDD]),
                None,
            )
        )
    }

    #[test]
    fn data_split_at_over() {
        let data = vec![0xAA, 0xBB, 0xCC, 0xDD];
        let chunk = RawChunk::from_data(ChunkType::FDAT, data);
        assert_eq!(
            chunk_data_split(chunk.ty, chunk.data(), 5),
            (
                RawChunk::from_slice(ChunkType::FDAT, &[0xAA, 0xBB, 0xCC, 0xDD]),
                None,
            )
        )
    }
}