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
mod entry;
mod header;
mod read;
mod write;

use crate::chunk::RawChunk;
pub use entry::*;
pub use header::*;
pub use read::*;
pub use write::*;

/// An object providing access to a PNA file.
/// An instance of a [Archive] can be read and/or written depending on the [T].
///
/// # Examples
/// Creates a new PNA file and add entry to it.
/// ```no_run
/// # use libpna::{Archive, EntryBuilder, WriteOption};
/// # use std::fs::File;
/// # use std::io::{self, prelude::*};
///
/// # fn main() -> io::Result<()> {
/// let file = File::create("foo.pna")?;
/// let mut archive = Archive::write_header(file)?;
/// let mut entry_builder = EntryBuilder::new_file(
///     "bar.txt".try_into().unwrap(),
///     WriteOption::builder().build(),
/// )?;
/// entry_builder.write_all(b"content")?;
/// let entry = entry_builder.build()?;
/// archive.add_entry(entry)?;
/// archive.finalize()?;
/// #     Ok(())
/// # }
/// ```
///
/// Read the entries of a pna file.
/// ```no_run
/// # use libpna::{Archive, ReadOption};
/// # use std::fs::File;
/// # use std::io::{self, copy, prelude::*};
///
/// # fn main() -> io::Result<()> {
/// let file = File::open("foo.pna")?;
/// let mut archive = Archive::read_header(file)?;
/// for entry in archive.entries_skip_solid() {
///     let entry = entry?;
///     let mut file = File::create(entry.header().path().as_path())?;
///     let mut reader = entry.reader(ReadOption::builder().build())?;
///     copy(&mut reader, &mut file)?;
/// }
/// #     Ok(())
/// # }
/// ```
pub struct Archive<T> {
    inner: T,
    header: ArchiveHeader,
    // following fields are only use in reader mode
    next_archive: bool,
    buf: Vec<RawChunk>,
}

impl<T> Archive<T> {
    fn new(inner: T, header: ArchiveHeader) -> Self {
        Self::with_buffer(inner, header, Default::default())
    }

