coip-builder 0.1.0

Generic columnar .coi builder and 100% lossless MaxMind .mmdb importer
Documentation
//! Exact Longest-Prefix-Match (LPM) interval resolution for overlapping IPv4/IPv6 CIDRs.
//!
//! Because aligned CIDR prefixes never partially overlap (any two prefixes are either disjoint
//! or strictly nested), an O(N log N) stack-based sweep resolves arbitrary overlapping CIDRs,
//! duplicate overrides (last-insert-wins), and explicit delete holes (`record_idx == 0`).

use crate::mmdb::{V4Interval, V6HostInterval, V6Interval};

/// Resolve arbitrary (potentially overlapping or unsorted) IPv4 CIDR intervals using exact LPM.
/// Output intervals are strictly sorted, disjoint, non-zero (`record_idx > 0`), and merged where adjacent.
pub fn resolve_lpm_v4(mut intervals: Vec<V4Interval>) -> Vec<V4Interval> {
    if intervals.is_empty() {
        return intervals;
    }
    // Fast path: MMDB trie extraction already yields strictly sorted disjoint non-zero intervals.
    if is_disjoint_sorted_v4(&intervals) {
        return intervals;
    }

    // Attach original insertion order so identical (start, end) CIDRs follow last-insert-wins.
    let mut indexed: Vec<(V4Interval, usize)> = intervals
        .drain(..)
        .enumerate()
        .map(|(seq, iv)| (iv, seq))
        .collect();
    indexed.sort_unstable_by(|(a, sa), (b, sb)| {
        a.start
            .cmp(&b.start)
            .then_with(|| b.end.cmp(&a.end))
            .then_with(|| sa.cmp(sb))
    });

    let mut out: Vec<V4Interval> = Vec::with_capacity(indexed.len());
    let mut stack: Vec<(u32, u32)> = Vec::with_capacity(33); // (end, record_idx)
    let mut cursor: Option<u32> = None;

    let mut emit = |s: u32, e: u32, rid: u32| {
        if rid == 0 || s > e {
            return;
        }
        if let Some(last) = out.last_mut() {
            if last.record_idx == rid && last.end.checked_add(1) == Some(s) {
                last.end = e;
                return;
            }
        }
        out.push(V4Interval {
            start: s,
            end: e,
            record_idx: rid,
        });
    };

    for (iv, _) in indexed {
        while let Some(&(top_end, top_rid)) = stack.last() {
            if top_end < iv.start {
                if let Some(cur) = cursor {
                    emit(cur, top_end, top_rid);
                }
                cursor = top_end.checked_add(1);
                stack.pop();
            } else {
                break;
            }
        }

        if let Some(&mut (top_end, ref mut top_rid)) = stack.last_mut() {
            if let Some(cur) = cursor {
                if cur < iv.start {
                    emit(cur, iv.start - 1, *top_rid);
                }
            }
            cursor = Some(iv.start);
            if top_end == iv.end {
                *top_rid = iv.record_idx;
            } else {
                stack.push((iv.end, iv.record_idx));
            }
        } else {
            cursor = Some(iv.start);
            stack.push((iv.end, iv.record_idx));
        }
    }

    while let Some((top_end, top_rid)) = stack.pop() {
        if let Some(cur) = cursor {
            emit(cur, top_end, top_rid);
        }
        cursor = top_end.checked_add(1);
    }

    out
}

