libpna 0.38.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
//! Slice-based archive reading for memory-mapped access.

use super::verify_next_archive_number;
use crate::{
    Archive, Chunk, ChunkType, Entry, NormalEntry, RawChunk, ReadEntry, ReadOptions,
    archive::{ArchiveHeader, read::ExtractSolidEntries},
    entry::RawEntry,
};
use std::borrow::Cow;
use std::io;

impl<'d> Archive<&'d [u8]> {
    /// Reads the archive header from the provided bytes and returns a new [`Archive`].
    ///
    /// # Errors
    ///
    /// Returns an error if an I/O error occurs while reading the header from the bytes.
    #[inline]
    pub fn read_header_from_slice(bytes: &'d [u8]) -> io::Result<Self> {
        Self::read_header_from_slice_with_buffer(bytes, Vec::new())
    }

    #[inline]
    fn read_header_from_slice_with_buffer(bytes: &'d [u8], buf: Vec<RawChunk>) -> io::Result<Self> {
        let bytes = crate::bytes::read_signature(bytes)?;
        let (chunk, r) = crate::bytes::read_chunk(bytes, u32::MAX)?;
        if chunk.ty != ChunkType::AHED {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("unexpected chunk `{}`", chunk.ty),
            ));
        }
        let header = ArchiveHeader::try_from_bytes(chunk.data())?;
        Ok(Self::with_buffer(r, header, buf))
    }

    /// Reads the next raw entry (from `FHED` to `FEND` chunk) from the archive.
    ///
    /// Returns `Ok(None)` when no more entries remain.
    ///
    /// # Errors
    ///
    /// Returns an error if an I/O error occurs while reading from the archive.
    fn next_raw_item_slice(&mut self) -> io::Result<Option<RawEntry<Cow<'d, [u8]>>>> {
        let mut chunks = Vec::new();
        std::mem::swap(&mut self.buf, &mut chunks);
        let mut chunks = chunks.into_iter().map(Into::into).collect::<Vec<_>>();
        let max_chunk_size = self.max_chunk_size.map_or(u32::MAX, |max| max.get());
        loop {
            let (chunk, r) = crate::bytes::read_chunk(self.inner, max_chunk_size)?;
            self.inner = r;
            match chunk.ty {
                ChunkType::FEND | ChunkType::SEND => {
                    chunks.push(chunk.into());
                    break;
                }
                ChunkType::ANXT => self.next_archive = true,
                ChunkType::AEND => {
                    self.buf = chunks.into_iter().map(Into::into).collect::<Vec<_>>();
                    return Ok(None);
                }
                _ => chunks.push(chunk.into()),
            }
        }
        Ok(Some(RawEntry(chunks)))
    }

    /// Reads the next entry from the archive.
    ///
    /// Returns `Ok(None)` when no more entries remain.
    ///
    /// # Errors
    ///
    /// Returns an error if an I/O error occurs while reading from the archive.
    fn read_entry_slice(&mut self) -> io::Result<Option<ReadEntry<Cow<'d, [u8]>>>> {
        self.next_raw_item_slice()?
            .map(TryInto::try_into)
            .transpose()
    }

    /// Returns an iterator over the entries in the archive.
    ///
    /// # Examples
    /// ```no_run
    /// use libpna::{Archive, ReadEntry};
    /// use std::fs;
    /// # use std::io;
    ///
    /// # fn main() -> io::Result<()> {
    /// let file = fs::read("foo.pna")?;
    /// let mut archive = Archive::read_header_from_slice(&file[..])?;
    /// for entry in archive.entries_slice() {
    ///     match entry? {
    ///         ReadEntry::Solid(solid_entry) => {
    ///             // handle solid entry
    ///         }
    ///         ReadEntry::Normal(entry) => {
    ///             // handle normal entry
    ///         }
    ///     }
    /// }
    /// #    Ok(())
    /// # }
    /// ```
    #[inline]
    pub const fn entries_slice<'a>(&'a mut self) -> Entries<'a, 'd> {
        Entries::new(self)
    }

    /// Returns an iterator over raw entries in the archive.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use std::io;
    /// use libpna::Archive;
    /// use std::fs;
    ///
    /// # fn main() -> io::Result<()> {
    /// let bytes = fs::read("foo.pna")?;
    /// let mut src = Archive::read_header_from_slice(&bytes[..])?;
    /// let mut dist = Archive::write_header(Vec::new())?;
    /// for entry in src.raw_entries_slice() {
    ///     dist.add_entry(entry?)?;
    /// }
    /// dist.finalize()?;
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn raw_entries_slice<'s>(
        &'s mut self,
    ) -> impl Iterator<Item = io::Result<impl Entry + Sized + 'd>> + 's {
        RawEntries::<'s, 'd>(self)
    }

    /// Reads the next archive from the provided bytes and returns a new [`Archive`].
    ///
    /// # Errors
    ///
    /// Returns an error if an I/O error occurs while reading from the bytes.
    #[inline]
    pub fn read_next_archive_from_slice(self, bytes: &[u8]) -> io::Result<Archive<&[u8]>> {
        let mut next = Archive::read_header_from_slice_with_buffer(bytes, self.buf)?;
        next.max_chunk_size = self.max_chunk_size;
        verify_next_archive_number(&self.header, &next.header)?;
        Ok(next)
    }

    /// Reads the archive that follows this one in the same bytes and returns a new [`Archive`].
    ///
    /// Use this when the parts of a split archive are concatenated in a single byte
    /// sequence instead of one sequence per part.
    ///
    /// # Errors
    ///
    /// Returns an error if an I/O error occurs while reading from the bytes.
    #[inline]
    pub fn read_next_archive_in_stream_from_slice(self) -> io::Result<Self> {
        let Self {
            inner,
            header,
            max_chunk_size,
            buf,
            ..
        } = self;
        let mut next = Self::read_header_from_slice_with_buffer(inner, buf)?;
        next.max_chunk_size = max_chunk_size;
        verify_next_archive_number(&header, &next.header)?;
        Ok(next)
    }
}

