coip-format 0.1.0

Core binary format definitions, schema, varint, CRC32C, and wire codecs for COI (.coi) columnar IP databases
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
use alloc::vec::Vec;

use crate::{Codec, Cursor, FormatError};

pub const NO_ZSTD_DICT: u16 = 0xFFFF;
pub const INDEX_HEADER_SIZE: usize = 32;
pub const ALIAS_RULE_SIZE: usize = 20;
pub const HOST_EXT_ENTRY_SIZE: usize = 40;

/// IPv6 -> IPv4 alias delegation rule (Section 4).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AliasRule {
    /// Big-endian network prefix bytes.
    pub prefix: [u8; 16],
    /// Number of leading bits to compare (`0..=128`).
    pub prefix_len: u8,
    /// Bit offset of the embedded 32-bit IPv4 address (`0..=96`).
    pub v4_bit_offset: u8,
}

impl AliasRule {
    /// Test whether `ip_be` (`u128::from_be_bytes(ipv6.octets())`) matches this alias rule,
    /// returning the extracted big-endian numeric IPv4 (`u32`) on match.
    #[inline]
    pub fn match_ipv6(&self, ip_be: u128) -> Option<u32> {
        let matched = if self.prefix_len == 0 {
            true
        } else if self.prefix_len >= 128 {
            ip_be == u128::from_be_bytes(self.prefix)
        } else {
            let shift = 128 - self.prefix_len;
            (ip_be >> shift) == (u128::from_be_bytes(self.prefix) >> shift)
        };
        if matched {
            let shift = 96u8.saturating_sub(self.v4_bit_offset);
            Some(((ip_be >> shift) & 0xFFFF_FFFF) as u32)
        } else {
            None
        }
    }

    pub fn encode(&self, out: &mut Vec<u8>) {
        out.extend_from_slice(&self.prefix);
        out.push(self.prefix_len);
        out.push(self.v4_bit_offset);
        out.extend_from_slice(&[0u8; 2]);
    }

    pub fn decode(c: &mut Cursor<'_>) -> Result<Self, FormatError> {
        let prefix = c.read_array::<16>()?;
        let prefix_len = c.read_u8()?;
        let v4_bit_offset = c.read_u8()?;
        let _reserved = c.read_u16()?;
        if prefix_len > 128 || v4_bit_offset > 96 {
            return Err(FormatError::OutOfBounds("AliasRule bit range"));
        }
        Ok(Self {
            prefix,
            prefix_len,
            v4_bit_offset,
        })
    }
}

/// Decoded Section 4 (`Ipv6Aliases`).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Ipv6Aliases {
    pub rules: Vec<AliasRule>,
}

impl Ipv6Aliases {
    pub fn encode(&self) -> Vec<u8> {
        let mut out = Vec::with_capacity(4 + self.rules.len() * ALIAS_RULE_SIZE);
        out.extend_from_slice(&(self.rules.len() as u16).to_le_bytes());
        out.extend_from_slice(&0u16.to_le_bytes());
        for r in &self.rules {
            r.encode(&mut out);
        }
        out
    }

    pub fn decode(buf: &[u8]) -> Result<Self, FormatError> {
        let mut c = Cursor::new(buf);
        let count = c.read_u16()? as usize;
        let _reserved = c.read_u16()?;
        let mut rules = Vec::with_capacity(count);
        for _ in 0..count {
            rules.push(AliasRule::decode(&mut c)?);
        }
        Ok(Self { rules })
    }

    #[inline]
    pub fn match_ipv6(&self, ip_be: u128) -> Option<u32> {
        for r in &self.rules {
            if let Some(v4) = r.match_ipv6(ip_be) {
                return Some(v4);
            }
        }
        None
    }
}

/// Record ID encoding mode inside an IP index granule block.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum RidMode {
    ZigZagDeltaVarint = 0,
    LocalDict = 1,
    Rle = 2,
    ZeroSkipDelta = 3,
    LocalDictSplit = 4,
}

impl RidMode {
    #[inline]
    pub fn from_u8(v: u8) -> Result<Self, FormatError> {
        match v {
            0 => Ok(Self::ZigZagDeltaVarint),
            1 => Ok(Self::LocalDict),
            2 => Ok(Self::Rle),
            3 => Ok(Self::ZeroSkipDelta),
            4 => Ok(Self::LocalDictSplit),
            _ => Err(FormatError::InvalidRidMode(v)),
        }
    }
}

/// Fixed 32-byte header at the start of Section 5 (`Ipv4Index`) and Section 6 (`Ipv6Index`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IndexHeader {
    pub entry_count: u64,
    pub block_size: u32,
    pub block_count: u32,
    pub l1_bits: u8,
    pub starts_codec: Codec,
    pub rids_codec: Codec,
    pub starts_zstd_dict_id: u16,
    pub rids_zstd_dict_id: u16,
}