/// Resolve arbitrary overlapping IPv6 `<= /64` CIDR intervals using exact LPM.
pub fn resolve_lpm_v6(mut intervals: Vec<V6Interval>) -> Vec<V6Interval> {
    if intervals.is_empty() {
        return intervals;
    }
    if is_disjoint_sorted_v6(&intervals) {
        return intervals;
    }

    let mut indexed: Vec<(V6Interval, usize)> = intervals
        .drain(..)
        .enumerate()
        .map(|(seq, iv)| (iv, seq))
        .collect();
    indexed.sort_unstable_by(|(a, sa), (b, sb)| {
        a.start
            .cmp(&b.start)
            .then_with(|| b.end.cmp(&a.end))
            .then_with(|| sa.cmp(sb))
    });

    let mut out: Vec<V6Interval> = Vec::with_capacity(indexed.len());
    let mut stack: Vec<(u64, u32)> = Vec::with_capacity(65);
    let mut cursor: Option<u64> = None;

    let mut emit = |s: u64, e: u64, rid: u32| {
        if rid == 0 || s > e {
            return;
        }
        if let Some(last) = out.last_mut() {
            if last.record_idx == rid && last.end.checked_add(1) == Some(s) {
                last.end = e;
                return;
            }
        }
        out.push(V6Interval {
            start: s,
            end: e,
            record_idx: rid,
        });
    };

    for (iv, _) in indexed {
        while let Some(&(top_end, top_rid)) = stack.last() {
            if top_end < iv.start {
                if let Some(cur) = cursor {
                    emit(cur, top_end, top_rid);
                }
                cursor = top_end.checked_add(1);
                stack.pop();
            } else {
                break;
            }
        }

        if let Some(&mut (top_end, ref mut top_rid)) = stack.last_mut() {
            if let Some(cur) = cursor {
                if cur < iv.start {
                    emit(cur, iv.start - 1, *top_rid);
                }
            }
            cursor = Some(iv.start);
            if top_end == iv.end {
                *top_rid = iv.record_idx;
            } else {
                stack.push((iv.end, iv.record_idx));
            }
        } else {
            cursor = Some(iv.start);
            stack.push((iv.end, iv.record_idx));
        }
    }

    while let Some((top_end, top_rid)) = stack.pop() {
        if let Some(cur) = cursor {
            emit(cur, top_end, top_rid);
        }
        cursor = top_end.checked_add(1);
    }

    out
}

/// Resolve arbitrary overlapping IPv6 `> /64` (`Ipv6HostExt`) overrides using exact LPM.
/// Preserves explicit `record_idx == 0` entries so fine-grained holes can punch through a broader `<= /64` prefix.
pub fn resolve_lpm_v6_host(mut intervals: Vec<V6HostInterval>) -> Vec<V6HostInterval> {
    if intervals.is_empty() {
        return intervals;
    }
    if is_disjoint_sorted_v6_host(&intervals) {
        return intervals;
    }

    let mut indexed: Vec<(V6HostInterval, usize)> = intervals
        .drain(..)
        .enumerate()
        .map(|(seq, iv)| (iv, seq))
        .collect();
    indexed.sort_unstable_by(|(a, sa), (b, sb)| {
        a.start
            .cmp(&b.start)
            .then_with(|| b.end.cmp(&a.end))
            .then_with(|| sa.cmp(sb))
    });

    let mut out: Vec<V6HostInterval> = Vec::with_capacity(indexed.len());
    let mut stack: Vec<(u128, u32)> = Vec::with_capacity(129);
    let mut cursor: Option<u128> = None;

    let mut emit = |s: u128, e: u128, rid: u32| {
        if s > e {
            return;
        }
        if let Some(last) = out.last_mut() {
            if last.record_idx == rid && last.end.checked_add(1) == Some(s) {
                last.end = e;
                return;
            }
        }
        out.push(V6HostInterval {
            start: s,
            end: e,
            record_idx: rid,
        });
    };

    for (iv, _) in indexed {
        while let Some(&(top_end, top_rid)) = stack.last() {
            if top_end < iv.start {
                if let Some(cur) = cursor {
                    emit(cur, top_end, top_rid);
                }
                cursor = top_end.checked_add(1);
                stack.pop();
            } else {
                break;
            }
        }

        if let Some(&mut (top_end, ref mut top_rid)) = stack.last_mut() {
            if let Some(cur) = cursor {
                if cur < iv.start {
                    emit(cur, iv.start - 1, *top_rid);
                }
            }
            cursor = Some(iv.start);
            if top_end == iv.end {
                *top_rid = iv.record_idx;
            } else {
                stack.push((iv.end, iv.record_idx));
            }
        } else {
            cursor = Some(iv.start);
            stack.push((iv.end, iv.record_idx));
        }
    }

    while let Some((top_end, top_rid)) = stack.pop() {
        if let Some(cur) = cursor {
            emit(cur, top_end, top_rid);
        }
        cursor = top_end.checked_add(1);
    }

    out
}