pub(crate) struct RawEntries<'a, 'r>(&'a mut Archive<&'r [u8]>);

impl<'r> Iterator for RawEntries<'_, 'r> {
    type Item = io::Result<RawEntry<Cow<'r, [u8]>>>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.0.next_raw_item_slice().transpose()
    }
}

/// An iterator over the entries in the archive.
pub struct Entries<'a, 'r> {
    reader: &'a mut Archive<&'r [u8]>,
}

impl<'a, 'r> Entries<'a, 'r> {
    #[inline]
    pub(crate) const fn new(reader: &'a mut Archive<&'r [u8]>) -> Self {
        Self { reader }
    }

    /// Returns an iterator that extracts solid entries from the archive and returns them as normal entries.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use libpna::{Archive, ReadEntry, ReadOptions};
    /// use std::fs;
    /// # use std::io;
    ///
    /// # fn main() -> io::Result<()> {
    /// let file = fs::read("foo.pna")?;
    /// let mut archive = Archive::read_header_from_slice(&file[..])?;
    /// let options = ReadOptions::with_password(Some(b"password"));
    /// for entry in archive
    ///     .entries_slice()
    ///     .extract_solid_entries(&options)
    /// {
    ///     let mut reader = entry?.reader(ReadOptions::builder().build());
    ///     // process the entry
    /// }
    /// #    Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn extract_solid_entries(
        self,
        options: &ReadOptions,
    ) -> impl Iterator<Item = io::Result<NormalEntry<Cow<'r, [u8]>>>> + 'a {
        ExtractSolidEntries::new(self, options)
    }
}

