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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
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,
};
use core::num::NonZeroU32;
#[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 returns 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,
self.max_chunk_size,
|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)
}
/// Splits 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);
let max_chunk_size = self.max_chunk_size;
self.add_next_archive_marker()?;
self.finalize()?;
let mut archive = Archive::write_header_with(writer, header)?;
archive.max_chunk_size = max_chunk_size;
Ok(archive)
}
/// 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 returns 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 returns 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 max_chunk_size = self.max_chunk_size;
let writer = get_writer(
ChunkStreamWriter::new(ChunkType::SDAT, self.inner, max_chunk_size),
&context,
)?;
Ok(SolidArchive {
archive_header: self.header,
inner: writer,
max_chunk_size: None,
})
}
}
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,
self.max_chunk_size,
|w| {
let mut w = SolidArchiveEntryDataWriter(w);
f(&mut w)?;
Ok(w.0)
},
)
}
/// Sets the maximum chunk size for file data (FDAT) written via
/// [`write_file()`](SolidArchive::write_file).
///
/// This controls the inner FDAT chunk splitting for individual entries within
/// the solid stream. The outer SDAT chunk size is fixed when `SolidArchive` is
/// constructed and cannot be changed afterward. To control the outer SDAT chunk
/// size, call [`Archive::set_max_chunk_size`] before
/// [`write_solid_header()`](Archive::write_solid_header).
///
/// Pre-built entries added via [`add_entry()`](SolidArchive::add_entry) use their own
/// chunk size configured through [`EntryBuilder::max_chunk_size()`](crate::EntryBuilder::max_chunk_size).
#[inline]
pub fn set_max_file_chunk_size(&mut self, size: NonZeroU32) {
self.max_chunk_size = Some(size);
}
/// 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,
max_chunk_size: Option<NonZeroU32>,
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, max_chunk_size);
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");
}
fn count_chunks(archive: &[u8], ty: ChunkType) -> usize {
crate::chunk::read_chunks_from_slice(archive)
.unwrap()
.filter(|c| c.as_ref().unwrap().ty() == ty)
.count()
}
#[test]
fn archive_write_file_with_max_chunk_size() {
let option = WriteOptions::builder().build();
let mut writer = Archive::write_header(Vec::new()).expect("failed to write header");
writer.set_max_chunk_size(NonZeroU32::new(8).unwrap());
let large_data = b"abcdefghijklmnopqrstuvwxyz";
writer
.write_file(
EntryName::from_lossy("large.txt"),
Metadata::new(),
option,
|writer| writer.write_all(large_data),
)
.expect("failed to write");
let file = writer.finalize().expect("failed to finalize");
let fdat_count = count_chunks(&file, ChunkType::FDAT);
assert!(
fdat_count >= 4,
"26 bytes with max_chunk_size=8 should produce at least 4 FDAT chunks, got {fdat_count}"
);
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[..], large_data);
}
#[test]
fn solid_archive_write_file_with_max_chunk_size() {
let option = WriteOptions::builder().build();
let mut archive = Archive::write_header(Vec::new()).expect("failed to write header");
archive.set_max_chunk_size(NonZeroU32::new(8).unwrap());
let mut writer = archive
.into_solid_archive(option)
.expect("failed to create solid archive");
let large_data = b"abcdefghijklmnopqrstuvwxyz";
writer
.write_file(
EntryName::from_lossy("large.txt"),
Metadata::new(),
|writer| writer.write_all(large_data),
)
.expect("failed to write");
let file = writer.finalize().expect("failed to finalize");
// Outer SDAT chunks should be split by max_chunk_size
let sdat_count = count_chunks(&file, ChunkType::SDAT);
assert!(
sdat_count >= 2,
"outer SDAT should be split with max_chunk_size=8, got {sdat_count}"
);
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[..], large_data);
}
#[test]
fn solid_archive_set_max_file_chunk_size_after_creation() {
let option = WriteOptions::builder().build();
let mut writer =
Archive::write_solid_header(Vec::new(), option).expect("failed to write header");
writer.set_max_file_chunk_size(NonZeroU32::new(8).unwrap());
let large_data = b"abcdefghijklmnopqrstuvwxyz";
writer
.write_file(
EntryName::from_lossy("large.txt"),
Metadata::new(),
|writer| writer.write_all(large_data),
)
.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[..], large_data);
}
#[test]
fn split_to_next_archive_preserves_max_chunk_size() {
let option = WriteOptions::builder().build();
let mut writer = Archive::write_header(Vec::new()).expect("failed to write header");
writer.set_max_chunk_size(NonZeroU32::new(8).unwrap());
let next_writer = writer
.split_to_next_archive(Vec::new())
.expect("failed to split");
let large_data = b"abcdefghijklmnopqrstuvwxyz";
let mut next_writer = next_writer;
next_writer
.write_file(
EntryName::from_lossy("large.txt"),
Metadata::new(),
option,
|writer| writer.write_all(large_data),
)
.expect("failed to write");
let file = next_writer.finalize().expect("failed to finalize");
let fdat_count = count_chunks(&file, ChunkType::FDAT);
assert!(
fdat_count >= 4,
"max_chunk_size should be preserved across split, got {fdat_count} FDAT chunks"
);
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[..], large_data);
}
#[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());
}
}