Skip to main content

zip/format/
magic.rs

1//! "Magic" header values used in the zip spec to locate metadata records.
2
3/// These values currently always take up a fixed four bytes, so we can parse and wrap them in this
4/// struct to enforce some small amount of type safety.
5#[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
6#[repr(transparent)]
7pub struct Magic(u32);
8
9impl Magic {
10    /// Local file header signature
11    pub const LOCAL_FILE_HEADER_SIGNATURE: Self = Self::literal(0x0403_4b50);
12    /// Central directory header signature
13    pub const CENTRAL_DIRECTORY_HEADER_SIGNATURE: Self = Self::literal(0x0201_4b50);
14    /// Central directory end signature
15    pub const CENTRAL_DIRECTORY_END_SIGNATURE: Self = Self::literal(0x0605_4b50);
16    /// Zip64 central directory signature
17    pub const ZIP64_CENTRAL_DIRECTORY_END_SIGNATURE: Self = Self::literal(0x0606_4b50);
18    /// Zip64 central directory end locator signature
19    pub const ZIP64_CENTRAL_DIRECTORY_END_LOCATOR_SIGNATURE: Self = Self::literal(0x0706_4b50);
20    /// Data descriptor signature
21    pub const DATA_DESCRIPTOR_SIGNATURE: Self = Self::literal(0x0807_4b50);
22
23    /// Create new literal
24    #[must_use]
25    pub const fn literal(x: u32) -> Self {
26        Self(x)
27    }
28
29    /// Create new from bytes
30    #[inline(always)]
31    #[must_use]
32    pub const fn from_le_bytes(bytes: [u8; 4]) -> Self {
33        Self(u32::from_le_bytes(bytes))
34    }
35
36    /// Get as bytes
37    #[inline(always)]
38    #[must_use]
39    pub const fn to_le_bytes(self) -> [u8; 4] {
40        self.0.to_le_bytes()
41    }
42
43    /// From little endian
44    #[allow(clippy::wrong_self_convention)]
45    #[inline(always)]
46    #[must_use]
47    pub fn from_le(self) -> Self {
48        Self(u32::from_le(self.0))
49    }
50
51    /// To little endian
52    #[allow(clippy::wrong_self_convention)]
53    #[inline(always)]
54    #[must_use]
55    pub fn to_le(self) -> Self {
56        Self(u32::to_le(self.0))
57    }
58}