impl<'r> Iterator for Entries<'_, 'r> {
    type Item = io::Result<ReadEntry<Cow<'r, [u8]>>>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.reader.read_entry_slice().transpose()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{FileEntryBuilder, Metadata, RawChunk, SolidEntryBuilder, WriteOptions};
    use std::{io::Write, num::NonZeroU32};
    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
    use wasm_bindgen_test::wasm_bindgen_test as test;

    #[test]
    fn decode() {
        let bytes = include_bytes!("../../../../resources/test/zstd.pna");
        let mut archive = Archive::read_header_from_slice(bytes).unwrap();
        let mut entries = archive.entries_slice();
        assert!(entries.next().is_some());
        assert!(entries.next().is_some());
        assert!(entries.next().is_some());
        assert!(entries.next().is_some());
        assert!(entries.next().is_some());
        assert!(entries.next().is_some());
        assert!(entries.next().is_some());
        assert!(entries.next().is_some());
        assert!(entries.next().is_some());
        assert!(entries.next().is_none());
    }

    #[test]
    fn decode_solid() {
        let bytes = include_bytes!("../../../../resources/test/solid_zstd.pna");
        let mut archive = Archive::read_header_from_slice(bytes).unwrap();
        let mut entries = archive.entries_slice();
        let solid_entry = entries.next().unwrap().unwrap();
        if let ReadEntry::Solid(solid_entry) = solid_entry {
            let mut entries = solid_entry.entries(ReadOptions::builder().build()).unwrap();
            assert!(entries.next().is_some());
            assert!(entries.next().is_some());
            assert!(entries.next().is_some());
            assert!(entries.next().is_some());
            assert!(entries.next().is_some());
            assert!(entries.next().is_some());
            assert!(entries.next().is_some());
            assert!(entries.next().is_some());
            assert!(entries.next().is_some());
            assert!(entries.next().is_none());
        } else {
            panic!()
        }
    }

    fn archive_with_eight_byte_data() -> Vec<u8> {
        let mut archive = Archive::write_header(Vec::new()).unwrap();
        archive
            .write_file(
                "a".into(),
                Metadata::new(),
                WriteOptions::store(),
                |writer| writer.write_all(b"12345678"),
            )
            .unwrap();
        archive.finalize().unwrap()
    }

    fn archive_with_normal_and_solid_entries() -> Vec<u8> {
        let mut normal_builder =
            FileEntryBuilder::new_with_options("normal".into(), WriteOptions::store()).unwrap();
        normal_builder.write_all(b"normal data").unwrap();
        let normal = normal_builder
            .build()
            .unwrap()
            .with_extra_chunks(vec![RawChunk::from_data(
                ChunkType::private(*b"exTr").unwrap(),
                b"extra".to_vec(),
            )]);

        let mut solid = SolidEntryBuilder::new(WriteOptions::store()).unwrap();
        solid
            .write_file("solid-1".into(), Metadata::new(), |writer| {
                writer.write_all(b"solid data 1")
            })
            .unwrap();
        solid
            .write_file("solid-2".into(), Metadata::new(), |writer| {
                writer.write_all(b"solid data 2")
            })
            .unwrap();

        let mut archive = Archive::write_header(Vec::new()).unwrap();
        archive.add_entry(normal).unwrap();
        archive.add_entry(solid.build().unwrap()).unwrap();
        archive.finalize().unwrap()
    }

    fn collect_slice_entries<'d>(bytes: &'d [u8]) -> Vec<NormalEntry<Cow<'d, [u8]>>> {
        let mut archive = Archive::read_header_from_slice(bytes).unwrap();
        archive
            .entries_slice()
            .extract_solid_entries(&ReadOptions::builder().build())
            .collect::<io::Result<Vec<_>>>()
            .unwrap()
    }

    #[test]
    fn extract_solid_entries_borrows_normal_data_and_owns_solid_data() {
        let bytes = archive_with_normal_and_solid_entries();
        let entries = collect_slice_entries(&bytes);

        assert_eq!(entries.len(), 3);
        assert_eq!(entries[0].header().path(), "normal");
        assert!(
            entries[0]
                .data
                .iter()
                .all(|data| matches!(data, Cow::Borrowed(_)))
        );
        assert!(matches!(
            entries[0].extra.first().map(|chunk| &chunk.data),
            Some(Cow::Borrowed(_))
        ));

        assert_eq!(entries[1].header().path(), "solid-1");
        assert_eq!(entries[2].header().path(), "solid-2");
        for entry in &entries[1..] {
            assert!(entry.data.iter().all(|data| matches!(data, Cow::Owned(_))));
        }
    }

    #[test]
    fn extract_solid_entries_decodes_encrypted_compressed_data() {
        let bytes = include_bytes!("../../../../resources/test/solid_zstd_aes_gcm.pna");
        let mut archive = Archive::read_header_from_slice(bytes).unwrap();
        let entries = archive
            .entries_slice()
            .extract_solid_entries(&ReadOptions::with_password(Some(b"password")))
            .collect::<io::Result<Vec<_>>>()
            .unwrap();

        assert_eq!(entries.len(), 9);
        assert!(
            entries
                .iter()
                .all(|entry| entry.data.iter().all(|data| matches!(data, Cow::Owned(_))))
        );
    }

    #[test]
    fn entries_slice_enforces_max_chunk_size() {
        let bytes = archive_with_eight_byte_data();
        let mut archive = Archive::read_header_from_slice(&bytes).unwrap();
        archive.set_max_chunk_size(NonZeroU32::new(7).unwrap());

        assert_eq!(
            archive.entries_slice().next().unwrap().unwrap_err().kind(),
            io::ErrorKind::InvalidData
        );
    }

    #[test]
    fn next_archive_from_slice_preserves_max_chunk_size() {
        let mut first_bytes = Vec::new();
        let first = Archive::write_header(&mut first_bytes).unwrap();
        let mut second = first.split_to_next_archive(Vec::new()).unwrap();

        second
            .write_file(
                "a".into(),
                Metadata::new(),
                WriteOptions::store(),
                |writer| writer.write_all(b"12345678"),
            )
            .unwrap();
        let second_bytes = second.finalize().unwrap();

        let mut first = Archive::read_header_from_slice(&first_bytes).unwrap();
        first.set_max_chunk_size(NonZeroU32::new(7).unwrap());
        assert!(first.entries_slice().next().is_none());

        let mut second = first.read_next_archive_from_slice(&second_bytes).unwrap();
        assert_eq!(
            second.entries_slice().next().unwrap().unwrap_err().kind(),
            io::ErrorKind::InvalidData
        );
    }

    #[test]
    fn next_archive_in_stream_from_slice_reads_the_part_that_follows() {
        let mut bytes = Vec::new();
        let first = Archive::write_header(&mut bytes).unwrap();
        let mut second = first.split_to_next_archive(Vec::new()).unwrap();

        second
            .write_file(
                "a".into(),
                Metadata::new(),
                WriteOptions::store(),
                |writer| writer.write_all(b"12345678"),
            )
            .unwrap();
        let second_bytes = second.finalize().unwrap();
        bytes.extend_from_slice(&second_bytes);

        let mut first = Archive::read_header_from_slice(&bytes).unwrap();
        first.set_max_chunk_size(NonZeroU32::new(7).unwrap());
        assert!(first.entries_slice().next().is_none());
        assert!(first.has_next_archive());

        let mut second = first.read_next_archive_in_stream_from_slice().unwrap();
        assert_eq!(
            second.entries_slice().next().unwrap().unwrap_err().kind(),
            io::ErrorKind::InvalidData
        );
    }

    #[test]
    fn next_archive_in_stream_from_slice_rejects_non_consecutive_number() {
        let mut bytes = Vec::new();
        Archive::write_header(&mut bytes)
            .unwrap()
            .finalize()
            .unwrap();
        let independent = bytes.clone();
        bytes.extend_from_slice(&independent);

        let mut first = Archive::read_header_from_slice(&bytes).unwrap();
        assert!(first.entries_slice().next().is_none());
        let err = first
            .read_next_archive_in_stream_from_slice()
            .err()
            .unwrap();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
    }
}