impl IndexHeader {
    pub fn encode(&self) -> [u8; INDEX_HEADER_SIZE] {
        let mut out = [0u8; INDEX_HEADER_SIZE];
        out[0..8].copy_from_slice(&self.entry_count.to_le_bytes());
        out[8..12].copy_from_slice(&self.block_size.to_le_bytes());
        out[12..16].copy_from_slice(&self.block_count.to_le_bytes());
        out[16] = self.l1_bits;
        out[17] = self.starts_codec as u8;
        out[18] = self.rids_codec as u8;
        out[19] = 0;
        out[20..22].copy_from_slice(&self.starts_zstd_dict_id.to_le_bytes());
        out[22..24].copy_from_slice(&self.rids_zstd_dict_id.to_le_bytes());
        out
    }

    pub fn decode(c: &mut Cursor<'_>) -> Result<Self, FormatError> {
        let entry_count = c.read_u64()?;
        let block_size = c.read_u32()?;
        let block_count = c.read_u32()?;
        let l1_bits = c.read_u8()?;
        let starts_codec = Codec::from_u8(c.read_u8()?)?;
        let rids_codec = Codec::from_u8(c.read_u8()?)?;
        let _reserved_u8 = c.read_u8()?;
        let starts_zstd_dict_id = c.read_u16()?;
        let rids_zstd_dict_id = c.read_u16()?;
        let _reserved = c.read_u64()?;
        if l1_bits > 24 {
            return Err(FormatError::OutOfBounds("l1_bits > 24"));
        }
        Ok(Self {
            entry_count,
            block_size,
            block_count,
            l1_bits,
            starts_codec,
            rids_codec,
            starts_zstd_dict_id,
            rids_zstd_dict_id,
        })
    }
}

/// One inclusive IPv6 override entry finer than `/64` (Section 7).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HostExtEntry {
    pub start: u128,
    pub end: u128,
    pub record_id: u64,
}

impl HostExtEntry {
    pub fn encode(&self, out: &mut Vec<u8>) {
        out.extend_from_slice(&self.start.to_le_bytes());
        out.extend_from_slice(&self.end.to_le_bytes());
        out.extend_from_slice(&self.record_id.to_le_bytes());
    }

    pub fn decode(c: &mut Cursor<'_>) -> Result<Self, FormatError> {
        Ok(Self {
            start: c.read_u128()?,
            end: c.read_u128()?,
            record_id: c.read_u64()?,
        })
    }
}

/// Decoded Section 7 (`Ipv6HostExt`).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Ipv6HostExt {
    pub entries: Vec<HostExtEntry>,
}

impl Ipv6HostExt {
    pub fn encode(&self) -> Vec<u8> {
        let mut out = Vec::with_capacity(8 + self.entries.len() * HOST_EXT_ENTRY_SIZE);
        out.extend_from_slice(&(self.entries.len() as u32).to_le_bytes());
        out.extend_from_slice(&0u32.to_le_bytes());
        for e in &self.entries {
            e.encode(&mut out);
        }
        out
    }

    pub fn decode(buf: &[u8]) -> Result<Self, FormatError> {
        let mut c = Cursor::new(buf);
        let count = c.read_u32()? as usize;
        let _reserved = c.read_u32()?;
        let mut entries = Vec::with_capacity(count);
        for _ in 0..count {
            entries.push(HostExtEntry::decode(&mut c)?);
        }
        Ok(Self { entries })
    }

    /// Look up `ip_be` (`u128::from_be_bytes(ipv6.octets())`).
    /// Returns `Some(record_id)` on authoritative match (including `Some(0)` for an explicit hole).
    #[inline]
    pub fn lookup(&self, ip_be: u128) -> Option<u64> {
        if self.entries.is_empty() {
            return None;
        }
        let pos = self.entries.partition_point(|e| e.start <= ip_be);
        if pos == 0 {
            return None;
        }
        let entry = &self.entries[pos - 1];
        if ip_be <= entry.end {
            Some(entry.record_id)
        } else {
            None
        }
    }
}

/// Decoded Section 3 (`ZstdDicts`).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ZstdDicts {
    pub dicts: Vec<Vec<u8>>,
}

impl ZstdDicts {
    pub fn encode(&self) -> Vec<u8> {
        let count = self.dicts.len();
        let total_blobs: usize = self.dicts.iter().map(Vec::len).sum();
        let mut out = Vec::with_capacity(4 + (count + 1) * 8 + total_blobs);
        out.extend_from_slice(&(count as u16).to_le_bytes());
        out.extend_from_slice(&0u16.to_le_bytes());
        let mut off = 0u64;
        for d in &self.dicts {
            out.extend_from_slice(&off.to_le_bytes());
            off += d.len() as u64;
        }
        out.extend_from_slice(&off.to_le_bytes());
        for d in &self.dicts {
            out.extend_from_slice(d);
        }
        out
    }

