Skip to main content

coip_format/
index.rs

1use alloc::vec::Vec;
2
3use crate::{Codec, Cursor, FormatError};
4
5pub const NO_ZSTD_DICT: u16 = 0xFFFF;
6pub const INDEX_HEADER_SIZE: usize = 32;
7pub const ALIAS_RULE_SIZE: usize = 20;
8pub const HOST_EXT_ENTRY_SIZE: usize = 40;
9
10/// IPv6 -> IPv4 alias delegation rule (Section 4).
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub struct AliasRule {
13    /// Big-endian network prefix bytes.
14    pub prefix: [u8; 16],
15    /// Number of leading bits to compare (`0..=128`).
16    pub prefix_len: u8,
17    /// Bit offset of the embedded 32-bit IPv4 address (`0..=96`).
18    pub v4_bit_offset: u8,
19}
20
21impl AliasRule {
22    /// Test whether `ip_be` (`u128::from_be_bytes(ipv6.octets())`) matches this alias rule,
23    /// returning the extracted big-endian numeric IPv4 (`u32`) on match.
24    #[inline]
25    pub fn match_ipv6(&self, ip_be: u128) -> Option<u32> {
26        let matched = if self.prefix_len == 0 {
27            true
28        } else if self.prefix_len >= 128 {
29            ip_be == u128::from_be_bytes(self.prefix)
30        } else {
31            let shift = 128 - self.prefix_len;
32            (ip_be >> shift) == (u128::from_be_bytes(self.prefix) >> shift)
33        };
34        if matched {
35            let shift = 96u8.saturating_sub(self.v4_bit_offset);
36            Some(((ip_be >> shift) & 0xFFFF_FFFF) as u32)
37        } else {
38            None
39        }
40    }
41
42    pub fn encode(&self, out: &mut Vec<u8>) {
43        out.extend_from_slice(&self.prefix);
44        out.push(self.prefix_len);
45        out.push(self.v4_bit_offset);
46        out.extend_from_slice(&[0u8; 2]);
47    }
48
49    pub fn decode(c: &mut Cursor<'_>) -> Result<Self, FormatError> {
50        let prefix = c.read_array::<16>()?;
51        let prefix_len = c.read_u8()?;
52        let v4_bit_offset = c.read_u8()?;
53        let _reserved = c.read_u16()?;
54        if prefix_len > 128 || v4_bit_offset > 96 {
55            return Err(FormatError::OutOfBounds("AliasRule bit range"));
56        }
57        Ok(Self {
58            prefix,
59            prefix_len,
60            v4_bit_offset,
61        })
62    }
63}
64
65/// Decoded Section 4 (`Ipv6Aliases`).
66#[derive(Debug, Clone, Default, PartialEq, Eq)]
67pub struct Ipv6Aliases {
68    pub rules: Vec<AliasRule>,
69}
70
71impl Ipv6Aliases {
72    pub fn encode(&self) -> Vec<u8> {
73        let mut out = Vec::with_capacity(4 + self.rules.len() * ALIAS_RULE_SIZE);
74        out.extend_from_slice(&(self.rules.len() as u16).to_le_bytes());
75        out.extend_from_slice(&0u16.to_le_bytes());
76        for r in &self.rules {
77            r.encode(&mut out);
78        }
79        out
80    }
81
82    pub fn decode(buf: &[u8]) -> Result<Self, FormatError> {
83        let mut c = Cursor::new(buf);
84        let count = c.read_u16()? as usize;
85        let _reserved = c.read_u16()?;
86        let mut rules = Vec::with_capacity(count);
87        for _ in 0..count {
88            rules.push(AliasRule::decode(&mut c)?);
89        }
90        Ok(Self { rules })
91    }
92
93    #[inline]
94    pub fn match_ipv6(&self, ip_be: u128) -> Option<u32> {
95        for r in &self.rules {
96            if let Some(v4) = r.match_ipv6(ip_be) {
97                return Some(v4);
98            }
99        }
100        None
101    }
102}
103
104/// Record ID encoding mode inside an IP index granule block.
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106#[repr(u8)]
107pub enum RidMode {
108    ZigZagDeltaVarint = 0,
109    LocalDict = 1,
110    Rle = 2,
111    ZeroSkipDelta = 3,
112    LocalDictSplit = 4,
113}
114
115impl RidMode {
116    #[inline]
117    pub fn from_u8(v: u8) -> Result<Self, FormatError> {
118        match v {
119            0 => Ok(Self::ZigZagDeltaVarint),
120            1 => Ok(Self::LocalDict),
121            2 => Ok(Self::Rle),
122            3 => Ok(Self::ZeroSkipDelta),
123            4 => Ok(Self::LocalDictSplit),
124            _ => Err(FormatError::InvalidRidMode(v)),
125        }
126    }
127}
128
129/// Fixed 32-byte header at the start of Section 5 (`Ipv4Index`) and Section 6 (`Ipv6Index`).
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131pub struct IndexHeader {
132    pub entry_count: u64,
133    pub block_size: u32,
134    pub block_count: u32,
135    pub l1_bits: u8,
136    pub starts_codec: Codec,
137    pub rids_codec: Codec,
138    pub starts_zstd_dict_id: u16,
139    pub rids_zstd_dict_id: u16,
140}
141
142impl IndexHeader {
143    pub fn encode(&self) -> [u8; INDEX_HEADER_SIZE] {
144        let mut out = [0u8; INDEX_HEADER_SIZE];
145        out[0..8].copy_from_slice(&self.entry_count.to_le_bytes());
146        out[8..12].copy_from_slice(&self.block_size.to_le_bytes());
147        out[12..16].copy_from_slice(&self.block_count.to_le_bytes());
148        out[16] = self.l1_bits;
149        out[17] = self.starts_codec as u8;
150        out[18] = self.rids_codec as u8;
151        out[19] = 0;
152        out[20..22].copy_from_slice(&self.starts_zstd_dict_id.to_le_bytes());
153        out[22..24].copy_from_slice(&self.rids_zstd_dict_id.to_le_bytes());
154        out
155    }
156
157    pub fn decode(c: &mut Cursor<'_>) -> Result<Self, FormatError> {
158        let entry_count = c.read_u64()?;
159        let block_size = c.read_u32()?;
160        let block_count = c.read_u32()?;
161        let l1_bits = c.read_u8()?;
162        let starts_codec = Codec::from_u8(c.read_u8()?)?;
163        let rids_codec = Codec::from_u8(c.read_u8()?)?;
164        let _reserved_u8 = c.read_u8()?;
165        let starts_zstd_dict_id = c.read_u16()?;
166        let rids_zstd_dict_id = c.read_u16()?;
167        let _reserved = c.read_u64()?;
168        if l1_bits > 24 {
169            return Err(FormatError::OutOfBounds("l1_bits > 24"));
170        }
171        Ok(Self {
172            entry_count,
173            block_size,
174            block_count,
175            l1_bits,
176            starts_codec,
177            rids_codec,
178            starts_zstd_dict_id,
179            rids_zstd_dict_id,
180        })
181    }
182}
183
184/// One inclusive IPv6 override entry finer than `/64` (Section 7).
185#[derive(Debug, Clone, Copy, PartialEq, Eq)]
186pub struct HostExtEntry {
187    pub start: u128,
188    pub end: u128,
189    pub record_id: u64,
190}
191
192impl HostExtEntry {
193    pub fn encode(&self, out: &mut Vec<u8>) {
194        out.extend_from_slice(&self.start.to_le_bytes());
195        out.extend_from_slice(&self.end.to_le_bytes());
196        out.extend_from_slice(&self.record_id.to_le_bytes());
197    }
198
199    pub fn decode(c: &mut Cursor<'_>) -> Result<Self, FormatError> {
200        Ok(Self {
201            start: c.read_u128()?,
202            end: c.read_u128()?,
203            record_id: c.read_u64()?,
204        })
205    }
206}
207
208/// Decoded Section 7 (`Ipv6HostExt`).
209#[derive(Debug, Clone, Default, PartialEq, Eq)]
210pub struct Ipv6HostExt {
211    pub entries: Vec<HostExtEntry>,
212}
213
214impl Ipv6HostExt {
215    pub fn encode(&self) -> Vec<u8> {
216        let mut out = Vec::with_capacity(8 + self.entries.len() * HOST_EXT_ENTRY_SIZE);
217        out.extend_from_slice(&(self.entries.len() as u32).to_le_bytes());
218        out.extend_from_slice(&0u32.to_le_bytes());
219        for e in &self.entries {
220            e.encode(&mut out);
221        }
222        out
223    }
224
225    pub fn decode(buf: &[u8]) -> Result<Self, FormatError> {
226        let mut c = Cursor::new(buf);
227        let count = c.read_u32()? as usize;
228        let _reserved = c.read_u32()?;
229        let mut entries = Vec::with_capacity(count);
230        for _ in 0..count {
231            entries.push(HostExtEntry::decode(&mut c)?);
232        }
233        Ok(Self { entries })
234    }
235
236    /// Look up `ip_be` (`u128::from_be_bytes(ipv6.octets())`).
237    /// Returns `Some(record_id)` on authoritative match (including `Some(0)` for an explicit hole).
238    #[inline]
239    pub fn lookup(&self, ip_be: u128) -> Option<u64> {
240        if self.entries.is_empty() {
241            return None;
242        }
243        let pos = self.entries.partition_point(|e| e.start <= ip_be);
244        if pos == 0 {
245            return None;
246        }
247        let entry = &self.entries[pos - 1];
248        if ip_be <= entry.end {
249            Some(entry.record_id)
250        } else {
251            None
252        }
253    }
254}
255
256/// Decoded Section 3 (`ZstdDicts`).
257#[derive(Debug, Clone, Default, PartialEq, Eq)]
258pub struct ZstdDicts {
259    pub dicts: Vec<Vec<u8>>,
260}
261
262impl ZstdDicts {
263    pub fn encode(&self) -> Vec<u8> {
264        let count = self.dicts.len();
265        let total_blobs: usize = self.dicts.iter().map(Vec::len).sum();
266        let mut out = Vec::with_capacity(4 + (count + 1) * 8 + total_blobs);
267        out.extend_from_slice(&(count as u16).to_le_bytes());
268        out.extend_from_slice(&0u16.to_le_bytes());
269        let mut off = 0u64;
270        for d in &self.dicts {
271            out.extend_from_slice(&off.to_le_bytes());
272            off += d.len() as u64;
273        }
274        out.extend_from_slice(&off.to_le_bytes());
275        for d in &self.dicts {
276            out.extend_from_slice(d);
277        }
278        out
279    }
280
281    pub fn decode(buf: &[u8]) -> Result<Self, FormatError> {
282        let mut c = Cursor::new(buf);
283        let count = c.read_u16()? as usize;
284        let _reserved = c.read_u16()?;
285        let mut offsets = Vec::with_capacity(count + 1);
286        for _ in 0..=count {
287            offsets.push(c.read_u64()?);
288        }
289        let blobs = c.remaining_slice();
290        let mut dicts = Vec::with_capacity(count);
291        for i in 0..count {
292            let start = usize::try_from(offsets[i]).map_err(|_| FormatError::UnexpectedEof)?;
293            let end = usize::try_from(offsets[i + 1]).map_err(|_| FormatError::UnexpectedEof)?;
294            if start > end || end > blobs.len() {
295                return Err(FormatError::OutOfBounds("ZstdDicts blob slice"));
296            }
297            dicts.push(blobs[start..end].to_vec());
298        }
299        Ok(Self { dicts })
300    }
301}
302
303/// Decompose an inclusive IPv4 range `[start..=end]` into the minimal list of `(network_u32, prefix_len)` CIDRs.
304pub fn range_to_cidrs_v4(mut start: u32, end: u32) -> Vec<(u32, u8)> {
305    let mut out = Vec::new();
306    if start > end {
307        return out;
308    }
309    loop {
310        let max_align_bits = if start == 0 {
311            32u32
312        } else {
313            start.trailing_zeros()
314        };
315        let rem = (end as u64) - (start as u64) + 1;
316        let max_len_bits = 63 - rem.leading_zeros();
317        let host_bits = max_align_bits.min(max_len_bits);
318        let prefix_len = (32 - host_bits) as u8;
319        out.push((start, prefix_len));
320        let step = 1u64 << host_bits;
321        let next = (start as u64) + step;
322        if next > (end as u64) {
323            break;
324        }
325        start = next as u32;
326    }
327    out
328}
329
330/// Decompose an inclusive IPv6 range `[start..=end]` into the minimal list of `(network_u128, prefix_len)` CIDRs.
331pub fn range_to_cidrs_v6(mut start: u128, end: u128) -> Vec<(u128, u8)> {
332    let mut out = Vec::new();
333    if start > end {
334        return out;
335    }
336    loop {
337        let max_align_bits = if start == 0 {
338            128u32
339        } else {
340            start.trailing_zeros()
341        };
342        let host_bits = if start == 0 && end == u128::MAX {
343            128u32
344        } else {
345            let diff = end - start;
346            // Largest k such that (1 << k) - 1 <= diff (i.e., 2^k <= diff + 1)
347            let rem_minus_1 = diff;
348            let max_len_bits = if rem_minus_1 == u128::MAX {
349                128u32
350            } else {
351                127 - (rem_minus_1 + 1).leading_zeros()
352            };
353            max_align_bits.min(max_len_bits)
354        };
355        let prefix_len = (128 - host_bits) as u8;
356        out.push((start, prefix_len));
357        if host_bits == 128 {
358            break;
359        }
360        let step = 1u128 << host_bits;
361        match start.checked_add(step) {
362            Some(next) if next <= end => start = next,
363            _ => break,
364        }
365    }
366    out
367}
368
369#[cfg(test)]
370mod tests {
371    use super::*;
372
373    #[test]
374    fn test_alias_rules() {
375        let rule_v4_mapped = AliasRule {
376            prefix: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0, 0, 0, 0],
377            prefix_len: 96,
378            v4_bit_offset: 96,
379        };
380        let ip = u128::from_be_bytes([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 8, 8, 8, 8]);
381        assert_eq!(rule_v4_mapped.match_ipv6(ip), Some(0x0808_0808));
382
383        let rule_6to4 = AliasRule {
384            prefix: [0x20, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
385            prefix_len: 16,
386            v4_bit_offset: 16,
387        };
388        let ip6to4 = u128::from_be_bytes([0x20, 0x02, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
389        assert_eq!(rule_6to4.match_ipv6(ip6to4), Some(0x0102_0304));
390        assert_eq!(rule_v4_mapped.match_ipv6(ip6to4), None);
391    }
392
393    #[test]
394    fn test_host_ext_lookup() {
395        let ext = Ipv6HostExt {
396            entries: alloc::vec![
397                HostExtEntry {
398                    start: 100,
399                    end: 105,
400                    record_id: 42
401                },
402                HostExtEntry {
403                    start: 200,
404                    end: 200,
405                    record_id: 0
406                },
407            ],
408        };
409        assert_eq!(ext.lookup(99), None);
410        assert_eq!(ext.lookup(100), Some(42));
411        assert_eq!(ext.lookup(105), Some(42));
412        assert_eq!(ext.lookup(106), None);
413        assert_eq!(ext.lookup(200), Some(0));
414    }
415
416    #[test]
417    fn test_range_to_cidrs() {
418        assert_eq!(range_to_cidrs_v4(0, u32::MAX), alloc::vec![(0, 0)]);
419        assert_eq!(
420            range_to_cidrs_v4(0x0101_0100, 0x0101_01FF),
421            alloc::vec![(0x0101_0100, 24)]
422        );
423        // 10.0.0.1..=10.0.0.4 -> /32, /31, /32
424        assert_eq!(
425            range_to_cidrs_v4(0x0A00_0001, 0x0A00_0004),
426            alloc::vec![(0x0A00_0001, 32), (0x0A00_0002, 31), (0x0A00_0004, 32)]
427        );
428        assert_eq!(range_to_cidrs_v6(0, u128::MAX), alloc::vec![(0, 0)]);
429        assert_eq!(
430            range_to_cidrs_v6(
431                0x2001_0db8_0000_0000u128 << 64,
432                (0x2001_0db8_0000_0000u128 << 64) | u64::MAX as u128
433            ),
434            alloc::vec![(0x2001_0db8_0000_0000u128 << 64, 64)]
435        );
436    }
437}