    fn with_buffer(inner: T, header: ArchiveHeader, buf: Vec<RawChunk>) -> Self {
        Self {
            inner,
            header,
            next_archive: false,
            buf,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::{self, Cursor, Write};

    #[test]
    fn store_archive() {
        archive(
            b"src data bytes",
            WriteOption::builder().compression(Compression::No).build(),
        )
        .unwrap()
    }

    #[test]
    fn deflate_archive() {
        archive(
            b"src data bytes",
            WriteOption::builder()
                .compression(Compression::Deflate)
                .build(),
        )
        .unwrap()
    }

    #[test]
    fn zstd_archive() {
        archive(
            b"src data bytes",
            WriteOption::builder()
                .compression(Compression::ZStandard)
                .build(),
        )
        .unwrap()
    }

    #[test]
    fn xz_archive() {
        archive(
            b"src data bytes",
            WriteOption::builder().compression(Compression::XZ).build(),
        )
        .unwrap();
    }

    #[test]
    fn store_with_aes_cbc_archive() {
        archive(
            b"plain text",
            WriteOption::builder()
                .compression(Compression::No)
                .encryption(Encryption::Aes)
                .cipher_mode(CipherMode::CBC)
                .password(Some("password"))
                .build(),
        )
        .unwrap();
    }

    #[test]
    fn zstd_with_aes_ctr_archive() {
        archive(
            b"plain text",
            WriteOption::builder()
                .compression(Compression::ZStandard)
                .encryption(Encryption::Aes)
                .cipher_mode(CipherMode::CTR)
                .password(Some("password"))
                .build(),
        )
        .unwrap();
    }

    #[test]
    fn zstd_with_aes_cbc_archive() {
        archive(
            b"plain text",
            WriteOption::builder()
                .compression(Compression::ZStandard)
                .encryption(Encryption::Aes)
                .cipher_mode(CipherMode::CBC)
                .password(Some("password"))
                .build(),
        )
        .unwrap();
    }

    #[test]
    fn zstd_with_camellia_ctr_archive() {
        archive(
            b"plain text",
            WriteOption::builder()
                .compression(Compression::ZStandard)
                .encryption(Encryption::Camellia)
                .cipher_mode(CipherMode::CTR)
                .password(Some("password"))
                .build(),
        )
        .unwrap();
    }

    #[test]
    fn zstd_with_camellia_cbc_archive() {
        archive(
            b"plain text",
            WriteOption::builder()
                .compression(Compression::ZStandard)
                .encryption(Encryption::Camellia)
                .cipher_mode(CipherMode::CBC)
                .password(Some("password"))
                .build(),
        )
        .unwrap();
    }

    #[test]
    fn xz_with_aes_cbc_archive() {
        archive(
            b"plain text",
            WriteOption::builder()
                .compression(Compression::XZ)
                .encryption(Encryption::Aes)
                .cipher_mode(CipherMode::CBC)
                .hash_algorithm(HashAlgorithm::Pbkdf2Sha256)
                .password(Some("password"))
                .build(),
        )
        .unwrap()
    }

    #[test]
    fn xz_with_camellia_cbc_archive() {
        archive(
            b"plain text",
            WriteOption::builder()
                .compression(Compression::XZ)
                .encryption(Encryption::Camellia)
                .cipher_mode(CipherMode::CBC)
                .hash_algorithm(HashAlgorithm::Pbkdf2Sha256)
                .password(Some("password"))
                .build(),
        )
        .unwrap()
    }

    fn create_archive(src: &[u8], options: WriteOption) -> io::Result<Vec<u8>> {
        let mut writer = Archive::write_header(Vec::with_capacity(src.len()))?;
        writer.add_entry({
            let mut builder = EntryBuilder::new_file("test/text".try_into().unwrap(), options)?;
            builder.write_all(src)?;
            builder.build()?
        })?;
        writer.finalize()
    }

    fn archive(src: &[u8], options: WriteOption) -> io::Result<()> {
        let archive = create_archive(src, options.clone())?;
        let mut archive_reader = Archive::read_header(Cursor::new(archive))?;
        let item = archive_reader.entries_skip_solid().next().unwrap().unwrap();
        let mut reader = item
            .reader(ReadOption::with_password(options.password))
            .unwrap();
        let mut dist = Vec::new();
        io::copy(&mut reader, &mut dist)?;
        assert_eq!(src, dist.as_slice());
        Ok(())
    }

    #[test]
    fn solid_entry() -> Result<(), Box<dyn std::error::Error>> {
        let archive = {
            let mut writer = Archive::write_header(Vec::new())?;
            let dir_entry = {
                let builder = EntryBuilder::new_dir("test".try_into().unwrap());
                builder.build().unwrap()
            };
            let file_entry = {
                let options = WriteOption::builder().build();
                let mut builder = EntryBuilder::new_file("test/text".try_into().unwrap(), options)?;
                builder.write_all("text".as_bytes())?;
                builder.build()?
            };
            writer.add_entry({
                let mut builder = SolidEntryBuilder::new(WriteOption::builder().build()).unwrap();
                builder.add_entry(dir_entry).unwrap();
                builder.add_entry(file_entry).unwrap();
                builder.build().unwrap()
            })?;
            writer.finalize().unwrap()
        };

        let mut archive_reader = Archive::read_header(Cursor::new(archive)).unwrap();
        let mut entries = archive_reader.entries_with_password(Some("password"));
        entries.next().unwrap().expect("failed to read entry");
        entries.next().unwrap().expect("failed to read entry");
        assert!(entries.next().is_none());
        Ok(())
    }

    #[test]
    fn copy_entry() {
        let archive = create_archive(b"archive text", WriteOption::builder().build())
            .expect("failed to create archive");
        let mut reader =
            Archive::read_header(Cursor::new(&archive)).expect("failed to read archive header");

        let mut writer = Archive::write_header(Vec::new()).expect("failed to write archive header");

        for entry in reader.entries_skip_solid() {
            writer
                .add_entry(entry.expect("failed to read entry"))
                .expect("failed to add entry");
        }
        assert_eq!(
            archive,
            writer.finalize().expect("failed to finish archive")
        )
    }

    #[test]
    fn append() {
        let buf = Vec::new();
        let cursor = Cursor::new(buf);
        let mut writer = Archive::write_header(cursor).unwrap();
        writer
            .add_entry({
                let builder = EntryBuilder::new_file(
                    EntryName::from_lossy("text1.txt"),
                    WriteOption::builder().build(),
                )
                .unwrap();
                builder.build().unwrap()
            })
            .unwrap();
        let result = writer.finalize().unwrap();

        let cursor = Cursor::new(result.into_inner());
        let mut appender = Archive::read_header(cursor).unwrap();
        appender.seek_to_end().unwrap();
        appender
            .add_entry({
                let builder = EntryBuilder::new_file(
                    EntryName::from_lossy("text2.txt"),
                    WriteOption::builder().build(),
                )
                .unwrap();
                builder.build().unwrap()
            })
            .unwrap();
        let appended = appender.finalize().unwrap();

        let cursor = Cursor::new(appended.into_inner());
        let mut reader = Archive::read_header(cursor).unwrap();

        let mut entries = reader.entries_skip_solid();
        assert!(entries.next().is_some());
        assert!(entries.next().is_some());
        assert!(entries.next().is_none());
    }
}