use std::collections::{BTreeMap, HashMap};
use coip_format::Value;
use rayon::prelude::*;
use crate::error::{BuilderError, Result};
use crate::mmdb::{V4Interval, V6HostInterval, V6Interval};
#[derive(Debug, Clone, Default)]
pub struct PruneConfig {
pub keep_fields: Option<Vec<String>>,
}
impl PruneConfig {
pub fn is_noop(&self) -> bool {
self.keep_fields.is_none()
}
}
#[derive(Debug, Clone)]
enum KeepNode {
All,
Fields(BTreeMap<String, KeepNode>),
}
impl KeepNode {
fn compile(paths: &[String]) -> Result<Self> {
let mut root = KeepNode::Fields(BTreeMap::new());
let mut count = 0usize;
for raw in paths {
let p = raw.trim();
if p.is_empty() {
return Err(BuilderError::InvalidInput("empty keep_fields path".into()));
}
if p == "*" {
return Ok(KeepNode::All);
}
let segs: Vec<&str> = p.split('.').collect();
if segs.iter().any(|s| s.is_empty()) {
return Err(BuilderError::InvalidInput(format!(
"malformed keep_fields path '{p}'"
)));
}
insert_keep(&mut root, &segs);
count += 1;
}
if count == 0 {
return Err(BuilderError::InvalidInput(
"keep_fields must contain at least one path".into(),
));
}
Ok(root)
}
fn child(&self, name: &str) -> Option<&KeepNode> {
match self {
Self::All => Some(&KeepNode::All),
Self::Fields(m) => m.get(name),
}
}
}
fn insert_keep(node: &mut KeepNode, segs: &[&str]) {
if segs.is_empty() {
*node = KeepNode::All;
return;
}
match node {
KeepNode::All => {}
KeepNode::Fields(map) => {
if segs.len() == 1 {
map.insert(segs[0].to_owned(), KeepNode::All);
} else {
let entry = map
.entry(segs[0].to_owned())
.or_insert_with(|| KeepNode::Fields(BTreeMap::new()));
insert_keep(entry, &segs[1..]);
}
}
}
}
fn prune_map(map: &BTreeMap<String, Value>, keep: &KeepNode) -> Option<BTreeMap<String, Value>> {
let was_empty = map.is_empty();
let mut out = BTreeMap::new();
for (k, v) in map {
let Some(child_keep) = keep.child(k) else {
continue;
};
if let Some(pruned_v) = prune_value(v, child_keep) {
out.insert(k.clone(), pruned_v);
}
}
if out.is_empty() && !was_empty {
None
} else {
Some(out)
}
}
fn prune_value(val: &Value, keep: &KeepNode) -> Option<Value> {
match val {
Value::Map(m) => prune_map(m, keep).map(Value::Map),
Value::Array(arr) => {
let mut out = Vec::with_capacity(arr.len());
for item in arr {
if let Some(p) = prune_value(item, keep) {
out.push(p);
}
}
if out.is_empty() && !arr.is_empty() {
None
} else {
Some(Value::Array(out))
}
}
other => Some(other.clone()),
}
}
pub fn apply_pruning(
prune: &PruneConfig,
unique_records: Vec<BTreeMap<String, Value>>,
v4_intervals: &mut Vec<V4Interval>,
v6_intervals: &mut Vec<V6Interval>,
v6_host_ext: &mut [V6HostInterval],
) -> Result<Vec<BTreeMap<String, Value>>> {
if prune.is_noop() {
return Ok(unique_records);
}
let keep_root = match &prune.keep_fields {
Some(paths) => KeepNode::compile(paths)?,
None => KeepNode::All,
};
let pruned: Vec<Option<BTreeMap<String, Value>>> = unique_records
.par_iter()
.map(|rec| prune_map(rec, &keep_root))
.collect();
let mut old_to_new = vec![0u32; unique_records.len() + 1];
let mut dedup: HashMap<BTreeMap<String, Value>, u32> = HashMap::new();
let mut new_records: Vec<BTreeMap<String, Value>> = Vec::new();
for (idx, opt_rec) in pruned.into_iter().enumerate() {
if let Some(rec) = opt_rec {
let new_id = if let Some(&existing) = dedup.get(&rec) {
existing
} else {
let id = (new_records.len() + 1) as u32;
dedup.insert(rec.clone(), id);
new_records.push(rec);
id
};
old_to_new[idx + 1] = new_id;
} else {
old_to_new[idx + 1] = 0;
}
}
v4_intervals.retain_mut(|iv| {
iv.record_idx = old_to_new[iv.record_idx as usize];
iv.record_idx != 0
});
v6_intervals.retain_mut(|iv| {
iv.record_idx = old_to_new[iv.record_idx as usize];
iv.record_idx != 0
});
for iv in v6_host_ext.iter_mut() {
iv.record_idx = old_to_new[iv.record_idx as usize];
}
Ok(new_records)
}