eazip 0.2.4

An simple yet flexible zip 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
use crate::{
    CompressionMethod, FileType, Timestamp,
    types::{self, Pod},
    utils::Counter,
};
use std::{
    collections::HashSet,
    fmt,
    io::{self, Write},
};

trait WriteExt: Write {
    fn write_pod<T: Pod>(&mut self, data: &T) -> io::Result<()> {
        self.write_all(data.as_bytes())
    }

    #[inline]
    fn write_all_many<const N: usize>(&mut self, data: [&[u8]; N]) -> io::Result<()> {
        self._write_all_many(&mut data.map(io::IoSlice::new))
    }

    fn _write_all_many(&mut self, mut bufs: &mut [io::IoSlice]) -> io::Result<()> {
        #[cold]
        fn write_zero() -> io::Error {
            io::Error::new(io::ErrorKind::WriteZero, "failed to write whole buffer")
        }

        io::IoSlice::advance_slices(&mut bufs, 0);
        while !bufs.is_empty() {
            match self.write_vectored(bufs) {
                Ok(0) => return Err(write_zero()),
                Ok(n) => io::IoSlice::advance_slices(&mut bufs, n),
                Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
                Err(e) => return Err(e),
            }
        }

        Ok(())
    }
}

impl<W: Write> WriteExt for W {}

#[allow(dead_code)]
#[derive(Debug, Clone, Copy)]
#[repr(C, packed(4))]
struct LocalZip64 {
    id: types::U16,
    size: types::U16,
    uncompressed_size: types::U64,
    compressed_size: types::U64,
}

unsafe impl Pod for LocalZip64 {}

#[allow(dead_code)]
#[derive(Debug, Clone, Copy)]
#[repr(C, packed(4))]
struct CentralZip64 {
    id: types::U16,
    size: types::U16,
    uncompressed_size: types::U64,
    compressed_size: types::U64,
    local_header_offset: types::U64,
}

unsafe impl Pod for CentralZip64 {}

#[allow(dead_code)]
#[derive(Debug, Clone, Copy)]
#[repr(C, packed)]
struct ExtendedTimestamp {
    id: types::U16,
    size: types::U16,
    flags: u8,
    timestamp: types::U32,
}

unsafe impl Pod for ExtendedTimestamp {}

impl ExtendedTimestamp {
    fn new(modified: Timestamp) -> Option<Self> {
        match modified.to_unix().try_into() {
            Ok(t) if t != 0 => Some(ExtendedTimestamp {
                id: types::U16::set(0x5455),
                size: types::U16::set(5),
                flags: 1,
                timestamp: types::U32::set(t),
            }),
            _ => None,
        }
    }
}

pub struct Metadata {
    pub compression_method: CompressionMethod,
    pub compressed_size: u64,
    pub uncompressed_size: u64,
    pub crc32: u32,
    pub typ: FileType,
    pub modified_at: Timestamp,
}

#[derive(Debug, Default)]
enum State {
    #[default]
    Default,
    Writing(u64),
}

#[derive(Default)]
pub struct RawArchiveWriter {
    state: State,
    entries: HashSet<Box<str>>,
    central_headers: Vec<u8>,
    position: u64,
}

impl fmt::Debug for RawArchiveWriter {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RawArchiveWriter")
            .field("state", &self.state)
            .field("entries", &self.entries)
            .field("position", &self.position)
            .finish()
    }
}

impl RawArchiveWriter {
    #[inline]
    fn start_writing(&mut self) -> io::Result<()> {
        #[cold]
        fn error() -> io::Error {
            io::Error::other("A non-recoverable error occurred or a file was not `finish`ed")
        }

        if let State::Writing(_) = self.state {
            return Err(error());
        }
        self.state = State::Writing(self.position);

        Ok(())
    }

    pub fn recover<W: io::Seek>(&mut self, mut writer: W) -> io::Result<()> {
        let State::Writing(pos) = self.state else {
            return Ok(());
        };

        writer.seek(io::SeekFrom::Start(pos))?;
        self.state = State::Default;
        self.position = pos;

        Ok(())
    }

    fn check_name(&self, name: &str) -> io::Result<Box<str>> {
        #[cold]
        fn invalid_name(msg: &str) -> io::Error {
            io::Error::new(io::ErrorKind::InvalidInput, msg)
        }

        if u16::try_from(name.len()).is_err() {
            return Err(invalid_name("file name too long"));
        }
        if self.entries.contains(name) {
            return Err(invalid_name("duplicated file name"));
        }

        crate::utils::validate_name(name).ok_or_else(|| invalid_name("invalid file name"))
    }

