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
557
558
mod slice;
use crate::{
archive::{Archive, ArchiveHeader, PNA_HEADER},
chunk::{Chunk, ChunkReader, ChunkType, RawChunk, read_chunk},
entry::{Entry, NormalEntry, RawEntry, ReadEntry},
};
#[cfg(feature = "unstable-async")]
use futures_util::AsyncReadExt;
pub(crate) use slice::read_header_from_slice;
use std::{
io::{self, Read, Seek, SeekFrom},
mem::swap,
};
pub(crate) fn read_pna_header<R: Read>(mut reader: R) -> io::Result<()> {
let mut header = [0u8; PNA_HEADER.len()];
reader.read_exact(&mut header)?;
if &header != PNA_HEADER {
return Err(io::Error::new(io::ErrorKind::InvalidData, "It's not PNA"));
}
Ok(())
}
#[cfg(feature = "unstable-async")]
async fn read_pna_header_async<R: futures_io::AsyncRead + Unpin>(mut reader: R) -> io::Result<()> {
let mut header = [0u8; PNA_HEADER.len()];
reader.read_exact(&mut header).await?;
if &header != PNA_HEADER {
return Err(io::Error::new(io::ErrorKind::InvalidData, "It's not PNA"));
}
Ok(())
}
impl<R: Read> Archive<R> {
/// Reads the archive header from the provided reader and returns a new [Archive].
///
/// # Arguments
///
/// * `reader` - The [Read] object to read the header from.
///
/// # Returns
///
/// A new [`io::Result<Archive<R>>`].
///
/// # Errors
///
/// Returns an error if an I/O error occurs while reading the header from the reader.
#[inline]
pub fn read_header(reader: R) -> io::Result<Self> {
Self::read_header_with_buffer(reader, Default::default())
}
fn read_header_with_buffer(mut reader: R, buf: Vec<RawChunk>) -> io::Result<Self> {
read_pna_header(&mut reader)?;
let mut chunk_reader = ChunkReader::new(&mut reader, None);
let chunk = chunk_reader.read_chunk()?;
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(reader, header, buf))
}
/// Reads the next raw entry (from `FHED` to `FEND` chunk) from the archive.
///
/// # Returns
///
/// An [`io::Result<Option<RawEntry>>`]. Returns `Ok(None)` if there are no more items to read.
///
/// # Errors
///
/// Returns an error if an I/O error occurs while reading from the archive.
fn next_raw_item(&mut self) -> io::Result<Option<RawEntry>> {
let mut chunks = Vec::new();
swap(&mut self.buf, &mut chunks);
loop {
let chunk = read_chunk(&mut self.inner, self.max_chunk_size)?;
match chunk.ty {
ChunkType::FEND | ChunkType::SEND => {
chunks.push(chunk);
break;
}
ChunkType::ANXT => self.next_archive = true,
ChunkType::AEND => {
self.buf = chunks;
return Ok(None);
}
_ => chunks.push(chunk),
}
}
Ok(Some(RawEntry(chunks)))
}
/// Reads the next entry from the archive.
///
/// # Returns
///
/// An [`io::Result<Option<ReadEntry>>`]. Returns `Ok(None)` if there are no more entries to read.
///
/// # Errors
///
/// Returns an error if an I/O error occurs while reading from the archive.
fn read_entry(&mut self) -> io::Result<Option<ReadEntry>> {
self.next_raw_item()?.map(TryInto::try_into).transpose()
}
/// Returns an iterator over raw entries in the archive.
///
/// # Returns
///
/// An iterator over raw entries in the archive.
///
/// # Examples
/// ```no_run
/// # use std::io;
/// use libpna::Archive;
/// use std::fs::File;
///
/// # fn main() -> io::Result<()> {
/// let mut src = Archive::read_header(File::open("foo.pna")?)?;
/// let mut dist = Archive::write_header(File::create("bar.pna")?)?;
/// for entry in src.raw_entries() {
/// dist.add_entry(entry?)?;
/// }
/// dist.finalize()?;
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn raw_entries(&mut self) -> impl Iterator<Item = io::Result<impl Entry + Sized>> + '_ {
RawEntries(self)
}
/// Returns an iterator over the entries in the archive, excluding entries in solid mode.
///
/// # Deprecated
///
/// Use [`Archive::entries()`] followed by `skip_solid()` instead.
///
/// # Returns
///
/// An iterator over the entries in the archive.
#[inline]
#[deprecated(
since = "0.28.1",
note = "Use `Archive::entries().skip_solid()` chain instead"
)]
pub fn entries_skip_solid(&mut self) -> impl Iterator<Item = io::Result<NormalEntry>> + '_ {
self.entries().skip_solid()
}
/// Returns an iterator over the entries in the archive, including entries in solid mode.
///
/// # Arguments
///
/// * `password` - a password for solid mode entry.
///
/// # Returns
///
/// An iterator over the entries in the archive.
#[inline]
pub fn entries_with_password<'a>(
&'a mut self,
password: Option<&'a [u8]>,
) -> impl Iterator<Item = io::Result<NormalEntry>> + 'a {
self.entries().extract_solid_entries(password)
}
/// Reads the next archive from the provided reader and returns a new [`Archive`].
///
/// # Arguments
///
/// * `reader` - The reader to read from.
///
/// # Returns
///
/// A new [`Archive`].
///
/// # Errors
///
/// Returns an error if an I/O error occurs while reading from the reader.
#[inline]
pub fn read_next_archive<OR: Read>(self, reader: OR) -> io::Result<Archive<OR>> {
let current_header = self.header;
let mut next = Archive::<OR>::read_header_with_buffer(reader, self.buf)?;
next.max_chunk_size = self.max_chunk_size;
if current_header.archive_number + 1 != next.header.archive_number {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"Next archive number must be +1 (current: {}, detected: {})",
current_header.archive_number, next.header.archive_number
),
));
}
Ok(next)
}
}
impl<R> Archive<R> {
/// Returns an iterator over the entries in the archive.
///
/// # 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::File::open("foo.pna")?;
/// let mut archive = Archive::read_header(file)?;
/// for entry in archive.entries() {
/// match entry? {
/// ReadEntry::Solid(_solid_entry) => {
/// // handle solid entry
/// }
/// ReadEntry::Normal(_entry) => {
/// // handle normal entry
/// }
/// }
/// }
/// # Ok(())
/// # }
/// ```
#[inline]
pub const fn entries(&mut self) -> Entries<'_, R> {
Entries::new(self)
}
}
#[cfg(feature = "unstable-async")]
impl<R: futures_io::AsyncRead + Unpin> Archive<R> {
/// Reads the archive header from the provided reader and returns a new [Archive].
/// This API is unstable.
///
/// # Errors
///
/// Returns an error if an I/O error occurs while reading the header from the reader.
#[inline]
pub async fn read_header_async(reader: R) -> io::Result<Self> {
Self::read_header_with_buffer_async(reader, Default::default()).await
}
async fn read_header_with_buffer_async(mut reader: R, buf: Vec<RawChunk>) -> io::Result<Self> {
read_pna_header_async(&mut reader).await?;
let mut chunk_reader = ChunkReader::new(&mut reader, None);
let chunk = chunk_reader.read_chunk_async().await?;
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(reader, header, buf))
}
async fn next_raw_item_async(&mut self) -> io::Result<Option<RawEntry>> {
let mut chunks = Vec::new();
swap(&mut self.buf, &mut chunks);
let mut reader = ChunkReader::new(&mut self.inner, self.max_chunk_size);
loop {
let chunk = reader.read_chunk_async().await?;
match chunk.ty {
ChunkType::FEND | ChunkType::SEND => {
chunks.push(chunk);
break;
}
ChunkType::ANXT => self.next_archive = true,
ChunkType::AEND => {
self.buf = chunks;
return Ok(None);
}
_ => chunks.push(chunk),
}
}
Ok(Some(RawEntry(chunks)))
}
/// Reads a [`ReadEntry`] from the archive.
/// This API is unstable.
///
/// # Errors
///
/// Returns an error if an I/O error occurs while reading from the archive.
#[inline]
pub async fn read_entry_async(&mut self) -> io::Result<Option<ReadEntry>> {
self.next_raw_item_async()
.await?
.map(TryInto::try_into)
.transpose()
}
}
pub(crate) struct RawEntries<'r, R>(&'r mut Archive<R>);
impl<R: Read> Iterator for RawEntries<'_, R> {
type Item = io::Result<RawEntry>;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.0.next_raw_item().transpose()
}
}
#[cfg(feature = "unstable-async")]
impl<R: futures_io::AsyncRead + Unpin> futures_util::Stream for RawEntries<'_, R> {
type Item = io::Result<RawEntry>;
#[inline]
fn poll_next(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
use futures_util::Future;
let this = self.get_mut();
let mut pinned = std::pin::pin!(this.0.next_raw_item_async());
pinned.as_mut().poll(cx).map(|it| it.transpose())
}
}
/// An iterator over the entries in the archive.
pub struct Entries<'r, R> {
reader: &'r mut Archive<R>,
}
impl<'r, R> Entries<'r, R> {
#[inline]
pub(crate) const fn new(reader: &'r mut Archive<R>) -> 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::File::open("foo.pna")?;
/// let mut archive = Archive::read_header(file)?;
/// for entry in archive.entries().extract_solid_entries(Some(b"password")) {
/// let mut reader = entry?.reader(ReadOptions::builder().build());
/// // process the entry
/// }
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn extract_solid_entries(self, password: Option<&'r [u8]>) -> NormalEntries<'r, R> {
NormalEntries::new(self.reader, password)
}
}
impl<'r, R: Read> Entries<'r, R> {
/// Returns an iterator over the entries in the archive, excluding entries in solid mode.
///
/// # Returns
///
/// An iterator over the entries in the archive.
#[inline]
pub fn skip_solid(self) -> impl Iterator<Item = io::Result<NormalEntry>> + 'r {
self.filter_map(|it| match it {
Ok(e) => match e {
ReadEntry::Solid(_) => None,
ReadEntry::Normal(r) => Some(Ok(r)),
},
Err(e) => Some(Err(e)),
})
}
}
impl<R: Read> Iterator for Entries<'_, R> {
type Item = io::Result<ReadEntry>;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.reader.read_entry().transpose()
}
}
#[cfg(feature = "unstable-async")]
impl<R: futures_io::AsyncRead + Unpin> futures_util::Stream for Entries<'_, R> {
type Item = io::Result<ReadEntry>;
#[inline]
fn poll_next(
self: std::pin::Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
use futures_util::Future;
let this = self.get_mut();
let mut pinned = std::pin::pin!(this.reader.read_entry_async());
pinned.as_mut().poll(cx).map(|it| it.transpose())
}
}
/// An iterator over the entries in the archive.
pub struct NormalEntries<'r, R> {
reader: &'r mut Archive<R>,
password: Option<&'r [u8]>,
solid_iter: Option<crate::entry::SolidIntoEntries>,
}
impl<'r, R> NormalEntries<'r, R> {
#[inline]
pub(crate) fn new(reader: &'r mut Archive<R>, password: Option<&'r [u8]>) -> Self {
Self {
reader,
password,
solid_iter: None,
}
}
}
impl<R: Read> Iterator for NormalEntries<'_, R> {
type Item = io::Result<NormalEntry>;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
loop {
if let Some(iter) = &mut self.solid_iter {
if let Some(item) = iter.next() {
return Some(item);
}
self.solid_iter = None;
}
match self.reader.read_entry() {
Ok(Some(ReadEntry::Normal(entry))) => return Some(Ok(entry)),
Ok(Some(ReadEntry::Solid(entry))) => match entry.into_entries(self.password) {
Ok(iter) => {
self.solid_iter = Some(iter);
continue;
}
Err(e) => return Some(Err(e)),
},
Ok(None) => return None,
Err(e) => return Some(Err(e)),
}
}
}
}
impl<R: Read + Seek> Archive<R> {
/// Seeks the cursor to the start of the end-of-archive marker.
///
/// # Errors
/// Returns an error if this function failed to seek or contains a broken chunk.
///
/// # Examples
/// For appending entry to the existing archive.
/// ```no_run
/// # use std::fs::File;
/// # use std::io;
/// # use libpna::*;
///
/// # fn main() -> io::Result<()> {
/// let file = File::open("foo.pna")?;
/// let mut archive = Archive::read_header(file)?;
/// archive.seek_to_end()?;
/// archive.add_entry({
/// let entry = EntryBuilder::new_dir("dir_entry".into());
/// entry.build()?
/// })?;
/// archive.finalize()?;
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn seek_to_end(&mut self) -> io::Result<()> {
let mut reader = ChunkReader::new(&mut self.inner, self.max_chunk_size);
let byte = loop {
let (ty, byte_length) = reader.skip_chunk()?;
if ty == ChunkType::AEND {
break byte_length;
} else if ty == ChunkType::ANXT {
self.next_archive = true;
}
};
self.inner.seek(SeekFrom::Current(-(byte as i64)))?;
Ok(())
}
}
#[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 decode() {
let file_bytes = include_bytes!("../../../resources/test/empty.pna");
let mut reader = Archive::read_header(&file_bytes[..]).unwrap();
let mut entries = reader.entries();
assert!(entries.next().is_none());
}
#[cfg(feature = "unstable-async")]
#[tokio::test]
async fn decode_async() {
use tokio_util::compat::TokioAsyncReadCompatExt;
let input = include_bytes!("../../../resources/test/zstd.pna");
let file = io::Cursor::new(input).compat();
let mut reader = Archive::read_header_async(file).await.unwrap();
assert!(reader.read_entry_async().await.unwrap().is_some());
assert!(reader.read_entry_async().await.unwrap().is_some());
assert!(reader.read_entry_async().await.unwrap().is_some());
assert!(reader.read_entry_async().await.unwrap().is_some());
assert!(reader.read_entry_async().await.unwrap().is_some());
assert!(reader.read_entry_async().await.unwrap().is_some());
assert!(reader.read_entry_async().await.unwrap().is_some());
assert!(reader.read_entry_async().await.unwrap().is_some());
assert!(reader.read_entry_async().await.unwrap().is_some());
assert!(reader.read_entry_async().await.unwrap().is_none());
}
#[cfg(feature = "unstable-async")]
#[tokio::test]
async fn extract_async() -> io::Result<()> {
use crate::ReadOptions;
use tokio_util::compat::{FuturesAsyncReadCompatExt, TokioAsyncReadCompatExt};
let input = include_bytes!("../../../resources/test/zstd.pna");
let file = io::Cursor::new(input).compat();
let mut archive = Archive::read_header_async(file).await?;
while let Some(entry) = archive.read_entry_async().await? {
match entry {
ReadEntry::Solid(solid_entry) => {
for entry in solid_entry.entries(None)? {
let entry = entry?;
let mut file = io::Cursor::new(Vec::new());
let mut reader = entry.reader(ReadOptions::builder().build())?.compat();
tokio::io::copy(&mut reader, &mut file).await?;
}
}
ReadEntry::Normal(entry) => {
let mut file = io::Cursor::new(Vec::new());
let mut reader = entry.reader(ReadOptions::builder().build())?.compat();
tokio::io::copy(&mut reader, &mut file).await?;
}
}
}
Ok(())
}
}