coip-reader 0.2.0

High-performance read-only reader for COI (.coi) columnar IP databases with projection, LRU caching, and serde support
Documentation
//! Compiled Column Projection for skipping unrequested columns and dictionaries.

use std::collections::BTreeMap;

use crate::error::{ReaderError, Result};

/// Compiled tree describing which fields/subtrees to materialize during lookup.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProjectionNode {
    /// Materialize the entire subtree rooted here.
    All,
    /// Materialize only the named child fields/keys.
    Fields(BTreeMap<String, ProjectionNode>),
}

impl ProjectionNode {
    #[inline]
    pub fn child(&self, name: &str) -> Option<&ProjectionNode> {
        match self {
            Self::All => Some(&ProjectionNode::All),
            Self::Fields(map) => map.get(name),
        }
    }

    #[inline]
    pub fn selects_any_of(&self, names: &[String]) -> bool {
        match self {
            Self::All => true,
            Self::Fields(map) => names.iter().any(|n| map.contains_key(n)),
        }
    }
}

/// Compiled column projection reusable across millions of lookups with zero parsing overhead.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Projection {
    pub(crate) root: ProjectionNode,
}

impl Projection {
    /// Select all fields (equivalent to unprojected lookup).
    pub fn all() -> Self {
        Self {
            root: ProjectionNode::All,
        }
    }

    /// Compile dot-separated field paths, e.g.:
    /// `&["country.iso_code", "location.latitude", "location.longitude", "city.names.en"]`.
    pub fn from_paths<I, S>(paths: I) -> Result<Self>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let mut root = ProjectionNode::Fields(BTreeMap::new());
        let mut count = 0usize;
        for raw_path in paths {
            let path = raw_path.as_ref().trim();
            if path.is_empty() {
                return Err(ReaderError::InvalidProjection(
                    "empty projection path".into(),
                ));
            }
            if path == "*" {
                return Ok(Self::all());
            }
            let segments: Vec<&str> = path.split('.').collect();
            if segments.iter().any(|s| s.is_empty()) {
                return Err(ReaderError::InvalidProjection(format!(
                    "malformed projection path '{path}'"
                )));
            }
            insert_path(&mut root, &segments);
            count += 1;
        }
        if count == 0 {
            return Err(ReaderError::InvalidProjection(
                "at least one projection path is required".into(),
            ));
        }
        Ok(Self { root })
    }
}

fn insert_path(node: &mut ProjectionNode, segments: &[&str]) {
    if segments.is_empty() {
        *node = ProjectionNode::All;
        return;
    }
    match node {
        ProjectionNode::All => {}
        ProjectionNode::Fields(map) => {
            if segments.len() == 1 {
                map.insert(segments[0].to_owned(), ProjectionNode::All);
            } else {
                let entry = map
                    .entry(segments[0].to_owned())
                    .or_insert_with(|| ProjectionNode::Fields(BTreeMap::new()));
                insert_path(entry, &segments[1..]);
            }
        }
    }
}