Skip to main content

coip_format/
header.rs

1use alloc::vec::Vec;
2
3use crate::{Cursor, FormatError, crc32c};
4
5pub const MAGIC_HEADER: [u8; 4] = *b"COI\0";
6pub const MAGIC_FOOTER: [u8; 4] = *b"COI\xFF";
7pub const FORMAT_MAJOR: u16 = 1;
8pub const FORMAT_MINOR: u16 = 0;
9pub const HEADER_SIZE: usize = 64;
10pub const SECTION_ENTRY_SIZE: usize = 32;
11pub const FOOTER_SIZE: usize = 16;
12pub const SECTION_ALIGN: u64 = 8;
13
14/// Bitmask flags stored in `FileHeader.flags`.
15pub mod header_flags {
16    pub const HAS_IPV4: u32 = 0x01;
17    pub const HAS_IPV6: u32 = 0x02;
18    pub const HAS_IPV6_HOST_EXT: u32 = 0x04;
19    pub const HAS_ZSTD_DICTS: u32 = 0x08;
20}
21
22/// Compression codec identifier.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
24#[repr(u8)]
25pub enum Codec {
26    None = 0,
27    Zstd = 1,
28    Lz4 = 2,
29    BitPack = 3,
30}
31
32impl Codec {
33    #[inline]
34    pub fn from_u8(v: u8) -> Result<Self, FormatError> {
35        match v {
36            0 => Ok(Self::None),
37            1 => Ok(Self::Zstd),
38            2 => Ok(Self::Lz4),
39            3 => Ok(Self::BitPack),
40            _ => Err(FormatError::InvalidCodec(v)),
41        }
42    }
43}
44
45/// Section kind identifier in the Section Directory.
46#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
47#[repr(u16)]
48pub enum SectionKind {
49    Metadata = 1,
50    Schema = 2,
51    ZstdDicts = 3,
52    Ipv6Aliases = 4,
53    Ipv4Index = 5,
54    Ipv6Index = 6,
55    Ipv6HostExt = 7,
56    RecordColumns = 8,
57    DictTables = 9,
58}
59
60impl SectionKind {
61    #[inline]
62    pub fn from_u16(v: u16) -> Result<Self, FormatError> {
63        match v {
64            1 => Ok(Self::Metadata),
65            2 => Ok(Self::Schema),
66            3 => Ok(Self::ZstdDicts),
67            4 => Ok(Self::Ipv6Aliases),
68            5 => Ok(Self::Ipv4Index),
69            6 => Ok(Self::Ipv6Index),
70            7 => Ok(Self::Ipv6HostExt),
71            8 => Ok(Self::RecordColumns),
72            9 => Ok(Self::DictTables),
73            _ => Err(FormatError::InvalidSectionKind(v)),
74        }
75    }
76
77    pub const fn name(self) -> &'static str {
78        match self {
79            Self::Metadata => "Metadata",
80            Self::Schema => "Schema",
81            Self::ZstdDicts => "ZstdDicts",
82            Self::Ipv6Aliases => "Ipv6Aliases",
83            Self::Ipv4Index => "Ipv4Index",
84            Self::Ipv6Index => "Ipv6Index",
85            Self::Ipv6HostExt => "Ipv6HostExt",
86            Self::RecordColumns => "RecordColumns",
87            Self::DictTables => "DictTables",
88        }
89    }
90}
91
92/// Fixed 64-byte COI file header at offset 0.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub struct FileHeader {
95    pub format_major: u16,
96    pub format_minor: u16,
97    pub flags: u32,
98    pub profile_codec: Codec,
99    pub section_count: u8,
100    pub header_ext_len: u16,
101    pub build_epoch: u64,
102    pub record_count: u64,
103    pub section_dir_offset: u64,
104    pub file_size: u64,
105    pub header_crc32c: u32,
106}
107
108impl FileHeader {
109    pub fn encode(&self) -> [u8; HEADER_SIZE] {
110        let mut out = [0u8; HEADER_SIZE];
111        out[0..4].copy_from_slice(&MAGIC_HEADER);
112        out[4..6].copy_from_slice(&self.format_major.to_le_bytes());
113        out[6..8].copy_from_slice(&self.format_minor.to_le_bytes());
114        out[8..12].copy_from_slice(&self.flags.to_le_bytes());
115        out[12] = self.profile_codec as u8;
116        out[13] = self.section_count;
117        out[14..16].copy_from_slice(&self.header_ext_len.to_le_bytes());
118        out[16..24].copy_from_slice(&self.build_epoch.to_le_bytes());
119        out[24..32].copy_from_slice(&self.record_count.to_le_bytes());
120        out[32..40].copy_from_slice(&self.section_dir_offset.to_le_bytes());
121        out[40..48].copy_from_slice(&self.file_size.to_le_bytes());
122        let crc = crc32c(&out[0..48]);
123        out[48..52].copy_from_slice(&crc.to_le_bytes());
124        out
125    }
126
127    pub fn decode(buf: &[u8]) -> Result<Self, FormatError> {
128        if buf.len() < HEADER_SIZE {
129            return Err(FormatError::UnexpectedEof);
130        }
131        let mut c = Cursor::new(&buf[..HEADER_SIZE]);
132        let magic = c.read_array::<4>()?;
133        if magic != MAGIC_HEADER {
134            return Err(FormatError::InvalidMagic);
135        }
136        let format_major = c.read_u16()?;
137        let format_minor = c.read_u16()?;
138        if format_major != FORMAT_MAJOR {
139            return Err(FormatError::UnsupportedVersion {
140                major: format_major,
141                minor: format_minor,
142            });
143        }
144        let flags = c.read_u32()?;
145        let profile_codec = Codec::from_u8(c.read_u8()?)?;
146        let section_count = c.read_u8()?;
147        let header_ext_len = c.read_u16()?;
148        let build_epoch = c.read_u64()?;
149        let record_count = c.read_u64()?;
150        let section_dir_offset = c.read_u64()?;
151        let file_size = c.read_u64()?;
152        let header_crc32c = c.read_u32()?;
153        let actual_crc = crc32c(&buf[0..48]);
154        if header_crc32c != actual_crc {
155            return Err(FormatError::InvalidCrc {
156                expected: header_crc32c,
157                actual: actual_crc,
158            });
159        }
160        Ok(Self {
161            format_major,
162            format_minor,
163            flags,
164            profile_codec,
165            section_count,
166            header_ext_len,
167            build_epoch,
168            record_count,
169            section_dir_offset,
170            file_size,
171            header_crc32c,
172        })
173    }
174
175    #[inline]
176    pub const fn has_ipv4(&self) -> bool {
177        (self.flags & header_flags::HAS_IPV4) != 0
178    }
179
180    #[inline]
181    pub const fn has_ipv6(&self) -> bool {
182        (self.flags & header_flags::HAS_IPV6) != 0
183    }
184
185    #[inline]
186    pub const fn has_ipv6_host_ext(&self) -> bool {
187        (self.flags & header_flags::HAS_IPV6_HOST_EXT) != 0
188    }
189
190    #[inline]
191    pub const fn has_zstd_dicts(&self) -> bool {
192        (self.flags & header_flags::HAS_ZSTD_DICTS) != 0
193    }
194}
195
196/// 32-byte entry in the Section Directory.
197#[derive(Debug, Clone, Copy, PartialEq, Eq)]
198pub struct SectionEntry {
199    pub kind: SectionKind,
200    pub flags: u16,
201    pub crc32c: u32,
202    pub offset: u64,
203    pub length: u64,
204    pub uncompressed_length: u64,
205}
206
207impl SectionEntry {
208    #[inline]
209    pub fn codec(&self) -> Result<Codec, FormatError> {
210        Codec::from_u8((self.flags & 0x0F) as u8)
211    }
212
213    pub fn encode(&self, out: &mut Vec<u8>) {
214        out.extend_from_slice(&(self.kind as u16).to_le_bytes());
215        out.extend_from_slice(&self.flags.to_le_bytes());
216        out.extend_from_slice(&self.crc32c.to_le_bytes());
217        out.extend_from_slice(&self.offset.to_le_bytes());
218        out.extend_from_slice(&self.length.to_le_bytes());
219        out.extend_from_slice(&self.uncompressed_length.to_le_bytes());
220    }
221
222    pub fn decode(c: &mut Cursor<'_>) -> Result<Self, FormatError> {
223        let kind = SectionKind::from_u16(c.read_u16()?)?;
224        let flags = c.read_u16()?;
225        let _ = Codec::from_u8((flags & 0x0F) as u8)?;
226        let crc32c = c.read_u32()?;
227        let offset = c.read_u64()?;
228        if offset % SECTION_ALIGN != 0 {
229            return Err(FormatError::InvalidAlignment { offset });
230        }
231        let length = c.read_u64()?;
232        let uncompressed_length = c.read_u64()?;
233        Ok(Self {
234            kind,
235            flags,
236            crc32c,
237            offset,
238            length,
239            uncompressed_length,
240        })
241    }
242}
243
244/// Fixed 16-byte COI file footer at `file_size - 16`.
245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
246pub struct FileFooter {
247    pub dir_crc32c: u32,
248    pub section_dir_offset: u64,
249}
250
251impl FileFooter {
252    pub fn encode(&self) -> [u8; FOOTER_SIZE] {
253        let mut out = [0u8; FOOTER_SIZE];
254        out[0..4].copy_from_slice(&self.dir_crc32c.to_le_bytes());
255        out[4..12].copy_from_slice(&self.section_dir_offset.to_le_bytes());
256        out[12..16].copy_from_slice(&MAGIC_FOOTER);
257        out
258    }
259
260    pub fn decode(buf: &[u8]) -> Result<Self, FormatError> {
261        if buf.len() < FOOTER_SIZE {
262            return Err(FormatError::UnexpectedEof);
263        }
264        let mut c = Cursor::new(&buf[..FOOTER_SIZE]);
265        let dir_crc32c = c.read_u32()?;
266        let section_dir_offset = c.read_u64()?;
267        let magic_end = c.read_array::<4>()?;
268        if magic_end != MAGIC_FOOTER {
269            return Err(FormatError::InvalidMagic);
270        }
271        Ok(Self {
272            dir_crc32c,
273            section_dir_offset,
274        })
275    }
276}
277
278/// Align an offset up to the next multiple of 8 bytes.
279#[inline]
280pub const fn align8(offset: u64) -> u64 {
281    (offset + (SECTION_ALIGN - 1)) & !(SECTION_ALIGN - 1)
282}