use std::sync::Arc;
use coip_format::{
Cursor, FormatError, IndexHeader, NO_ZSTD_DICT, RidMode, read_svarint, read_uvarint,
};
use crate::cache::ShardedLruCache;
use crate::codec::decompress_with_dict;
use crate::error::{ReaderError, Result};
use crate::source::Backing;
struct DecodedBlockU32 {
starts: Vec<u32>,
rids: Vec<u64>,
}
struct DecodedBlockU64 {
starts: Vec<u64>,
rids: Vec<u64>,
}
#[inline]
fn resolve_dict(zstd_dicts: &[(u32, Vec<u8>)], dict_id: u16) -> Result<Option<(u32, &[u8])>> {
if dict_id == NO_ZSTD_DICT {
return Ok(None);
}
let (crc, bytes) = zstd_dicts
.get(dict_id as usize)
.ok_or_else(|| ReaderError::Corrupt(format!("missing zstd dict_id {dict_id}")))?;
Ok(Some((*crc, bytes.as_slice())))
}
pub struct Ipv4IndexReader {
header: IndexHeader,
l1_buckets: Vec<u32>,
first_ips: Vec<u32>,
block_offsets: Vec<u64>,
blocks_base_offset: u64,
cache: ShardedLruCache<u32, Arc<DecodedBlockU32>>,
}
impl Ipv4IndexReader {
pub fn parse(
backing: &Backing<'_>,
section_offset: u64,
section_len: u64,
cache_blocks: usize,
) -> Result<Self> {
let hdr_bytes = backing.read_slice(section_offset, coip_format::INDEX_HEADER_SIZE)?;
let mut c = Cursor::new(&hdr_bytes);
let header = IndexHeader::decode(&mut c)?;
let block_count = header.block_count as usize;
let l1_count = if header.l1_bits > 0 {
(1usize << header.l1_bits) + 1
} else {
0
};
let dir_bytes_len = l1_count * 4 + block_count * 4 + (block_count + 1) * 8;
let dir_offset = section_offset + (coip_format::INDEX_HEADER_SIZE as u64);
if (coip_format::INDEX_HEADER_SIZE as u64) + (dir_bytes_len as u64) > section_len {
return Err(FormatError::UnexpectedEof.into());
}
let dir_bytes = backing.read_slice(dir_offset, dir_bytes_len)?;
let mut dc = Cursor::new(&dir_bytes);
let mut l1_buckets = Vec::with_capacity(l1_count);
for _ in 0..l1_count {
l1_buckets.push(dc.read_u32()?);
}
let mut first_ips = Vec::with_capacity(block_count);
for _ in 0..block_count {
first_ips.push(dc.read_u32()?);
}
let mut block_offsets = Vec::with_capacity(block_count + 1);
for _ in 0..=block_count {
block_offsets.push(dc.read_u64()?);
}
let blocks_base_offset = dir_offset + (dir_bytes_len as u64);
Ok(Self {
header,
l1_buckets,
first_ips,
block_offsets,
blocks_base_offset,
cache: ShardedLruCache::new(cache_blocks),
})
}
pub fn entry_count(&self) -> u64 {
self.header.entry_count
}
pub fn block_count(&self) -> u32 {
self.header.block_count
}
pub fn header(&self) -> &IndexHeader {
&self.header
}
pub fn clear_cache(&self) {
self.cache.clear();
}
pub fn collect_transitions(
&self,
backing: &Backing<'_>,
zstd_dicts: &[(u32, Vec<u8>)],
) -> Result<Vec<(u32, u64)>> {
let mut out = Vec::with_capacity(self.header.entry_count as usize);
for b in 0..self.header.block_count {
let blk = self.decode_block_uncached(backing, zstd_dicts, b)?;
for (&s, &r) in blk.starts.iter().zip(blk.rids.iter()) {
out.push((s, r));
}
}
Ok(out)
}
#[inline]
pub fn lookup(
&self,
backing: &Backing<'_>,
zstd_dicts: &[(u32, Vec<u8>)],
key: u32,
) -> Result<u64> {
if self.first_ips.is_empty() || key < self.first_ips[0] {
return Ok(0);
}
let block_idx = self.locate_block(key);
let block = self.get_or_decode_block(backing, zstd_dicts, block_idx)?;
let pos = block.starts.partition_point(|&s| s <= key);
if pos == 0 {
Ok(0)
} else {
Ok(block.rids[pos - 1])
}
}
#[inline]
fn locate_block(&self, key: u32) -> u32 {
if !self.l1_buckets.is_empty() {
let p = (key >> (32 - self.header.l1_bits)) as usize;
let lo = self.l1_buckets[p] as usize;
let hi = self.l1_buckets[p + 1] as usize;
if lo == hi {
return lo as u32;
}
let rel = self.first_ips[lo..=hi].partition_point(|&ip| ip <= key);
return (lo + rel.saturating_sub(1)) as u32;
}
let pos = self.first_ips.partition_point(|&ip| ip <= key);
pos.saturating_sub(1) as u32
}
fn get_or_decode_block(
&self,
backing: &Backing<'_>,
zstd_dicts: &[(u32, Vec<u8>)],
block_idx: u32,
) -> Result<Arc<DecodedBlockU32>> {
if let Some(hit) = self.cache.get(&block_idx) {
return Ok(hit);
}
let decoded = Arc::new(self.decode_block_uncached(backing, zstd_dicts, block_idx)?);
self.cache.put(block_idx, Arc::clone(&decoded));
Ok(decoded)
}
fn decode_block_uncached(
&self,
backing: &Backing<'_>,
zstd_dicts: &[(u32, Vec<u8>)],
block_idx: u32,
) -> Result<DecodedBlockU32> {
let b = block_idx as usize;
let rel_start = self.block_offsets[b];
let rel_end = self.block_offsets[b + 1];
let block_len = (rel_end - rel_start) as usize;
let raw_block = backing.read_slice(self.blocks_base_offset + rel_start, block_len)?;
if raw_block.len() < 4 {
return Err(FormatError::UnexpectedEof.into());
}
let starts_blob_len =
u32::from_le_bytes([raw_block[0], raw_block[1], raw_block[2], raw_block[3]]) as usize;
if 4 + starts_blob_len > raw_block.len() {
return Err(FormatError::OutOfBounds("starts_blob_len").into());
}
let starts_blob = &raw_block[4..4 + starts_blob_len];
let rids_blob = &raw_block[4 + starts_blob_len..];
let n = self.entries_in_block(block_idx);
let s_dict = resolve_dict(zstd_dicts, self.header.starts_zstd_dict_id)?;
let raw_starts =
decompress_with_dict(self.header.starts_codec, starts_blob, Some(n * 3), s_dict)?;
let mut starts = Vec::with_capacity(n);
let mut cur = self.first_ips[b];
starts.push(cur);
let mut pos = 0usize;
for _ in 1..n {
let (delta, used) = read_uvarint(&raw_starts[pos..])?;
pos += used;
cur = cur
.checked_add(delta as u32)
.ok_or_else(|| ReaderError::Corrupt("IPv4 delta overflow".into()))?;
starts.push(cur);
}
let r_dict = resolve_dict(zstd_dicts, self.header.rids_zstd_dict_id)?;
let raw_rids =
decompress_with_dict(self.header.rids_codec, rids_blob, Some(n * 3), r_dict)?;
let rids = decode_rids(&raw_rids, n)?;
Ok(DecodedBlockU32 { starts, rids })
}
#[inline]
fn entries_in_block(&self, block_idx: u32) -> usize {
let start = (block_idx as u64) * (self.header.block_size as u64);
let rem = self.header.entry_count.saturating_sub(start);
rem.min(self.header.block_size as u64) as usize
}
}
pub struct Ipv6IndexReader {
header: IndexHeader,
l1_buckets: Vec<u32>,
first_ips: Vec<u64>,
block_offsets: Vec<u64>,
blocks_base_offset: u64,
cache: ShardedLruCache<u32, Arc<DecodedBlockU64>>,
}
impl Ipv6IndexReader {
pub fn parse(
backing: &Backing<'_>,
section_offset: u64,
section_len: u64,
cache_blocks: usize,
) -> Result<Self> {
let hdr_bytes = backing.read_slice(section_offset, coip_format::INDEX_HEADER_SIZE)?;
let mut c = Cursor::new(&hdr_bytes);
let header = IndexHeader::decode(&mut c)?;
let block_count = header.block_count as usize;
let l1_count = if header.l1_bits > 0 {
(1usize << header.l1_bits) + 1
} else {
0
};
let dir_bytes_len = l1_count * 4 + block_count * 8 + (block_count + 1) * 8;
let dir_offset = section_offset + (coip_format::INDEX_HEADER_SIZE as u64);
if (coip_format::INDEX_HEADER_SIZE as u64) + (dir_bytes_len as u64) > section_len {
return Err(FormatError::UnexpectedEof.into());
}
let dir_bytes = backing.read_slice(dir_offset, dir_bytes_len)?;
let mut dc = Cursor::new(&dir_bytes);
let mut l1_buckets = Vec::with_capacity(l1_count);
for _ in 0..l1_count {
l1_buckets.push(dc.read_u32()?);
}
let mut first_ips = Vec::with_capacity(block_count);
for _ in 0..block_count {
first_ips.push(dc.read_u64()?);
}
let mut block_offsets = Vec::with_capacity(block_count + 1);
for _ in 0..=block_count {
block_offsets.push(dc.read_u64()?);
}
let blocks_base_offset = dir_offset + (dir_bytes_len as u64);
Ok(Self {
header,
l1_buckets,
first_ips,
block_offsets,
blocks_base_offset,
cache: ShardedLruCache::new(cache_blocks),
})
}
pub fn entry_count(&self) -> u64 {
self.header.entry_count
}
pub fn block_count(&self) -> u32 {
self.header.block_count
}
pub fn header(&self) -> &IndexHeader {
&self.header
}
pub fn clear_cache(&self) {
self.cache.clear();
}
pub fn collect_transitions(
&self,
backing: &Backing<'_>,
zstd_dicts: &[(u32, Vec<u8>)],
) -> Result<Vec<(u64, u64)>> {
let mut out = Vec::with_capacity(self.header.entry_count as usize);
for b in 0..self.header.block_count {
let blk = self.decode_block_uncached(backing, zstd_dicts, b)?;
for (&s, &r) in blk.starts.iter().zip(blk.rids.iter()) {
out.push((s, r));
}
}
Ok(out)
}
#[inline]
pub fn lookup(
&self,
backing: &Backing<'_>,
zstd_dicts: &[(u32, Vec<u8>)],
key: u64,
) -> Result<u64> {
if self.first_ips.is_empty() || key < self.first_ips[0] {
return Ok(0);
}
let block_idx = self.locate_block(key);
let block = self.get_or_decode_block(backing, zstd_dicts, block_idx)?;
let pos = block.starts.partition_point(|&s| s <= key);
if pos == 0 {
Ok(0)
} else {
Ok(block.rids[pos - 1])
}
}
#[inline]
fn locate_block(&self, key: u64) -> u32 {
if !self.l1_buckets.is_empty() {
let p = (key >> (64 - self.header.l1_bits)) as usize;
let lo = self.l1_buckets[p] as usize;
let hi = self.l1_buckets[p + 1] as usize;
if lo == hi {
return lo as u32;
}
let rel = self.first_ips[lo..=hi].partition_point(|&ip| ip <= key);
return (lo + rel.saturating_sub(1)) as u32;
}
let pos = self.first_ips.partition_point(|&ip| ip <= key);
pos.saturating_sub(1) as u32
}
fn get_or_decode_block(
&self,
backing: &Backing<'_>,
zstd_dicts: &[(u32, Vec<u8>)],
block_idx: u32,
) -> Result<Arc<DecodedBlockU64>> {
if let Some(hit) = self.cache.get(&block_idx) {
return Ok(hit);
}
let decoded = Arc::new(self.decode_block_uncached(backing, zstd_dicts, block_idx)?);
self.cache.put(block_idx, Arc::clone(&decoded));
Ok(decoded)
}
fn decode_block_uncached(
&self,
backing: &Backing<'_>,
zstd_dicts: &[(u32, Vec<u8>)],
block_idx: u32,
) -> Result<DecodedBlockU64> {
let b = block_idx as usize;
let rel_start = self.block_offsets[b];
let rel_end = self.block_offsets[b + 1];
let block_len = (rel_end - rel_start) as usize;
let raw_block = backing.read_slice(self.blocks_base_offset + rel_start, block_len)?;
if raw_block.len() < 4 {
return Err(FormatError::UnexpectedEof.into());
}
let starts_blob_len =
u32::from_le_bytes([raw_block[0], raw_block[1], raw_block[2], raw_block[3]]) as usize;
if 4 + starts_blob_len > raw_block.len() {
return Err(FormatError::OutOfBounds("starts_blob_len").into());
}
let starts_blob = &raw_block[4..4 + starts_blob_len];
let rids_blob = &raw_block[4 + starts_blob_len..];
let n = self.entries_in_block(block_idx);
let s_dict = resolve_dict(zstd_dicts, self.header.starts_zstd_dict_id)?;
let raw_starts =
decompress_with_dict(self.header.starts_codec, starts_blob, Some(n * 4), s_dict)?;
let mut starts = Vec::with_capacity(n);
let mut cur = self.first_ips[b];
starts.push(cur);
let mut pos = 0usize;
for _ in 1..n {
let (delta, used) = read_uvarint(&raw_starts[pos..])?;
pos += used;
cur = cur
.checked_add(delta)
.ok_or_else(|| ReaderError::Corrupt("IPv6 delta overflow".into()))?;
starts.push(cur);
}
let r_dict = resolve_dict(zstd_dicts, self.header.rids_zstd_dict_id)?;
let raw_rids =
decompress_with_dict(self.header.rids_codec, rids_blob, Some(n * 3), r_dict)?;
let rids = decode_rids(&raw_rids, n)?;
Ok(DecodedBlockU64 { starts, rids })
}
#[inline]
fn entries_in_block(&self, block_idx: u32) -> usize {
let start = (block_idx as u64) * (self.header.block_size as u64);
let rem = self.header.entry_count.saturating_sub(start);
rem.min(self.header.block_size as u64) as usize
}
}
fn decode_local_dict_table(raw: &[u8], pos: &mut usize) -> Result<Vec<u64>> {
let (dict_len_u64, used) = read_uvarint(&raw[*pos..])?;
*pos += used;
let dict_len = dict_len_u64 as usize;
if dict_len == 0 || dict_len > 65_536 {
return Err(ReaderError::Corrupt(format!(
"invalid LocalDict len {dict_len}"
)));
}
let mut dict = Vec::with_capacity(dict_len);
let (first, used) = read_uvarint(&raw[*pos..])?;
*pos += used;
dict.push(first);
let mut cur = first;
for _ in 1..dict_len {
let (delta, used) = read_uvarint(&raw[*pos..])?;
*pos += used;
cur = cur
.checked_add(delta)
.ok_or_else(|| ReaderError::Corrupt("LocalDict delta overflow".into()))?;
dict.push(cur);
}
Ok(dict)
}
fn decode_rids(raw: &[u8], n: usize) -> Result<Vec<u64>> {
if n == 0 {
return Ok(Vec::new());
}
if raw.is_empty() {
return Err(FormatError::UnexpectedEof.into());
}
let mode = RidMode::from_u8(raw[0])?;
let mut pos = 1usize;
let mut out = Vec::with_capacity(n);
match mode {
RidMode::ZigZagDeltaVarint => {
let (first, used) = read_uvarint(&raw[pos..])?;
pos += used;
out.push(first);
let mut cur = first;
for _ in 1..n {
let (delta, used) = read_svarint(&raw[pos..])?;
pos += used;
cur = cur.wrapping_add(delta as u64);
out.push(cur);
}
}
RidMode::LocalDict => {
let dict = decode_local_dict_table(raw, &mut pos)?;
if dict.len() <= 256 {
if pos + n > raw.len() {
return Err(FormatError::UnexpectedEof.into());
}
for &idx in &raw[pos..pos + n] {
out.push(
*dict
.get(idx as usize)
.ok_or_else(|| ReaderError::Corrupt("LocalDict u8 idx OOB".into()))?,
);
}
} else {
if pos + n * 2 > raw.len() {
return Err(FormatError::UnexpectedEof.into());
}
for chunk in raw[pos..pos + n * 2].chunks_exact(2) {
let idx = u16::from_le_bytes([chunk[0], chunk[1]]) as usize;
out.push(
*dict
.get(idx)
.ok_or_else(|| ReaderError::Corrupt("LocalDict u16 idx OOB".into()))?,
);
}
}
}
RidMode::Rle => {
while out.len() < n {
let (rid, u1) = read_uvarint(&raw[pos..])?;
pos += u1;
let (run, u2) = read_uvarint(&raw[pos..])?;
pos += u2;
let run = run as usize;
if out.len() + run > n {
return Err(ReaderError::Corrupt("RLE run exceeds block size".into()));
}
out.resize(out.len() + run, rid);
}
}
RidMode::ZeroSkipDelta => {
let bm_len = n.div_ceil(8);
if pos + bm_len > raw.len() {
return Err(FormatError::UnexpectedEof.into());
}
let bitmap = &raw[pos..pos + bm_len];
pos += bm_len;
let mut prev_nz: Option<u64> = None;
for i in 0..n {
if ((bitmap[i >> 3] >> (i & 7)) & 1) == 0 {
out.push(0);
} else {
let val = match prev_nz {
None => {
let (v, u) = read_uvarint(&raw[pos..])?;
pos += u;
v
}
Some(p) => {
let (d, u) = read_svarint(&raw[pos..])?;
pos += u;
p.wrapping_add(d as u64)
}
};
prev_nz = Some(val);
out.push(val);
}
}
}
RidMode::LocalDictSplit => {
let dict = decode_local_dict_table(raw, &mut pos)?;
if pos + n * 2 > raw.len() {
return Err(FormatError::UnexpectedEof.into());
}
let lo = &raw[pos..pos + n];
let hi = &raw[pos + n..pos + n * 2];
for i in 0..n {
let idx = ((hi[i] as usize) << 8) | (lo[i] as usize);
out.push(
*dict
.get(idx)
.ok_or_else(|| ReaderError::Corrupt("LocalDictSplit idx OOB".into()))?,
);
}
}
}
Ok(out)
}