fn is_disjoint_sorted_v4(intervals: &[V4Interval]) -> bool {
    if intervals.iter().any(|iv| iv.record_idx == 0) {
        return false;
    }
    intervals.windows(2).all(|w| w[0].end < w[1].start)
}

fn is_disjoint_sorted_v6(intervals: &[V6Interval]) -> bool {
    if intervals.iter().any(|iv| iv.record_idx == 0) {
        return false;
    }
    intervals.windows(2).all(|w| w[0].end < w[1].start)
}

fn is_disjoint_sorted_v6_host(intervals: &[V6HostInterval]) -> bool {
    intervals.windows(2).all(|w| w[0].end < w[1].start)
}

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

    #[test]
    fn test_lpm_v4_nested_override_and_hole() {
        let input = vec![
            // Broad 0.0.0.0/0 -> 1
            V4Interval {
                start: 0,
                end: u32::MAX,
                record_idx: 1,
            },
            // 10.0.0.0/8 -> 2
            V4Interval {
                start: 0x0A00_0000,
                end: 0x0AFF_FFFF,
                record_idx: 2,
            },
            // 10.1.0.0/16 -> 0 (explicit delete hole!)
            V4Interval {
                start: 0x0A01_0000,
                end: 0x0A01_FFFF,
                record_idx: 0,
            },
            // 10.1.1.1/32 -> 3 (override inside hole!)
            V4Interval {
                start: 0x0A01_0101,
                end: 0x0A01_0101,
                record_idx: 3,
            },
            // Duplicate 10.1.1.1/32 -> 4 (last insert wins!)
            V4Interval {
                start: 0x0A01_0101,
                end: 0x0A01_0101,
                record_idx: 4,
            },
            // 255.255.255.255/32 -> 5 (u32::MAX boundary)
            V4Interval {
                start: u32::MAX,
                end: u32::MAX,
                record_idx: 5,
            },
        ];
        let out = resolve_lpm_v4(input);
        assert_eq!(out.len(), 6);
        assert_eq!(
            (out[0].start, out[0].end, out[0].record_idx),
            (0, 0x09FF_FFFF, 1)
        );
        assert_eq!(
            (out[1].start, out[1].end, out[1].record_idx),
            (0x0A00_0000, 0x0A00_FFFF, 2)
        );
        assert_eq!(
            (out[2].start, out[2].end, out[2].record_idx),
            (0x0A01_0101, 0x0A01_0101, 4)
        );
        assert_eq!(
            (out[3].start, out[3].end, out[3].record_idx),
            (0x0A02_0000, 0x0AFF_FFFF, 2)
        );
        assert_eq!(
            (out[4].start, out[4].end, out[4].record_idx),
            (0x0B00_0000, u32::MAX - 1, 1)
        );
        assert_eq!(
            (out[5].start, out[5].end, out[5].record_idx),
            (u32::MAX, u32::MAX, 5)
        );
    }

    #[test]
    fn test_lpm_v6_host_preserves_explicit_zero_hole() {
        let input = vec![
            V6HostInterval {
                start: 100,
                end: 103,
                record_idx: 1,
            },
            V6HostInterval {
                start: 101,
                end: 101,
                record_idx: 0,
            },
        ];
        let out = resolve_lpm_v6_host(input);
        assert_eq!(out.len(), 3);
        assert_eq!((out[0].start, out[0].end, out[0].record_idx), (100, 100, 1));
        assert_eq!((out[1].start, out[1].end, out[1].record_idx), (101, 101, 0));
        assert_eq!((out[2].start, out[2].end, out[2].record_idx), (102, 103, 1));
    }
}