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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
use crate::{
archive::{Archive, ArchiveHeader, PNA_HEADER, SolidArchive},
chunk::{Chunk, ChunkExt, ChunkStreamWriter, ChunkType, RawChunk},
cipher::CipherWriter,
compress::CompressionWriter,
entry::{
Entry, EntryHeader, EntryName, EntryPart, Metadata, NormalEntry, SealedEntryExt,
SolidHeader, WriteCipher, WriteOption, WriteOptions, get_writer, get_writer_context,
},
io::TryIntoInner,
};
#[cfg(feature = "unstable-async")]
use futures_io::AsyncWrite;
#[cfg(feature = "unstable-async")]
use futures_util::AsyncWriteExt;
use std::io::{self, Write};
/// Internal Writer type alias.
pub(crate) type InternalDataWriter<W> = CompressionWriter<CipherWriter<W>>;
/// Internal Writer type alias.
pub(crate) type InternalArchiveDataWriter<W> = InternalDataWriter<ChunkStreamWriter<W>>;
/// Writer that compresses and encrypts according to the given options.
pub struct EntryDataWriter<W: Write>(InternalArchiveDataWriter<W>);
impl<W: Write> Write for EntryDataWriter<W> {
#[inline]
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
self.0.flush()
}
}
pub struct SolidArchiveEntryDataWriter<'w, W: Write>(
InternalArchiveDataWriter<&'w mut InternalArchiveDataWriter<W>>,
);
impl<W: Write> Write for SolidArchiveEntryDataWriter<'_, W> {
#[inline]
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.write(buf)
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
self.0.flush()
}
}
impl<W: Write> Archive<W> {
/// Writes the archive header to the given `Write` object and return a new [Archive].
///
/// # Arguments
///
/// * `write` - The [Write] object to write the header to.
///
/// # Returns
///
/// A new [`io::Result<Archive<W>>`]
///
/// # Examples
///
/// ```no_run
/// use libpna::Archive;
/// use std::fs;
/// # use std::io;
///
/// # fn main() -> io::Result<()> {
/// let file = fs::File::create("example.pna")?;
/// let mut archive = Archive::write_header(file)?;
/// archive.finalize()?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if an I/O error occurs while writing header to the writer.
#[inline]
pub fn write_header(write: W) -> io::Result<Self> {
let header = ArchiveHeader::new(0, 0, 0);
Self::write_header_with(write, header)
}
#[inline]
fn write_header_with(mut write: W, header: ArchiveHeader) -> io::Result<Self> {
write.write_all(PNA_HEADER)?;
(ChunkType::AHED, header.to_bytes()).write_chunk_in(&mut write)?;
Ok(Self::new(write, header))
}
/// Writes a regular file as a normal entry into the archive.
///
/// # Examples
/// ```no_run
/// use libpna::{Archive, Metadata, WriteOptions};
/// # use std::error::Error;
/// use std::fs;
/// use std::io::{self, prelude::*};
///
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let file = fs::File::create("foo.pna")?;
/// let mut archive = Archive::write_header(file)?;
/// archive.write_file(
/// "bar.txt".into(),
/// Metadata::new(),
/// WriteOptions::builder().build(),
/// |writer| writer.write_all(b"text"),
/// )?;
/// archive.finalize()?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if an I/O error occurs while writing the entry, or if the closure returns an error.
#[inline]
pub fn write_file<F>(
&mut self,
name: EntryName,
metadata: Metadata,
option: impl WriteOption,
mut f: F,
) -> io::Result<()>
where
F: FnMut(&mut EntryDataWriter<&mut W>) -> io::Result<()>,
{
write_file_entry(&mut self.inner, name, metadata, option, |w| {
let mut w = EntryDataWriter(w);
f(&mut w)?;
Ok(w.0)
})
}
/// Adds a new entry to the archive.
///
/// # Arguments
///
/// * `entry` - The entry to add to the archive.
///
/// # Examples
///
/// ```no_run
/// use libpna::{Archive, EntryBuilder, WriteOptions};
/// use std::fs;
/// # use std::io;
///
/// # fn main() -> io::Result<()> {
/// let file = fs::File::create("example.pna")?;
/// let mut archive = Archive::write_header(file)?;
/// archive.add_entry(
/// EntryBuilder::new_file("example.txt".into(), WriteOptions::builder().build())?.build()?,
/// )?;
/// archive.finalize()?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if an I/O error occurs while writing a given entry.
#[inline]
pub fn add_entry(&mut self, entry: impl Entry) -> io::Result<usize> {
entry.write_in(&mut self.inner)
}
/// Adds a part of an entry to the archive.
///
/// # Arguments
///
/// * `entry_part` - The part of an entry to add to the archive.
///
/// # Examples
///
/// ```no_run
/// # use libpna::{Archive, EntryBuilder, EntryPart, WriteOptions};
/// # use std::fs::File;
/// # use std::io;
///
/// # fn main() -> io::Result<()> {
/// let part1_file = File::create("example.part1.pna")?;
/// let mut archive_part1 = Archive::write_header(part1_file)?;
/// let entry =
/// EntryBuilder::new_file("example.txt".into(), WriteOptions::builder().build())?.build()?;
/// archive_part1.add_entry_part(EntryPart::from(entry))?;
///
/// let part2_file = File::create("example.part2.pna")?;
/// let archive_part2 = archive_part1.split_to_next_archive(part2_file)?;
/// archive_part2.finalize()?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if an I/O error occurs while writing the entry part.
#[inline]
pub fn add_entry_part<T>(&mut self, entry_part: EntryPart<T>) -> io::Result<usize>
where
RawChunk<T>: Chunk,
{
let mut written_len = 0;
for chunk in entry_part.0 {
written_len += chunk.write_chunk_in(&mut self.inner)?;
}
Ok(written_len)
}
#[inline]
fn add_next_archive_marker(&mut self) -> io::Result<usize> {
(ChunkType::ANXT, []).write_chunk_in(&mut self.inner)
}
/// Split to the next archive.
///
/// # Examples
/// ```no_run
/// # use libpna::{Archive, EntryBuilder, EntryPart, WriteOptions};
/// # use std::fs::File;
/// # use std::io;
///
/// # fn main() -> io::Result<()> {
/// let part1_file = File::create("example.part1.pna")?;
/// let mut archive_part1 = Archive::write_header(part1_file)?;
/// let entry =
/// EntryBuilder::new_file("example.txt".into(), WriteOptions::builder().build())?.build()?;
/// archive_part1.add_entry_part(EntryPart::from(entry))?;
///
/// let part2_file = File::create("example.part2.pna")?;
/// let archive_part2 = archive_part1.split_to_next_archive(part2_file)?;
/// archive_part2.finalize()?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if an I/O error occurs while splitting to the next archive.
#[inline]
pub fn split_to_next_archive<OW: Write>(mut self, writer: OW) -> io::Result<Archive<OW>> {
let next_archive_number = self.header.archive_number + 1;
let header = ArchiveHeader::new(0, 0, next_archive_number);
self.add_next_archive_marker()?;
self.finalize()?;
Archive::write_header_with(writer, header)
}
/// Writes the end-of-archive marker and finalizes the archive.
///
/// Marks that the PNA archive contains no more entries.
/// Normally, a PNA archive reader will continue reading entries in the hope that the entry exists until it encounters this end marker.
/// This end marker should always be recorded at the end of the file unless there is a special reason to do so.
///
/// # Examples
/// Creates an empty archive.
/// ```no_run
/// # use std::io;
/// # use std::fs::File;
/// # use libpna::Archive;
///
/// # fn main() -> io::Result<()> {
/// let file = File::create("foo.pna")?;
/// let mut archive = Archive::write_header(file)?;
/// archive.finalize()?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
/// Returns an error if writing the end-of-archive marker fails.
#[inline]
#[must_use = "archive is not complete until finalize succeeds"]
pub fn finalize(mut self) -> io::Result<W> {
(ChunkType::AEND, []).write_chunk_in(&mut self.inner)?;
Ok(self.inner)
}
}
#[cfg(feature = "unstable-async")]
impl<W: AsyncWrite + Unpin> Archive<W> {
/// Writes the archive header to the given object and return a new [Archive].
/// This API is unstable.
///
/// # Errors
///
/// Returns an error if an I/O error occurs while writing header to the writer.
#[inline]
pub async fn write_header_async(write: W) -> io::Result<Self> {
let header = ArchiveHeader::new(0, 0, 0);
Self::write_header_with_async(write, header).await
}
#[inline]
async fn write_header_with_async(mut write: W, header: ArchiveHeader) -> io::Result<Self> {
write.write_all(PNA_HEADER).await?;
let mut chunk_writer = crate::chunk::ChunkWriter::new(&mut write);
chunk_writer
.write_chunk_async((ChunkType::AHED, header.to_bytes()))
.await?;
Ok(Self::new(write, header))
}
/// Adds a new entry to the archive.
/// This API is unstable.
///
/// # Errors
///
/// Returns an error if an I/O error occurs while writing a given entry.
#[inline]
pub async fn add_entry_async(&mut self, entry: impl Entry) -> io::Result<usize> {
let mut bytes = Vec::new();
entry.write_in(&mut bytes)?;
self.inner.write_all(&bytes).await?;
Ok(bytes.len())
}
/// Writes the end-of-archive marker and finalizes the archive.
/// This API is unstable.
///
/// # Errors
///
/// Returns an error if writing the end-of-archive marker fails.
#[inline]
pub async fn finalize_async(mut self) -> io::Result<W> {
let mut chunk_writer = crate::chunk::ChunkWriter::new(&mut self.inner);
chunk_writer
.write_chunk_async((ChunkType::AEND, []))
.await?;
Ok(self.inner)
}
}
impl<W: Write> Archive<W> {
/// Writes the archive header to the given `Write` object and return a new [SolidArchive].
///
/// # Arguments
///
/// * `write` - The [Write] object to write the header to.
/// * `option` - The [WriteOptions] object of a solid mode option.
///
/// # Returns
///
/// A new [`io::Result<SolidArchive<W>>`]
///
/// # Examples
///
/// ```no_run
/// use libpna::{Archive, WriteOptions};
/// use std::fs::File;
/// # use std::io;
///
/// # fn main() -> io::Result<()> {
/// let option = WriteOptions::builder().build();
/// let file = File::create("example.pna")?;
/// let mut archive = Archive::write_solid_header(file, option)?;
/// archive.finalize()?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if an I/O error occurs while writing header to the writer.
#[inline]
pub fn write_solid_header(write: W, option: impl WriteOption) -> io::Result<SolidArchive<W>> {
let archive = Self::write_header(write)?;
archive.into_solid_archive(option)
}
#[inline]
fn into_solid_archive(mut self, option: impl WriteOption) -> io::Result<SolidArchive<W>> {
let header = SolidHeader::new(
option.compression(),
option.encryption(),
option.cipher_mode(),
);
let context = get_writer_context(option)?;
(ChunkType::SHED, header.to_bytes()).write_chunk_in(&mut self.inner)?;
if let Some(WriteCipher { context: c, .. }) = &context.cipher {
(ChunkType::PHSF, c.phsf.as_bytes()).write_chunk_in(&mut self.inner)?;
(ChunkType::SDAT, c.iv.as_slice()).write_chunk_in(&mut self.inner)?;
}
self.inner.flush()?;
let writer = get_writer(
ChunkStreamWriter::new(ChunkType::SDAT, self.inner),
&context,
)?;
Ok(SolidArchive {
archive_header: self.header,
inner: writer,
})
}
}
impl<W: Write> SolidArchive<W> {
/// Adds a new entry to the archive.
///
/// # Arguments
///
/// * `entry` - The entry to add to the archive.
///
/// # Examples
///
/// ```no_run
/// use libpna::{Archive, EntryBuilder, WriteOptions};
/// use std::fs::File;
/// # use std::io;
///
/// # fn main() -> io::Result<()> {
/// let option = WriteOptions::builder().build();
/// let file = File::create("example.pna")?;
/// let mut archive = Archive::write_solid_header(file, option)?;
/// archive
/// .add_entry(EntryBuilder::new_file("example.txt".into(), WriteOptions::store())?.build()?)?;
/// archive.finalize()?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns an error if an I/O error occurs while writing a given entry.
#[inline]
pub fn add_entry<T>(&mut self, entry: NormalEntry<T>) -> io::Result<usize>
where
NormalEntry<T>: Entry,
{
entry.write_in(&mut self.inner)
}
/// Writes a regular file as a solid entry into the archive.
///
/// # Errors
///
/// Returns an error if an I/O error occurs while writing the entry, or if the closure returns an error.
///
/// # Examples
/// ```no_run
/// use libpna::{Archive, Metadata, WriteOptions};
/// # use std::error::Error;
/// use std::fs;
/// use std::io::{self, prelude::*};
///
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let file = fs::File::create("foo.pna")?;
/// let option = WriteOptions::builder().build();
/// let mut archive = Archive::write_solid_header(file, option)?;
/// archive.write_file("bar.txt".into(), Metadata::new(), |writer| {
/// writer.write_all(b"text")
/// })?;
/// archive.finalize()?;
/// # Ok(())
/// # }
/// ```
#[inline]
pub fn write_file<F>(&mut self, name: EntryName, metadata: Metadata, mut f: F) -> io::Result<()>
where
F: FnMut(&mut SolidArchiveEntryDataWriter<W>) -> io::Result<()>,
{
let option = WriteOptions::store();
write_file_entry(&mut self.inner, name, metadata, option, |w| {
let mut w = SolidArchiveEntryDataWriter(w);
f(&mut w)?;
Ok(w.0)
})
}
/// Writes the end-of-archive marker and finalizes the archive.
///
/// Marks that the PNA archive contains no more entries.
/// Normally, a PNA archive reader will continue reading entries in the hope that the entry exists until it encounters this end marker.
/// This end marker should always be recorded at the end of the file unless there is a special reason to do so.
///
/// # Errors
/// Returns an error if writing the end-of-archive marker fails.
///
/// # Examples
/// Creates an empty archive.
/// ```no_run
/// use libpna::{Archive, WriteOptions};
/// use std::fs::File;
/// # use std::io;
///
/// # fn main() -> io::Result<()> {
/// let option = WriteOptions::builder().build();
/// let file = File::create("example.pna")?;
/// let mut archive = Archive::write_solid_header(file, option)?;
/// archive.finalize()?;
/// # Ok(())
/// # }
/// ```
#[inline]
#[must_use = "archive is not complete until finalize succeeds"]
pub fn finalize(self) -> io::Result<W> {
let archive = self.finalize_solid_entry()?;
archive.finalize()
}
#[inline]
fn finalize_solid_entry(mut self) -> io::Result<Archive<W>> {
self.inner.flush()?;
let mut inner = self.inner.try_into_inner()?.try_into_inner()?.into_inner();
(ChunkType::SEND, []).write_chunk_in(&mut inner)?;
Ok(Archive::new(inner, self.archive_header))
}
}
pub(crate) fn write_file_entry<W, F>(
inner: &mut W,
name: EntryName,
metadata: Metadata,
option: impl WriteOption,
mut f: F,
) -> io::Result<()>
where
W: Write,
F: FnMut(InternalArchiveDataWriter<&mut W>) -> io::Result<InternalArchiveDataWriter<&mut W>>,
{
let header = EntryHeader::for_file(
option.compression(),
option.encryption(),
option.cipher_mode(),
name,
);
(ChunkType::FHED, header.to_bytes()).write_chunk_in(inner)?;
if let Some(c) = metadata.created {
(ChunkType::cTIM, c.whole_seconds().to_be_bytes()).write_chunk_in(inner)?;
if c.subsec_nanoseconds() != 0 {
(ChunkType::cTNS, c.subsec_nanoseconds().to_be_bytes()).write_chunk_in(inner)?;
}
}
if let Some(m) = metadata.modified {
(ChunkType::mTIM, m.whole_seconds().to_be_bytes()).write_chunk_in(inner)?;
if m.subsec_nanoseconds() != 0 {
(ChunkType::mTNS, m.subsec_nanoseconds().to_be_bytes()).write_chunk_in(inner)?;
}
}
if let Some(a) = metadata.accessed {
(ChunkType::aTIM, a.whole_seconds().to_be_bytes()).write_chunk_in(inner)?;
if a.subsec_nanoseconds() != 0 {
(ChunkType::aTNS, a.subsec_nanoseconds().to_be_bytes()).write_chunk_in(inner)?;
}
}
if let Some(p) = metadata.permission {
(ChunkType::fPRM, p.to_bytes()).write_chunk_in(inner)?;
}
let context = get_writer_context(option)?;
if let Some(WriteCipher { context: c, .. }) = &context.cipher {
(ChunkType::PHSF, c.phsf.as_bytes()).write_chunk_in(inner)?;
(ChunkType::FDAT, &c.iv[..]).write_chunk_in(inner)?;
}
let inner = {
let writer = ChunkStreamWriter::new(ChunkType::FDAT, inner);
let writer = get_writer(writer, &context)?;
let mut writer = f(writer)?;
writer.flush()?;
writer.try_into_inner()?.try_into_inner()?.into_inner()
};
(ChunkType::FEND, Vec::<u8>::new()).write_chunk_in(inner)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ReadOptions;
use std::io::Read;
#[cfg(all(target_family = "wasm", target_os = "unknown"))]
use wasm_bindgen_test::wasm_bindgen_test as test;
#[test]
fn encode() {
let writer = Archive::write_header(Vec::new()).expect("failed to write header");
let file = writer.finalize().expect("failed to finalize");
let expected = include_bytes!("../../../resources/test/empty.pna");
assert_eq!(file.as_slice(), expected.as_slice());
}
#[test]
fn archive_write_file_entry() {
let option = WriteOptions::builder().build();
let mut writer = Archive::write_header(Vec::new()).expect("failed to write header");
writer
.write_file(
EntryName::from_lossy("text.txt"),
Metadata::new(),
option,
|writer| writer.write_all(b"text"),
)
.expect("failed to write");
let file = writer.finalize().expect("failed to finalize");
let mut reader = Archive::read_header(&file[..]).expect("failed to read archive");
let mut entries = reader.entries_with_password(None);
let entry = entries
.next()
.expect("failed to get entry")
.expect("failed to read entry");
let mut data_reader = entry
.reader(ReadOptions::builder().build())
.expect("failed to read entry data");
let mut data = Vec::new();
data_reader
.read_to_end(&mut data)
.expect("failed to read data");
assert_eq!(&data[..], b"text");
}
#[test]
fn solid_write_file_entry() {
let option = WriteOptions::builder().build();
let mut writer =
Archive::write_solid_header(Vec::new(), option).expect("failed to write header");
writer
.write_file(
EntryName::from_lossy("text.txt"),
Metadata::new(),
|writer| writer.write_all(b"text"),
)
.expect("failed to write");
let file = writer.finalize().expect("failed to finalize");
let mut reader = Archive::read_header(&file[..]).expect("failed to read archive");
let mut entries = reader.entries_with_password(None);
let entry = entries
.next()
.expect("failed to get entry")
.expect("failed to read entry");
let mut data_reader = entry
.reader(ReadOptions::builder().build())
.expect("failed to read entry data");
let mut data = Vec::new();
data_reader
.read_to_end(&mut data)
.expect("failed to read data");
assert_eq!(&data[..], b"text");
}
#[cfg(feature = "unstable-async")]
#[tokio::test]
async fn encode_async() {
use tokio_util::compat::TokioAsyncWriteCompatExt;
let archive_bytes = {
let file = Vec::new().compat_write();
let writer = Archive::write_header_async(file).await.unwrap();
writer.finalize_async().await.unwrap().into_inner()
};
let expected = include_bytes!("../../../resources/test/empty.pna");
assert_eq!(archive_bytes.as_slice(), expected.as_slice());
}
}