    pub fn write_file_raw<W: Write>(
        &mut self,
        writer: &mut W,
        name: &str,
        content: &[u8],
        meta: &Metadata,
    ) -> io::Result<()> {
        let name = self.check_name(name)?;

        self.start_writing()?;
        let mut counter = Counter::new(writer);

        self.write_local_header(&mut counter, &name, meta, false)?;
        counter.write_all(content)?;
        self.push_central_header(name, meta, false, self.position)?;

        self.position += counter.amt;
        self.state = State::Default;

        Ok(())
    }

    pub fn start_stream_raw<W: Write>(
        &mut self,
        writer: W,
        name: &str,
        options: &super::FileOptions,
    ) -> io::Result<RawFileStreamer<'_, W>> {
        let file_name = self.check_name(name)?;

        self.start_writing()?;
        let local_header_offset = self.position;
        let mut writer = Counter::new(writer);

        self.write_local_header(
            &mut writer,
            &file_name,
            &Metadata {
                compression_method: options.compression_method,
                compressed_size: 0,
                uncompressed_size: 0,
                crc32: 0,
                typ: FileType::File,
                modified_at: options.modified_at,
            },
            true,
        )?;

        Ok(RawFileStreamer {
            started_at: writer.amt,
            writer,

            file_name,
            local_header_offset,
            compression_method: options.compression_method,
            modified_at: options.modified_at,

            raw: self,
        })
    }

    fn write_local_header<W: Write>(
        &mut self,
        writer: &mut W,
        name: &str,
        meta: &Metadata,
        is_streaming: bool,
    ) -> io::Result<()> {
        let zip64 = LocalZip64 {
            id: types::U16::set(0x0001),
            size: types::U16::set(16),
            compressed_size: types::U64::set(meta.compressed_size),
            uncompressed_size: types::U64::set(meta.uncompressed_size),
        };

        let time = ExtendedTimestamp::new(meta.modified_at);
        let time = time.as_slice().as_bytes();

        let stream_flag = if is_streaming { 1 << 3 } else { 0 };

        writer.write_all_many([
            types::LocalFileHeader {
                signature: types::LocalFileHeader::SIGNATURE,
                required_version: types::U16::set(45),
                flags: types::U16::set((1 << 11) | stream_flag),
                compression_method: types::U16::set(meta.compression_method.0),
                last_modified_time: types::U16::set(0),
                last_modified_date: types::U16::set(0),
                crc32: types::U32::set(meta.crc32),
                compressed_size: types::U32::set(0xffff_ffff),
                uncompressed_size: types::U32::set(0xffff_ffff),
                file_name_length: types::U16::set(name.len() as u16),
                extra_fields_length: types::U16::set((size_of::<LocalZip64>() + time.len()) as _),
            }
            .as_bytes(),
            name.as_bytes(),
            zip64.as_bytes(),
            time,
        ])?;

        Ok(())
    }

    fn push_central_header(
        &mut self,
        name: Box<str>,
        meta: &Metadata,
        is_streaming: bool,
        local_header_offset: u64,
    ) -> io::Result<()> {
        self.central_headers.try_reserve(
            size_of::<types::CentralFileHeader>()
                + size_of::<CentralZip64>()
                + size_of::<ExtendedTimestamp>()
                + name.len(),
        )?;
        self.entries.try_reserve(1)?;

        debug_assert!(name.len() <= u16::MAX as usize);

        let zip64 = CentralZip64 {
            id: types::U16::set(0x0001),
            size: types::U16::set(24),
            compressed_size: types::U64::set(meta.compressed_size),
            uncompressed_size: types::U64::set(meta.uncompressed_size),
            local_header_offset: types::U64::set(local_header_offset),
        };

        let time = ExtendedTimestamp::new(meta.modified_at);
        let time = time.as_slice().as_bytes();

        let stream_flag = if is_streaming { 1 << 3 } else { 0 };

        let attributes = match meta.typ {
            FileType::File => (1 << 5) | (8 << 28),
            FileType::Directory => (1 << 4) | (4 << 28),
            FileType::Symlink => (0o777 << 16) | (10 << 28),
        };

        self.central_headers.extend_from_slice(
            types::CentralFileHeader {
                signature: types::CentralFileHeader::SIGNATURE,
                made_by: types::U16::set(0x0300),    // Unix
                version_needed: types::U16::set(45), // Version 4.5 for Zip64 support
                flags: types::U16::set((1 << 11) | stream_flag),
                compression_method: types::U16::set(meta.compression_method.0),
                last_modified_time: types::U16::set(0),
                last_modified_date: types::U16::set(0),
                crc32: types::U32::set(meta.crc32),
                compressed_size: types::U32::set(0xffff_ffff),
                uncompressed_size: types::U32::set(0xffff_ffff),
                file_name_length: types::U16::set(name.len() as _),
                extra_fields_length: types::U16::set((size_of::<CentralZip64>() + time.len()) as _),
                file_comment_length: types::U16::set(0),
                disk_number: types::U16::set(0),
                internal_attributes: types::U16::set(1), // "Binary Data" flag
                external_attributes: types::U32::set(attributes),
                local_header_offset: types::U32::set(0xffff_ffff),
            }
            .as_bytes(),
        );

        self.central_headers.extend_from_slice(name.as_bytes());
        self.central_headers.extend_from_slice(zip64.as_bytes());
        self.central_headers.extend_from_slice(time);

        self.entries.insert(name);

        Ok(())
    }

    pub fn finish<W: Write>(mut self, writer: &mut W) -> io::Result<()> {
        self.start_writing()?;

        let central_directory_offset = self.position;

        let central_directory_size = self.central_headers.len() as u64;
        let central_directory_64_offset = central_directory_offset + central_directory_size;

        let total_entries = types::U64::set(self.entries.len() as u64);

        writer.write_all_many([
            &self.central_headers,
            types::EndOfCentralDirectory64 {
                signature: types::EndOfCentralDirectory64::SIGNATURE,
                record_size: types::U64::set(44),
                made_by: types::U16::set(0x0300),    // Unix
                version_needed: types::U16::set(45), // Version 4.5 for Zip64 support
                disk_number: types::U32::set(0),
                disk_with_central_directory: types::U32::set(0),
                entries_on_this_disk: total_entries,
                total_entries,
                central_directory_size: types::U64::set(central_directory_size),
                central_directory_offset: types::U64::set(central_directory_offset),
            }
            .as_bytes(),
            types::EndOfCentralDirectory64Locator {
                signature: types::EndOfCentralDirectory64Locator::SIGNATURE,
                disk_with_central_directory: types::U32::set(0),
                central_directory_64_offset: types::U64::set(central_directory_64_offset),
                total_disks: types::U32::set(1),
            }
            .as_bytes(),
            types::EndOfCentralDirectory {
                signature: types::EndOfCentralDirectory::SIGNATURE,
                disk_number: types::U16::set(0),
                disk_with_central_directory: types::U16::set(0),
                entries_on_this_disk: types::U16::set(0xffff),
                total_entries: types::U16::set(0xffff),
                central_directory_size: types::U32::set(0xffff_ffff),
                central_directory_offset: types::U32::set(0xffff_ffff),
                comment_length: types::U16::set(0),
            }
            .as_bytes(),
        ])?;

        Ok(())
    }
}