    pub fn decode(buf: &[u8]) -> Result<Self, FormatError> {
        let mut c = Cursor::new(buf);
        let count = c.read_u16()? as usize;
        let _reserved = c.read_u16()?;
        let mut offsets = Vec::with_capacity(count + 1);
        for _ in 0..=count {
            offsets.push(c.read_u64()?);
        }
        let blobs = c.remaining_slice();
        let mut dicts = Vec::with_capacity(count);
        for i in 0..count {
            let start = usize::try_from(offsets[i]).map_err(|_| FormatError::UnexpectedEof)?;
            let end = usize::try_from(offsets[i + 1]).map_err(|_| FormatError::UnexpectedEof)?;
            if start > end || end > blobs.len() {
                return Err(FormatError::OutOfBounds("ZstdDicts blob slice"));
            }
            dicts.push(blobs[start..end].to_vec());
        }
        Ok(Self { dicts })
    }
}

/// Decompose an inclusive IPv4 range `[start..=end]` into the minimal list of `(network_u32, prefix_len)` CIDRs.
pub fn range_to_cidrs_v4(mut start: u32, end: u32) -> Vec<(u32, u8)> {
    let mut out = Vec::new();
    if start > end {
        return out;
    }
    loop {
        let max_align_bits = if start == 0 {
            32u32
        } else {
            start.trailing_zeros()
        };
        let rem = (end as u64) - (start as u64) + 1;
        let max_len_bits = 63 - rem.leading_zeros();
        let host_bits = max_align_bits.min(max_len_bits);
        let prefix_len = (32 - host_bits) as u8;
        out.push((start, prefix_len));
        let step = 1u64 << host_bits;
        let next = (start as u64) + step;
        if next > (end as u64) {
            break;
        }
        start = next as u32;
    }
    out
}

/// Decompose an inclusive IPv6 range `[start..=end]` into the minimal list of `(network_u128, prefix_len)` CIDRs.
pub fn range_to_cidrs_v6(mut start: u128, end: u128) -> Vec<(u128, u8)> {
    let mut out = Vec::new();
    if start > end {
        return out;
    }
    loop {
        let max_align_bits = if start == 0 {
            128u32
        } else {
            start.trailing_zeros()
        };
        let host_bits = if start == 0 && end == u128::MAX {
            128u32
        } else {
            let diff = end - start;
            // Largest k such that (1 << k) - 1 <= diff (i.e., 2^k <= diff + 1)
            let rem_minus_1 = diff;
            let max_len_bits = if rem_minus_1 == u128::MAX {
                128u32
            } else {
                127 - (rem_minus_1 + 1).leading_zeros()
            };
            max_align_bits.min(max_len_bits)
        };
        let prefix_len = (128 - host_bits) as u8;
        out.push((start, prefix_len));
        if host_bits == 128 {
            break;
        }
        let step = 1u128 << host_bits;
        match start.checked_add(step) {
            Some(next) if next <= end => start = next,
            _ => break,
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_alias_rules() {
        let rule_v4_mapped = AliasRule {
            prefix: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0, 0, 0, 0],
            prefix_len: 96,
            v4_bit_offset: 96,
        };
        let ip = u128::from_be_bytes([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 8, 8, 8, 8]);
        assert_eq!(rule_v4_mapped.match_ipv6(ip), Some(0x0808_0808));

        let rule_6to4 = AliasRule {
            prefix: [0x20, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            prefix_len: 16,
            v4_bit_offset: 16,
        };
        let ip6to4 = u128::from_be_bytes([0x20, 0x02, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);
        assert_eq!(rule_6to4.match_ipv6(ip6to4), Some(0x0102_0304));
        assert_eq!(rule_v4_mapped.match_ipv6(ip6to4), None);
    }

    #[test]
    fn test_host_ext_lookup() {
        let ext = Ipv6HostExt {
            entries: alloc::vec![
                HostExtEntry {
                    start: 100,
                    end: 105,
                    record_id: 42
                },
                HostExtEntry {
                    start: 200,
                    end: 200,
                    record_id: 0
                },
            ],
        };
        assert_eq!(ext.lookup(99), None);
        assert_eq!(ext.lookup(100), Some(42));
        assert_eq!(ext.lookup(105), Some(42));
        assert_eq!(ext.lookup(106), None);
        assert_eq!(ext.lookup(200), Some(0));
    }

    #[test]
    fn test_range_to_cidrs() {
        assert_eq!(range_to_cidrs_v4(0, u32::MAX), alloc::vec![(0, 0)]);
        assert_eq!(
            range_to_cidrs_v4(0x0101_0100, 0x0101_01FF),
            alloc::vec![(0x0101_0100, 24)]
        );
        // 10.0.0.1..=10.0.0.4 -> /32, /31, /32
        assert_eq!(
            range_to_cidrs_v4(0x0A00_0001, 0x0A00_0004),
            alloc::vec![(0x0A00_0001, 32), (0x0A00_0002, 31), (0x0A00_0004, 32)]
        );
        assert_eq!(range_to_cidrs_v6(0, u128::MAX), alloc::vec![(0, 0)]);
        assert_eq!(
            range_to_cidrs_v6(
                0x2001_0db8_0000_0000u128 << 64,
                (0x2001_0db8_0000_0000u128 << 64) | u64::MAX as u128
            ),
            alloc::vec![(0x2001_0db8_0000_0000u128 << 64, 64)]
        );
    }
}