Debian Codegraph @

third_party/rust/zip/src/spec.rs

raw
1 #![macro_use]
2
3 use crate::result::{ZipError, ZipResult};
4 use memchr::memmem::FinderRev;
5 use std::borrow::Cow;
6 use std::io;
7 use std::io::prelude::*;
8 use std::mem;
9 use std::path::{Component, Path, MAIN_SEPARATOR};
10
11 /// "Magic" header values used in the zip spec to locate metadata records.
12 ///
13 /// These values currently always take up a fixed four bytes, so we can parse and wrap them in this
14 /// struct to enforce some small amount of type safety.
15 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
16 #[repr(transparent)]
17 pub(crate) struct Magic(u32);
18
19 impl Magic {
20 pub const fn literal(x: u32) -> Self {
21 Self(x)
22 }
23
24 #[inline(always)]
25 pub const fn from_le_bytes(bytes: [u8; 4]) -> Self {
26 Self(u32::from_le_bytes(bytes))
27 }
28
29 #[inline(always)]
30 pub fn from_first_le_bytes(data: &[u8]) -> Self {
31 let first_bytes: [u8; 4] = data[..mem::size_of::<Self>()].try_into().unwrap();
32 Self::from_le_bytes(first_bytes)
33 }
34
35 #[inline(always)]
36 pub const fn to_le_bytes(self) -> [u8; 4] {
37 self.0.to_le_bytes()
38 }
39
40 #[allow(clippy::wrong_self_convention)]
41 #[inline(always)]
42 pub fn from_le(self) -> Self {
43 Self(u32::from_le(self.0))
44 }
45
46 #[allow(clippy::wrong_self_convention)]
47 #[inline(always)]
48 pub fn to_le(self) -> Self {
49 Self(u32::to_le(self.0))
50 }
51
52 pub const LOCAL_FILE_HEADER_SIGNATURE: Self = Self::literal(0x04034b50);
53 pub const CENTRAL_DIRECTORY_HEADER_SIGNATURE: Self = Self::literal(0x02014b50);
54 pub const CENTRAL_DIRECTORY_END_SIGNATURE: Self = Self::literal(0x06054b50);
55 pub const ZIP64_CENTRAL_DIRECTORY_END_SIGNATURE: Self = Self::literal(0x06064b50);
56 pub const ZIP64_CENTRAL_DIRECTORY_END_LOCATOR_SIGNATURE: Self = Self::literal(0x07064b50);
57 }
58
59 /// Similar to [`Magic`], but used for extra field tags as per section 4.5.3 of APPNOTE.TXT.
60 #[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
61 #[repr(transparent)]
62 pub(crate) struct ExtraFieldMagic(u16);
63
64 /* TODO: maybe try to use this for parsing extra fields as well as writing them? */
65 #[allow(dead_code)]
66 impl ExtraFieldMagic {
67 pub const fn literal(x: u16) -> Self {
68 Self(x)
69 }
70
71 #[inline(always)]
72 pub const fn from_le_bytes(bytes: [u8; 2]) -> Self {
73 Self(u16::from_le_bytes(bytes))
74 }
75
76 #[inline(always)]
77 pub const fn to_le_bytes(self) -> [u8; 2] {
78 self.0.to_le_bytes()
79 }
80
81 #[allow(clippy::wrong_self_convention)]
82 #[inline(always)]
83 pub fn from_le(self) -> Self {
84 Self(u16::from_le(self.0))
85 }
86
87 #[allow(clippy::wrong_self_convention)]
88 #[inline(always)]
89 pub fn to_le(self) -> Self {
90 Self(u16::to_le(self.0))
91 }
92
93 pub const ZIP64_EXTRA_FIELD_TAG: Self = Self::literal(0x0001);
94 }
95
96 /// This should be equal to `0xFFFFFFFF`.
97 pub const ZIP64_BYTES_THR: u64 = u32::MAX as u64;
98 pub const ZIP64_ENTRY_THR: usize = u16::MAX as usize;
99
100 pub(crate) trait FixedSizeBlock: Sized + Copy {
101 const MAGIC: Magic;
102
103 fn magic(self) -> Magic;
104
105 const WRONG_MAGIC_ERROR: ZipError;
106
107 /* TODO: use smallvec? */
108 fn interpret(bytes: &[u8]) -> ZipResult<Self> {
109 if bytes.len() != mem::size_of::<Self>() {
110 return Err(ZipError::InvalidArchive("Block is wrong size"));
111 }
112 let block_ptr: *const Self = bytes.as_ptr().cast();
113 let block = unsafe { block_ptr.read() }.from_le();
114 if block.magic() != Self::MAGIC {
115 return Err(Self::WRONG_MAGIC_ERROR);
116 }
117 Ok(block)
118 }
119
120 #[allow(clippy::wrong_self_convention)]
121 fn from_le(self) -> Self;
122
123 fn parse<T: Read>(reader: &mut T) -> ZipResult<Self> {
124 let mut block = vec![0u8; mem::size_of::<Self>()].into_boxed_slice();
125 reader.read_exact(&mut block)?;
126 Self::interpret(&block)
127 }
128
129 fn encode(self) -> Box<[u8]> {
130 self.to_le().serialize()
131 }
132
133 fn to_le(self) -> Self;
134
135 /* TODO: use Box<[u8; mem::size_of::<Self>()]> when generic_const_exprs are stabilized! */
136 fn serialize(self) -> Box<[u8]> {
137 /* TODO: use Box::new_zeroed() when stabilized! */
138 /* TODO: also consider using smallvec! */
139 let mut out_block = vec![0u8; mem::size_of::<Self>()].into_boxed_slice();
140 let out_ptr: *mut Self = out_block.as_mut_ptr().cast();
141 unsafe {
142 out_ptr.write(self);
143 }
144 out_block
145 }
146
147 fn write<T: Write>(self, writer: &mut T) -> ZipResult<()> {
148 let block = self.encode();
149 writer.write_all(&block)?;
150 Ok(())
151 }
152 }
153
154 /// Convert all the fields of a struct *from* little-endian representations.
155 macro_rules! from_le {
156 ($obj:ident, $field:ident, $type:ty) => {
157 $obj.$field = <$type>::from_le($obj.$field);
158 };
159 ($obj:ident, [($field:ident, $type:ty) $(,)?]) => {
160 from_le![$obj, $field, $type];
161 };
162 ($obj:ident, [($field:ident, $type:ty), $($rest:tt),+ $(,)?]) => {
163 from_le![$obj, $field, $type];
164 from_le!($obj, [$($rest),+]);
165 };
166 }
167
168 /// Convert all the fields of a struct *into* little-endian representations.
169 macro_rules! to_le {
170 ($obj:ident, $field:ident, $type:ty) => {
171 $obj.$field = <$type>::to_le($obj.$field);
172 };
173 ($obj:ident, [($field:ident, $type:ty) $(,)?]) => {
174 to_le![$obj, $field, $type];
175 };
176 ($obj:ident, [($field:ident, $type:ty), $($rest:tt),+ $(,)?]) => {
177 to_le![$obj, $field, $type];
178 to_le!($obj, [$($rest),+]);
179 };
180 }
181
182 /* TODO: derive macro to generate these fields? */
183 /// Implement `from_le()` and `to_le()`, providing the field specification to both macros
184 /// and methods.
185 macro_rules! to_and_from_le {
186 ($($args:tt),+ $(,)?) => {
187 #[inline(always)]
188 fn from_le(mut self) -> Self {
189 from_le![self, [$($args),+]];
190 self
191 }
192 #[inline(always)]
193 fn to_le(mut self) -> Self {
194 to_le![self, [$($args),+]];
195 self
196 }
197 };
198 }
199
200 #[derive(Copy, Clone, Debug)]
201 #[repr(packed)]
202 pub(crate) struct Zip32CDEBlock {
203 magic: Magic,
204 pub disk_number: u16,
205 pub disk_with_central_directory: u16,
206 pub number_of_files_on_this_disk: u16,
207 pub number_of_files: u16,
208 pub central_directory_size: u32,
209 pub central_directory_offset: u32,
210 pub zip_file_comment_length: u16,
211 }
212
213 impl FixedSizeBlock for Zip32CDEBlock {
214 const MAGIC: Magic = Magic::CENTRAL_DIRECTORY_END_SIGNATURE;
215
216 #[inline(always)]
217 fn magic(self) -> Magic {
218 self.magic
219 }
220
221 const WRONG_MAGIC_ERROR: ZipError =
222 ZipError::InvalidArchive("Invalid digital signature header");
223
224 to_and_from_le![
225 (magic, Magic),
226 (disk_number, u16),
227 (disk_with_central_directory, u16),
228 (number_of_files_on_this_disk, u16),
229 (number_of_files, u16),
230 (central_directory_size, u32),
231 (central_directory_offset, u32),
232 (zip_file_comment_length, u16)
233 ];
234 }
235
236 #[derive(Debug)]
237 pub(crate) struct Zip32CentralDirectoryEnd {
238 pub disk_number: u16,
239 pub disk_with_central_directory: u16,
240 pub number_of_files_on_this_disk: u16,
241 pub number_of_files: u16,
242 pub central_directory_size: u32,
243 pub central_directory_offset: u32,
244 pub zip_file_comment: Box<[u8]>,
245 }
246
247 impl Zip32CentralDirectoryEnd {
248 fn block_and_comment(self) -> ZipResult<(Zip32CDEBlock, Box<[u8]>)> {
249 let Self {
250 disk_number,
251 disk_with_central_directory,
252 number_of_files_on_this_disk,
253 number_of_files,
254 central_directory_size,
255 central_directory_offset,
256 zip_file_comment,
257 } = self;
258 let block = Zip32CDEBlock {
259 magic: Zip32CDEBlock::MAGIC,
260 disk_number,
261 disk_with_central_directory,
262 number_of_files_on_this_disk,
263 number_of_files,
264 central_directory_size,
265 central_directory_offset,
266 zip_file_comment_length: zip_file_comment
267 .len()
268 .try_into()
269 .map_err(|_| ZipError::InvalidArchive("File comment must be less than 64 KiB"))?,
270 };
271 Ok((block, zip_file_comment))
272 }
273
274 pub fn parse<T: Read>(reader: &mut T) -> ZipResult<Zip32CentralDirectoryEnd> {
275 let Zip32CDEBlock {
276 // magic,
277 disk_number,
278 disk_with_central_directory,
279 number_of_files_on_this_disk,
280 number_of_files,
281 central_directory_size,
282 central_directory_offset,
283 zip_file_comment_length,
284 ..
285 } = Zip32CDEBlock::parse(reader)?;
286
287 let mut zip_file_comment = vec![0u8; zip_file_comment_length as usize].into_boxed_slice();
288 reader.read_exact(&mut zip_file_comment)?;
289
290 Ok(Zip32CentralDirectoryEnd {
291 disk_number,
292 disk_with_central_directory,
293 number_of_files_on_this_disk,
294 number_of_files,
295 central_directory_size,
296 central_directory_offset,
297 zip_file_comment,
298 })
299 }
300
301 pub fn find_and_parse<T: Read + Seek>(
302 reader: &mut T,
303 ) -> ZipResult<(Zip32CentralDirectoryEnd, u64)> {
304 let file_length = reader.seek(io::SeekFrom::End(0))?;
305
306 if file_length < mem::size_of::<Zip32CDEBlock>() as u64 {
307 return Err(ZipError::InvalidArchive("Invalid zip header"));
308 }
309
310 let search_lower_bound = 0;
311
312 const END_WINDOW_SIZE: usize = 512;
313 /* TODO: use static_assertions!() */
314 debug_assert!(END_WINDOW_SIZE > mem::size_of::<Magic>());
315
316 const SIG_BYTES: [u8; mem::size_of::<Magic>()] =
317 Magic::CENTRAL_DIRECTORY_END_SIGNATURE.to_le_bytes();
318 let finder = FinderRev::new(&SIG_BYTES);
319
320 let mut window_start: u64 = file_length.saturating_sub(END_WINDOW_SIZE as u64);
321 let mut window = [0u8; END_WINDOW_SIZE];
322 while window_start >= search_lower_bound {
323 /* Go to the start of the window in the file. */
324 reader.seek(io::SeekFrom::Start(window_start))?;
325
326 /* Identify how many bytes to read (this may be less than the window size for files
327 * smaller than END_WINDOW_SIZE). */
328 let end = (window_start + END_WINDOW_SIZE as u64).min(file_length);
329 let cur_len = (end - window_start) as usize;
330 debug_assert!(cur_len > 0);
331 debug_assert!(cur_len <= END_WINDOW_SIZE);
332 let cur_window: &mut [u8] = &mut window[..cur_len];
333 /* Read the window into the bytes! */
334 reader.read_exact(cur_window)?;
335
336 /* Find instances of the magic signature. */
337 for offset in finder.rfind_iter(cur_window) {
338 let cde_start_pos = window_start + offset as u64;
339 reader.seek(io::SeekFrom::Start(cde_start_pos))?;
340 /* Drop any headers that don't parse. */
341 if let Ok(cde) = Self::parse(reader) {
342 return Ok((cde, cde_start_pos));
343 }
344 }
345
346 /* We always want to make sure we go allllll the way back to the start of the file if
347 * we can't find it elsewhere. However, our `while` condition doesn't check that. So we
348 * avoid infinite looping by checking at the end of the loop. */
349 if window_start == search_lower_bound {
350 break;
351 }
352 /* Shift the window by END_WINDOW_SIZE bytes, but make sure to cover matches that
353 * overlap our nice neat window boundaries! */
354 window_start = (window_start
355 /* NB: To catch matches across window boundaries, we need to make our blocks overlap
356 * by the width of the pattern to match. */
357 + mem::size_of::<Magic>() as u64)
358 /* This should never happen, but make sure we don't go past the end of the file. */
359 .min(file_length);
360 window_start = window_start
361 .saturating_sub(
362 /* Shift the window upon each iteration so we search END_WINDOW_SIZE bytes at
363 * once (unless limited by file_length). */
364 END_WINDOW_SIZE as u64,
365 )
366 /* This will never go below the value of `search_lower_bound`, so we have a special
367 * `if window_start == search_lower_bound` check above. */
368 .max(search_lower_bound);
369 }
370
371 Err(ZipError::InvalidArchive(
372 "Could not find central directory end",
373 ))
374 }
375
376 pub fn write<T: Write>(self, writer: &mut T) -> ZipResult<()> {
377 let (block, comment) = self.block_and_comment()?;
378 block.write(writer)?;
379 writer.write_all(&comment)?;
380 Ok(())
381 }
382 }
383
384 #[derive(Copy, Clone)]
385 #[repr(packed)]
386 pub(crate) struct Zip64CDELocatorBlock {
387 magic: Magic,
388 pub disk_with_central_directory: u32,
389 pub end_of_central_directory_offset: u64,
390 pub number_of_disks: u32,
391 }
392
393 impl FixedSizeBlock for Zip64CDELocatorBlock {
394 const MAGIC: Magic = Magic::ZIP64_CENTRAL_DIRECTORY_END_LOCATOR_SIGNATURE;
395
396 #[inline(always)]
397 fn magic(self) -> Magic {
398 self.magic
399 }
400
401 const WRONG_MAGIC_ERROR: ZipError =
402 ZipError::InvalidArchive("Invalid zip64 locator digital signature header");
403
404 to_and_from_le![
405 (magic, Magic),
406 (disk_with_central_directory, u32),
407 (end_of_central_directory_offset, u64),
408 (number_of_disks, u32),
409 ];
410 }
411
412 pub(crate) struct Zip64CentralDirectoryEndLocator {
413 pub disk_with_central_directory: u32,
414 pub end_of_central_directory_offset: u64,
415 pub number_of_disks: u32,
416 }
417
418 impl Zip64CentralDirectoryEndLocator {
419 pub fn parse<T: Read>(reader: &mut T) -> ZipResult<Zip64CentralDirectoryEndLocator> {
420 let Zip64CDELocatorBlock {
421 // magic,
422 disk_with_central_directory,
423 end_of_central_directory_offset,
424 number_of_disks,
425 ..
426 } = Zip64CDELocatorBlock::parse(reader)?;
427
428 Ok(Zip64CentralDirectoryEndLocator {
429 disk_with_central_directory,
430 end_of_central_directory_offset,
431 number_of_disks,
432 })
433 }
434
435 pub fn block(self) -> Zip64CDELocatorBlock {
436 let Self {
437 disk_with_central_directory,
438 end_of_central_directory_offset,
439 number_of_disks,
440 } = self;
441 Zip64CDELocatorBlock {
442 magic: Zip64CDELocatorBlock::MAGIC,
443 disk_with_central_directory,
444 end_of_central_directory_offset,
445 number_of_disks,
446 }
447 }
448
449 pub fn write<T: Write>(self, writer: &mut T) -> ZipResult<()> {
450 self.block().write(writer)
451 }
452 }
453
454 #[derive(Copy, Clone)]
455 #[repr(packed)]
456 pub(crate) struct Zip64CDEBlock {
457 magic: Magic,
458 pub record_size: u64,
459 pub version_made_by: u16,
460 pub version_needed_to_extract: u16,
461 pub disk_number: u32,
462 pub disk_with_central_directory: u32,
463 pub number_of_files_on_this_disk: u64,
464 pub number_of_files: u64,
465 pub central_directory_size: u64,
466 pub central_directory_offset: u64,
467 }
468
469 impl FixedSizeBlock for Zip64CDEBlock {
470 const MAGIC: Magic = Magic::ZIP64_CENTRAL_DIRECTORY_END_SIGNATURE;
471
472 fn magic(self) -> Magic {
473 self.magic
474 }
475
476 const WRONG_MAGIC_ERROR: ZipError =
477 ZipError::InvalidArchive("Invalid digital signature header");
478
479 to_and_from_le![
480 (magic, Magic),
481 (record_size, u64),
482 (version_made_by, u16),
483 (version_needed_to_extract, u16),
484 (disk_number, u32),
485 (disk_with_central_directory, u32),
486 (number_of_files_on_this_disk, u64),
487 (number_of_files, u64),
488 (central_directory_size, u64),
489 (central_directory_offset, u64),
490 ];
491 }
492
493 pub(crate) struct Zip64CentralDirectoryEnd {
494 pub version_made_by: u16,
495 pub version_needed_to_extract: u16,
496 pub disk_number: u32,
497 pub disk_with_central_directory: u32,
498 pub number_of_files_on_this_disk: u64,
499 pub number_of_files: u64,
500 pub central_directory_size: u64,
501 pub central_directory_offset: u64,
502 //pub extensible_data_sector: Vec<u8>, <-- We don't do anything with this at the moment.
503 }
504
505 impl Zip64CentralDirectoryEnd {
506 pub fn parse<T: Read>(reader: &mut T) -> ZipResult<Zip64CentralDirectoryEnd> {
507 let Zip64CDEBlock {
508 // record_size,
509 version_made_by,
510 version_needed_to_extract,
511 disk_number,
512 disk_with_central_directory,
513 number_of_files_on_this_disk,
514 number_of_files,
515 central_directory_size,
516 central_directory_offset,
517 ..
518 } = Zip64CDEBlock::parse(reader)?;
519 Ok(Self {
520 version_made_by,
521 version_needed_to_extract,
522 disk_number,
523 disk_with_central_directory,
524 number_of_files_on_this_disk,
525 number_of_files,
526 central_directory_size,
527 central_directory_offset,
528 })
529 }
530
531 pub fn find_and_parse<T: Read + Seek>(
532 reader: &mut T,
533 search_lower_bound: u64,
534 search_upper_bound: u64,
535 ) -> ZipResult<Vec<(Zip64CentralDirectoryEnd, u64)>> {
536 let mut results = Vec::new();
537
538 const END_WINDOW_SIZE: usize = 2048;
539 /* TODO: use static_assertions!() */
540 debug_assert!(END_WINDOW_SIZE > mem::size_of::<Magic>());
541
542 const SIG_BYTES: [u8; mem::size_of::<Magic>()] =
543 Magic::ZIP64_CENTRAL_DIRECTORY_END_SIGNATURE.to_le_bytes();
544 let finder = FinderRev::new(&SIG_BYTES);
545
546 let mut window_start: u64 = search_upper_bound
547 .saturating_sub(END_WINDOW_SIZE as u64)
548 .max(search_lower_bound);
549 let mut window = [0u8; END_WINDOW_SIZE];
550 while window_start >= search_lower_bound {
551 reader.seek(io::SeekFrom::Start(window_start))?;
552
553 /* Identify how many bytes to read (this may be less than the window size for files
554 * smaller than END_WINDOW_SIZE). */
555 let end = (window_start + END_WINDOW_SIZE as u64).min(search_upper_bound);
556
557 debug_assert!(end >= window_start);
558 let cur_len = (end - window_start) as usize;
559 if cur_len == 0 {
560 break;
561 }
562 debug_assert!(cur_len <= END_WINDOW_SIZE);
563 let cur_window: &mut [u8] = &mut window[..cur_len];
564 /* Read the window into the bytes! */
565 reader.read_exact(cur_window)?;
566
567 /* Find instances of the magic signature. */
568 for offset in finder.rfind_iter(cur_window) {
569 let cde_start_pos = window_start + offset as u64;
570 reader.seek(io::SeekFrom::Start(cde_start_pos))?;
571
572 debug_assert!(cde_start_pos >= search_lower_bound);
573 let archive_offset = cde_start_pos - search_lower_bound;
574 let cde = Self::parse(reader)?;
575
576 results.push((cde, archive_offset));
577 }
578
579 /* We always want to make sure we go allllll the way back to the start of the file if
580 * we can't find it elsewhere. However, our `while` condition doesn't check that. So we
581 * avoid infinite looping by checking at the end of the loop. */
582 if window_start == search_lower_bound {
583 break;
584 }
585 /* Shift the window by END_WINDOW_SIZE bytes, but make sure to cover matches that
586 * overlap our nice neat window boundaries! */
587 window_start = (window_start
588 /* NB: To catch matches across window boundaries, we need to make our blocks overlap
589 * by the width of the pattern to match. */
590 + mem::size_of::<Magic>() as u64)
591 /* This may never happen, but make sure we don't go past the end of the specified
592 * range. */
593 .min(search_upper_bound);
594 window_start = window_start
595 .saturating_sub(
596 /* Shift the window upon each iteration so we search END_WINDOW_SIZE bytes at
597 * once (unless limited by search_upper_bound). */
598 END_WINDOW_SIZE as u64,
599 )
600 /* This will never go below the value of `search_lower_bound`, so we have a special
601 * `if window_start == search_lower_bound` check above. */
602 .max(search_lower_bound);
603 }
604
605 if results.is_empty() {
606 Err(ZipError::InvalidArchive(
607 "Could not find ZIP64 central directory end",
608 ))
609 } else {
610 Ok(results)
611 }
612 }
613
614 pub fn block(self) -> Zip64CDEBlock {
615 let Self {
616 version_made_by,
617 version_needed_to_extract,
618 disk_number,
619 disk_with_central_directory,
620 number_of_files_on_this_disk,
621 number_of_files,
622 central_directory_size,
623 central_directory_offset,
624 } = self;
625 Zip64CDEBlock {
626 magic: Zip64CDEBlock::MAGIC,
627 /* currently unused */
628 record_size: 44,
629 version_made_by,
630 version_needed_to_extract,
631 disk_number,
632 disk_with_central_directory,
633 number_of_files_on_this_disk,
634 number_of_files,
635 central_directory_size,
636 central_directory_offset,
637 }
638 }
639
640 pub fn write<T: Write>(self, writer: &mut T) -> ZipResult<()> {
641 self.block().write(writer)
642 }
643 }
644
645 pub(crate) fn is_dir(filename: &str) -> bool {
646 filename
647 .chars()
648 .next_back()
649 .map_or(false, |c| c == '/' || c == '\\')
650 }
651
652 /// Converts a path to the ZIP format (forward-slash-delimited and normalized).
653 pub(crate) fn path_to_string<T: AsRef<Path>>(path: T) -> Box<str> {
654 let mut maybe_original = None;
655 if let Some(original) = path.as_ref().to_str() {
656 if (MAIN_SEPARATOR == '/' || !original[1..].contains(MAIN_SEPARATOR))
657 && !original.ends_with('.')
658 && !original.starts_with(['.', MAIN_SEPARATOR])
659 && !original.starts_with(['.', '.', MAIN_SEPARATOR])
660 && !original.contains([MAIN_SEPARATOR, MAIN_SEPARATOR])
661 && !original.contains([MAIN_SEPARATOR, '.', MAIN_SEPARATOR])
662 && !original.contains([MAIN_SEPARATOR, '.', '.', MAIN_SEPARATOR])
663 {
664 if original.starts_with(MAIN_SEPARATOR) {
665 maybe_original = Some(&original[1..]);
666 } else {
667 maybe_original = Some(original);
668 }
669 }
670 }
671 let mut recreate = maybe_original.is_none();
672 let mut normalized_components = Vec::new();
673
674 for component in path.as_ref().components() {
675 match component {
676 Component::Normal(os_str) => match os_str.to_str() {
677 Some(valid_str) => normalized_components.push(Cow::Borrowed(valid_str)),
678 None => {
679 recreate = true;
680 normalized_components.push(os_str.to_string_lossy());
681 }
682 },
683 Component::ParentDir => {
684 recreate = true;
685 normalized_components.pop();
686 }
687 _ => {
688 recreate = true;
689 }
690 }
691 }
692 if recreate {
693 normalized_components.join("/").into()
694 } else {
695 maybe_original.unwrap().into()
696 }
697 }
698
699 #[cfg(test)]
700 mod test {
701 use super::*;
702 use std::io::Cursor;
703
704 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
705 #[repr(packed)]
706 pub struct TestBlock {
707 magic: Magic,
708 pub file_name_length: u16,
709 }
710
711 impl FixedSizeBlock for TestBlock {
712 const MAGIC: Magic = Magic::literal(0x01111);
713
714 fn magic(self) -> Magic {
715 self.magic
716 }
717
718 const WRONG_MAGIC_ERROR: ZipError = ZipError::InvalidArchive("unreachable");
719
720 to_and_from_le![(magic, Magic), (file_name_length, u16)];
721 }
722
723 /// Demonstrate that a block object can be safely written to memory and deserialized back out.
724 #[test]
725 fn block_serde() {
726 let block = TestBlock {
727 magic: TestBlock::MAGIC,
728 file_name_length: 3,
729 };
730 let mut c = Cursor::new(Vec::new());
731 block.write(&mut c).unwrap();
732 c.set_position(0);
733 let block2 = TestBlock::parse(&mut c).unwrap();
734 assert_eq!(block, block2);
735 }
736 }