pub struct RawFileStreamer<'a, W: Write> {
    started_at: u64,
    writer: Counter<W>,

    file_name: Box<str>,
    local_header_offset: u64,
    compression_method: CompressionMethod,
    modified_at: Timestamp,

    raw: &'a mut RawArchiveWriter,
}

impl<W: Write> Write for RawFileStreamer<'_, W> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.writer.write(buf)
    }

    fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
        self.writer.write_vectored(bufs)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.writer.flush()
    }
}

impl<W: Write> RawFileStreamer<'_, W> {
    pub fn finish(mut self, uncompressed_size: u64, crc32: u32) -> io::Result<()> {
        let compressed_size = self.writer.amt - self.started_at;

        self.writer.write_pod(&types::DataDescriptor64 {
            signature: types::DataDescriptor64::SIGNATURE,
            crc32: types::U32::set(crc32),
            compressed_size: types::U64::set(compressed_size),
            uncompressed_size: types::U64::set(uncompressed_size),
        })?;
        self.raw.position += self.writer.amt;

        self.raw.push_central_header(
            self.file_name,
            &Metadata {
                compression_method: self.compression_method,
                compressed_size,
                uncompressed_size,
                crc32,
                typ: FileType::File,
                modified_at: self.modified_at,
            },
            true,
            self.local_header_offset,
        )?;

        self.raw.state = State::Default;

        Ok(())
    }
}