Skip to main content

coip_reader/
index_reader.rs

1//! IPv4 (`Section 5`) and IPv6 (`Section 6`) index readers with L1 direct buckets,
2//! `Section 3: ZstdDicts`, all 5 `RidMode`s, and 16-shard concurrent LRU block cache.
3
4use std::sync::Arc;
5
6use coip_format::{
7    Cursor, FormatError, IndexHeader, NO_ZSTD_DICT, RidMode, read_svarint, read_uvarint,
8};
9
10use crate::cache::ShardedLruCache;
11use crate::codec::decompress_with_dict;
12use crate::error::{ReaderError, Result};
13use crate::source::Backing;
14
15struct DecodedBlockU32 {
16    starts: Vec<u32>,
17    rids: Vec<u64>,
18}
19
20struct DecodedBlockU64 {
21    starts: Vec<u64>,
22    rids: Vec<u64>,
23}
24
25#[inline]
26fn resolve_dict(zstd_dicts: &[(u32, Vec<u8>)], dict_id: u16) -> Result<Option<(u32, &[u8])>> {
27    if dict_id == NO_ZSTD_DICT {
28        return Ok(None);
29    }
30    let (crc, bytes) = zstd_dicts
31        .get(dict_id as usize)
32        .ok_or_else(|| ReaderError::Corrupt(format!("missing zstd dict_id {dict_id}")))?;
33    Ok(Some((*crc, bytes.as_slice())))
34}
35
36/// Memory-resident sparse index + sharded LRU block cache for `Section 5: Ipv4Index`.
37pub struct Ipv4IndexReader {
38    header: IndexHeader,
39    l1_buckets: Vec<u32>,
40    first_ips: Vec<u32>,
41    block_offsets: Vec<u64>,
42    blocks_base_offset: u64,
43    cache: ShardedLruCache<u32, Arc<DecodedBlockU32>>,
44}
45
46impl Ipv4IndexReader {
47    pub fn parse(
48        backing: &Backing<'_>,
49        section_offset: u64,
50        section_len: u64,
51        cache_blocks: usize,
52    ) -> Result<Self> {
53        let hdr_bytes = backing.read_slice(section_offset, coip_format::INDEX_HEADER_SIZE)?;
54        let mut c = Cursor::new(&hdr_bytes);
55        let header = IndexHeader::decode(&mut c)?;
56        let block_count = header.block_count as usize;
57        let l1_count = if header.l1_bits > 0 {
58            (1usize << header.l1_bits) + 1
59        } else {
60            0
61        };
62
63        let dir_bytes_len = l1_count * 4 + block_count * 4 + (block_count + 1) * 8;
64        let dir_offset = section_offset + (coip_format::INDEX_HEADER_SIZE as u64);
65        if (coip_format::INDEX_HEADER_SIZE as u64) + (dir_bytes_len as u64) > section_len {
66            return Err(FormatError::UnexpectedEof.into());
67        }
68        let dir_bytes = backing.read_slice(dir_offset, dir_bytes_len)?;
69        let mut dc = Cursor::new(&dir_bytes);
70
71        let mut l1_buckets = Vec::with_capacity(l1_count);
72        for _ in 0..l1_count {
73            l1_buckets.push(dc.read_u32()?);
74        }
75        let mut first_ips = Vec::with_capacity(block_count);
76        for _ in 0..block_count {
77            first_ips.push(dc.read_u32()?);
78        }
79        let mut block_offsets = Vec::with_capacity(block_count + 1);
80        for _ in 0..=block_count {
81            block_offsets.push(dc.read_u64()?);
82        }
83
84        let blocks_base_offset = dir_offset + (dir_bytes_len as u64);
85
86        Ok(Self {
87            header,
88            l1_buckets,
89            first_ips,
90            block_offsets,
91            blocks_base_offset,
92            cache: ShardedLruCache::new(cache_blocks),
93        })
94    }
95
96    pub fn entry_count(&self) -> u64 {
97        self.header.entry_count
98    }
99
100    pub fn block_count(&self) -> u32 {
101        self.header.block_count
102    }
103
104    pub fn header(&self) -> &IndexHeader {
105        &self.header
106    }
107
108    pub fn clear_cache(&self) {
109        self.cache.clear();
110    }
111
112    /// Sequentially decode all IPv4 transitions `(start_u32, record_id)` without polluting the LRU cache.
113    pub fn collect_transitions(
114        &self,
115        backing: &Backing<'_>,
116        zstd_dicts: &[(u32, Vec<u8>)],
117    ) -> Result<Vec<(u32, u64)>> {
118        let mut out = Vec::with_capacity(self.header.entry_count as usize);
119        for b in 0..self.header.block_count {
120            let blk = self.decode_block_uncached(backing, zstd_dicts, b)?;
121            for (&s, &r) in blk.starts.iter().zip(blk.rids.iter()) {
122                out.push((s, r));
123            }
124        }
125        Ok(out)
126    }
127
128    /// Look up big-endian numeric IPv4 `key`, returning `record_id` (`0` = NotFound).
129    #[inline]
130    pub fn lookup(
131        &self,
132        backing: &Backing<'_>,
133        zstd_dicts: &[(u32, Vec<u8>)],
134        key: u32,
135    ) -> Result<u64> {
136        if self.first_ips.is_empty() || key < self.first_ips[0] {
137            return Ok(0);
138        }
139        let block_idx = self.locate_block(key);
140        let block = self.get_or_decode_block(backing, zstd_dicts, block_idx)?;
141        let pos = block.starts.partition_point(|&s| s <= key);
142        if pos == 0 {
143            Ok(0)
144        } else {
145            Ok(block.rids[pos - 1])
146        }
147    }
148
149    #[inline]
150    fn locate_block(&self, key: u32) -> u32 {
151        if !self.l1_buckets.is_empty() {
152            let p = (key >> (32 - self.header.l1_bits)) as usize;
153            let lo = self.l1_buckets[p] as usize;
154            let hi = self.l1_buckets[p + 1] as usize;
155            if lo == hi {
156                return lo as u32;
157            }
158            let rel = self.first_ips[lo..=hi].partition_point(|&ip| ip <= key);
159            return (lo + rel.saturating_sub(1)) as u32;
160        }
161        let pos = self.first_ips.partition_point(|&ip| ip <= key);
162        pos.saturating_sub(1) as u32
163    }
164
165    fn get_or_decode_block(
166        &self,
167        backing: &Backing<'_>,
168        zstd_dicts: &[(u32, Vec<u8>)],
169        block_idx: u32,
170    ) -> Result<Arc<DecodedBlockU32>> {
171        if let Some(hit) = self.cache.get(&block_idx) {
172            return Ok(hit);
173        }
174
175        let decoded = Arc::new(self.decode_block_uncached(backing, zstd_dicts, block_idx)?);
176        self.cache.put(block_idx, Arc::clone(&decoded));
177        Ok(decoded)
178    }
179
180    fn decode_block_uncached(
181        &self,
182        backing: &Backing<'_>,
183        zstd_dicts: &[(u32, Vec<u8>)],
184        block_idx: u32,
185    ) -> Result<DecodedBlockU32> {
186        let b = block_idx as usize;
187        let rel_start = self.block_offsets[b];
188        let rel_end = self.block_offsets[b + 1];
189        let block_len = (rel_end - rel_start) as usize;
190        let raw_block = backing.read_slice(self.blocks_base_offset + rel_start, block_len)?;
191
192        if raw_block.len() < 4 {
193            return Err(FormatError::UnexpectedEof.into());
194        }
195        let starts_blob_len =
196            u32::from_le_bytes([raw_block[0], raw_block[1], raw_block[2], raw_block[3]]) as usize;
197        if 4 + starts_blob_len > raw_block.len() {
198            return Err(FormatError::OutOfBounds("starts_blob_len").into());
199        }
200        let starts_blob = &raw_block[4..4 + starts_blob_len];
201        let rids_blob = &raw_block[4 + starts_blob_len..];
202
203        let n = self.entries_in_block(block_idx);
204        let s_dict = resolve_dict(zstd_dicts, self.header.starts_zstd_dict_id)?;
205        let raw_starts =
206            decompress_with_dict(self.header.starts_codec, starts_blob, Some(n * 3), s_dict)?;
207        let mut starts = Vec::with_capacity(n);
208        let mut cur = self.first_ips[b];
209        starts.push(cur);
210        let mut pos = 0usize;
211        for _ in 1..n {
212            let (delta, used) = read_uvarint(&raw_starts[pos..])?;
213            pos += used;
214            cur = cur
215                .checked_add(delta as u32)
216                .ok_or_else(|| ReaderError::Corrupt("IPv4 delta overflow".into()))?;
217            starts.push(cur);
218        }
219
220        let r_dict = resolve_dict(zstd_dicts, self.header.rids_zstd_dict_id)?;
221        let raw_rids =
222            decompress_with_dict(self.header.rids_codec, rids_blob, Some(n * 3), r_dict)?;
223        let rids = decode_rids(&raw_rids, n)?;
224
225        Ok(DecodedBlockU32 { starts, rids })
226    }
227
228    #[inline]
229    fn entries_in_block(&self, block_idx: u32) -> usize {
230        let start = (block_idx as u64) * (self.header.block_size as u64);
231        let rem = self.header.entry_count.saturating_sub(start);
232        rem.min(self.header.block_size as u64) as usize
233    }
234}
235
236/// Memory-resident sparse index + sharded LRU block cache for `Section 6: Ipv6Index`.
237pub struct Ipv6IndexReader {
238    header: IndexHeader,
239    l1_buckets: Vec<u32>,
240    first_ips: Vec<u64>,
241    block_offsets: Vec<u64>,
242    blocks_base_offset: u64,
243    cache: ShardedLruCache<u32, Arc<DecodedBlockU64>>,
244}
245
246impl Ipv6IndexReader {
247    pub fn parse(
248        backing: &Backing<'_>,
249        section_offset: u64,
250        section_len: u64,
251        cache_blocks: usize,
252    ) -> Result<Self> {
253        let hdr_bytes = backing.read_slice(section_offset, coip_format::INDEX_HEADER_SIZE)?;
254        let mut c = Cursor::new(&hdr_bytes);
255        let header = IndexHeader::decode(&mut c)?;
256        let block_count = header.block_count as usize;
257        let l1_count = if header.l1_bits > 0 {
258            (1usize << header.l1_bits) + 1
259        } else {
260            0
261        };
262
263        let dir_bytes_len = l1_count * 4 + block_count * 8 + (block_count + 1) * 8;
264        let dir_offset = section_offset + (coip_format::INDEX_HEADER_SIZE as u64);
265        if (coip_format::INDEX_HEADER_SIZE as u64) + (dir_bytes_len as u64) > section_len {
266            return Err(FormatError::UnexpectedEof.into());
267        }
268        let dir_bytes = backing.read_slice(dir_offset, dir_bytes_len)?;
269        let mut dc = Cursor::new(&dir_bytes);
270
271        let mut l1_buckets = Vec::with_capacity(l1_count);
272        for _ in 0..l1_count {
273            l1_buckets.push(dc.read_u32()?);
274        }
275        let mut first_ips = Vec::with_capacity(block_count);
276        for _ in 0..block_count {
277            first_ips.push(dc.read_u64()?);
278        }
279        let mut block_offsets = Vec::with_capacity(block_count + 1);
280        for _ in 0..=block_count {
281            block_offsets.push(dc.read_u64()?);
282        }
283
284        let blocks_base_offset = dir_offset + (dir_bytes_len as u64);
285
286        Ok(Self {
287            header,
288            l1_buckets,
289            first_ips,
290            block_offsets,
291            blocks_base_offset,
292            cache: ShardedLruCache::new(cache_blocks),
293        })
294    }
295
296    pub fn entry_count(&self) -> u64 {
297        self.header.entry_count
298    }
299
300    pub fn block_count(&self) -> u32 {
301        self.header.block_count
302    }
303
304    pub fn header(&self) -> &IndexHeader {
305        &self.header
306    }
307
308    pub fn clear_cache(&self) {
309        self.cache.clear();
310    }
311
312    /// Sequentially decode all IPv6 `/64` transitions `(start_hi64, record_id)` without polluting the LRU cache.
313    pub fn collect_transitions(
314        &self,
315        backing: &Backing<'_>,
316        zstd_dicts: &[(u32, Vec<u8>)],
317    ) -> Result<Vec<(u64, u64)>> {
318        let mut out = Vec::with_capacity(self.header.entry_count as usize);
319        for b in 0..self.header.block_count {
320            let blk = self.decode_block_uncached(backing, zstd_dicts, b)?;
321            for (&s, &r) in blk.starts.iter().zip(blk.rids.iter()) {
322                out.push((s, r));
323            }
324        }
325        Ok(out)
326    }
327
328    /// Look up upper 64 bits of an IPv6 address, returning `record_id` (`0` = NotFound).
329    #[inline]
330    pub fn lookup(
331        &self,
332        backing: &Backing<'_>,
333        zstd_dicts: &[(u32, Vec<u8>)],
334        key: u64,
335    ) -> Result<u64> {
336        if self.first_ips.is_empty() || key < self.first_ips[0] {
337            return Ok(0);
338        }
339        let block_idx = self.locate_block(key);
340        let block = self.get_or_decode_block(backing, zstd_dicts, block_idx)?;
341        let pos = block.starts.partition_point(|&s| s <= key);
342        if pos == 0 {
343            Ok(0)
344        } else {
345            Ok(block.rids[pos - 1])
346        }
347    }
348
349    #[inline]
350    fn locate_block(&self, key: u64) -> u32 {
351        if !self.l1_buckets.is_empty() {
352            let p = (key >> (64 - self.header.l1_bits)) as usize;
353            let lo = self.l1_buckets[p] as usize;
354            let hi = self.l1_buckets[p + 1] as usize;
355            if lo == hi {
356                return lo as u32;
357            }
358            let rel = self.first_ips[lo..=hi].partition_point(|&ip| ip <= key);
359            return (lo + rel.saturating_sub(1)) as u32;
360        }
361        let pos = self.first_ips.partition_point(|&ip| ip <= key);
362        pos.saturating_sub(1) as u32
363    }
364
365    fn get_or_decode_block(
366        &self,
367        backing: &Backing<'_>,
368        zstd_dicts: &[(u32, Vec<u8>)],
369        block_idx: u32,
370    ) -> Result<Arc<DecodedBlockU64>> {
371        if let Some(hit) = self.cache.get(&block_idx) {
372            return Ok(hit);
373        }
374
375        let decoded = Arc::new(self.decode_block_uncached(backing, zstd_dicts, block_idx)?);
376        self.cache.put(block_idx, Arc::clone(&decoded));
377        Ok(decoded)
378    }
379
380    fn decode_block_uncached(
381        &self,
382        backing: &Backing<'_>,
383        zstd_dicts: &[(u32, Vec<u8>)],
384        block_idx: u32,
385    ) -> Result<DecodedBlockU64> {
386        let b = block_idx as usize;
387        let rel_start = self.block_offsets[b];
388        let rel_end = self.block_offsets[b + 1];
389        let block_len = (rel_end - rel_start) as usize;
390        let raw_block = backing.read_slice(self.blocks_base_offset + rel_start, block_len)?;
391
392        if raw_block.len() < 4 {
393            return Err(FormatError::UnexpectedEof.into());
394        }
395        let starts_blob_len =
396            u32::from_le_bytes([raw_block[0], raw_block[1], raw_block[2], raw_block[3]]) as usize;
397        if 4 + starts_blob_len > raw_block.len() {
398            return Err(FormatError::OutOfBounds("starts_blob_len").into());
399        }
400        let starts_blob = &raw_block[4..4 + starts_blob_len];
401        let rids_blob = &raw_block[4 + starts_blob_len..];
402
403        let n = self.entries_in_block(block_idx);
404        let s_dict = resolve_dict(zstd_dicts, self.header.starts_zstd_dict_id)?;
405        let raw_starts =
406            decompress_with_dict(self.header.starts_codec, starts_blob, Some(n * 4), s_dict)?;
407        let mut starts = Vec::with_capacity(n);
408        let mut cur = self.first_ips[b];
409        starts.push(cur);
410        let mut pos = 0usize;
411        for _ in 1..n {
412            let (delta, used) = read_uvarint(&raw_starts[pos..])?;
413            pos += used;
414            cur = cur
415                .checked_add(delta)
416                .ok_or_else(|| ReaderError::Corrupt("IPv6 delta overflow".into()))?;
417            starts.push(cur);
418        }
419
420        let r_dict = resolve_dict(zstd_dicts, self.header.rids_zstd_dict_id)?;
421        let raw_rids =
422            decompress_with_dict(self.header.rids_codec, rids_blob, Some(n * 3), r_dict)?;
423        let rids = decode_rids(&raw_rids, n)?;
424
425        Ok(DecodedBlockU64 { starts, rids })
426    }
427
428    #[inline]
429    fn entries_in_block(&self, block_idx: u32) -> usize {
430        let start = (block_idx as u64) * (self.header.block_size as u64);
431        let rem = self.header.entry_count.saturating_sub(start);
432        rem.min(self.header.block_size as u64) as usize
433    }
434}
435
436fn decode_local_dict_table(raw: &[u8], pos: &mut usize) -> Result<Vec<u64>> {
437    let (dict_len_u64, used) = read_uvarint(&raw[*pos..])?;
438    *pos += used;
439    let dict_len = dict_len_u64 as usize;
440    if dict_len == 0 || dict_len > 65_536 {
441        return Err(ReaderError::Corrupt(format!(
442            "invalid LocalDict len {dict_len}"
443        )));
444    }
445    let mut dict = Vec::with_capacity(dict_len);
446    let (first, used) = read_uvarint(&raw[*pos..])?;
447    *pos += used;
448    dict.push(first);
449    let mut cur = first;
450    for _ in 1..dict_len {
451        let (delta, used) = read_uvarint(&raw[*pos..])?;
452        *pos += used;
453        cur = cur
454            .checked_add(delta)
455            .ok_or_else(|| ReaderError::Corrupt("LocalDict delta overflow".into()))?;
456        dict.push(cur);
457    }
458    Ok(dict)
459}
460
461fn decode_rids(raw: &[u8], n: usize) -> Result<Vec<u64>> {
462    if n == 0 {
463        return Ok(Vec::new());
464    }
465    if raw.is_empty() {
466        return Err(FormatError::UnexpectedEof.into());
467    }
468    let mode = RidMode::from_u8(raw[0])?;
469    let mut pos = 1usize;
470    let mut out = Vec::with_capacity(n);
471
472    match mode {
473        RidMode::ZigZagDeltaVarint => {
474            let (first, used) = read_uvarint(&raw[pos..])?;
475            pos += used;
476            out.push(first);
477            let mut cur = first;
478            for _ in 1..n {
479                let (delta, used) = read_svarint(&raw[pos..])?;
480                pos += used;
481                cur = cur.wrapping_add(delta as u64);
482                out.push(cur);
483            }
484        }
485        RidMode::LocalDict => {
486            let dict = decode_local_dict_table(raw, &mut pos)?;
487            if dict.len() <= 256 {
488                if pos + n > raw.len() {
489                    return Err(FormatError::UnexpectedEof.into());
490                }
491                for &idx in &raw[pos..pos + n] {
492                    out.push(
493                        *dict
494                            .get(idx as usize)
495                            .ok_or_else(|| ReaderError::Corrupt("LocalDict u8 idx OOB".into()))?,
496                    );
497                }
498            } else {
499                if pos + n * 2 > raw.len() {
500                    return Err(FormatError::UnexpectedEof.into());
501                }
502                for chunk in raw[pos..pos + n * 2].chunks_exact(2) {
503                    let idx = u16::from_le_bytes([chunk[0], chunk[1]]) as usize;
504                    out.push(
505                        *dict
506                            .get(idx)
507                            .ok_or_else(|| ReaderError::Corrupt("LocalDict u16 idx OOB".into()))?,
508                    );
509                }
510            }
511        }
512        RidMode::Rle => {
513            while out.len() < n {
514                let (rid, u1) = read_uvarint(&raw[pos..])?;
515                pos += u1;
516                let (run, u2) = read_uvarint(&raw[pos..])?;
517                pos += u2;
518                let run = run as usize;
519                if out.len() + run > n {
520                    return Err(ReaderError::Corrupt("RLE run exceeds block size".into()));
521                }
522                out.resize(out.len() + run, rid);
523            }
524        }
525        RidMode::ZeroSkipDelta => {
526            let bm_len = n.div_ceil(8);
527            if pos + bm_len > raw.len() {
528                return Err(FormatError::UnexpectedEof.into());
529            }
530            let bitmap = &raw[pos..pos + bm_len];
531            pos += bm_len;
532            let mut prev_nz: Option<u64> = None;
533            for i in 0..n {
534                if ((bitmap[i >> 3] >> (i & 7)) & 1) == 0 {
535                    out.push(0);
536                } else {
537                    let val = match prev_nz {
538                        None => {
539                            let (v, u) = read_uvarint(&raw[pos..])?;
540                            pos += u;
541                            v
542                        }
543                        Some(p) => {
544                            let (d, u) = read_svarint(&raw[pos..])?;
545                            pos += u;
546                            p.wrapping_add(d as u64)
547                        }
548                    };
549                    prev_nz = Some(val);
550                    out.push(val);
551                }
552            }
553        }
554        RidMode::LocalDictSplit => {
555            let dict = decode_local_dict_table(raw, &mut pos)?;
556            if pos + n * 2 > raw.len() {
557                return Err(FormatError::UnexpectedEof.into());
558            }
559            let lo = &raw[pos..pos + n];
560            let hi = &raw[pos + n..pos + n * 2];
561            for i in 0..n {
562                let idx = ((hi[i] as usize) << 8) | (lo[i] as usize);
563                out.push(
564                    *dict
565                        .get(idx)
566                        .ok_or_else(|| ReaderError::Corrupt("LocalDictSplit idx OOB".into()))?,
567                );
568            }
569        }
570    }
571
572    Ok(out)
573}