1use std::collections::{BTreeMap, HashMap};
5
6use coip_format::Value;
7use rayon::prelude::*;
8
9use crate::error::{BuilderError, Result};
10use crate::mmdb::{V4Interval, V6HostInterval, V6Interval};
11
12#[derive(Debug, Clone, Default)]
14pub struct PruneConfig {
15 pub keep_fields: Option<Vec<String>>,
18}
19
20impl PruneConfig {
21 pub fn is_noop(&self) -> bool {
22 self.keep_fields.is_none()
23 }
24}
25
26#[derive(Debug, Clone)]
27enum KeepNode {
28 All,
29 Fields(BTreeMap<String, KeepNode>),
30}
31
32impl KeepNode {
33 fn compile(paths: &[String]) -> Result<Self> {
34 let mut root = KeepNode::Fields(BTreeMap::new());
35 let mut count = 0usize;
36 for raw in paths {
37 let p = raw.trim();
38 if p.is_empty() {
39 return Err(BuilderError::InvalidInput("empty keep_fields path".into()));
40 }
41 if p == "*" {
42 return Ok(KeepNode::All);
43 }
44 let segs: Vec<&str> = p.split('.').collect();
45 if segs.iter().any(|s| s.is_empty()) {
46 return Err(BuilderError::InvalidInput(format!(
47 "malformed keep_fields path '{p}'"
48 )));
49 }
50 insert_keep(&mut root, &segs);
51 count += 1;
52 }
53 if count == 0 {
54 return Err(BuilderError::InvalidInput(
55 "keep_fields must contain at least one path".into(),
56 ));
57 }
58 Ok(root)
59 }
60
61 fn child(&self, name: &str) -> Option<&KeepNode> {
62 match self {
63 Self::All => Some(&KeepNode::All),
64 Self::Fields(m) => m.get(name),
65 }
66 }
67}
68
69fn insert_keep(node: &mut KeepNode, segs: &[&str]) {
70 if segs.is_empty() {
71 *node = KeepNode::All;
72 return;
73 }
74 match node {
75 KeepNode::All => {}
76 KeepNode::Fields(map) => {
77 if segs.len() == 1 {
78 map.insert(segs[0].to_owned(), KeepNode::All);
79 } else {
80 let entry = map
81 .entry(segs[0].to_owned())
82 .or_insert_with(|| KeepNode::Fields(BTreeMap::new()));
83 insert_keep(entry, &segs[1..]);
84 }
85 }
86 }
87}
88
89fn prune_map(map: &BTreeMap<String, Value>, keep: &KeepNode) -> Option<BTreeMap<String, Value>> {
90 let was_empty = map.is_empty();
91 let mut out = BTreeMap::new();
92 for (k, v) in map {
93 let Some(child_keep) = keep.child(k) else {
94 continue;
95 };
96 if let Some(pruned_v) = prune_value(v, child_keep) {
97 out.insert(k.clone(), pruned_v);
98 }
99 }
100 if out.is_empty() && !was_empty {
101 None
102 } else {
103 Some(out)
104 }
105}
106
107fn prune_value(val: &Value, keep: &KeepNode) -> Option<Value> {
108 match val {
109 Value::Map(m) => prune_map(m, keep).map(Value::Map),
110 Value::Array(arr) => {
111 let mut out = Vec::with_capacity(arr.len());
112 for item in arr {
113 if let Some(p) = prune_value(item, keep) {
114 out.push(p);
115 }
116 }
117 if out.is_empty() && !arr.is_empty() {
118 None
119 } else {
120 Some(Value::Array(out))
121 }
122 }
123 other => Some(other.clone()),
124 }
125}
126
127pub fn apply_pruning(
130 prune: &PruneConfig,
131 unique_records: Vec<BTreeMap<String, Value>>,
132 v4_intervals: &mut Vec<V4Interval>,
133 v6_intervals: &mut Vec<V6Interval>,
134 v6_host_ext: &mut [V6HostInterval],
135) -> Result<Vec<BTreeMap<String, Value>>> {
136 if prune.is_noop() {
137 return Ok(unique_records);
138 }
139
140 let keep_root = match &prune.keep_fields {
141 Some(paths) => KeepNode::compile(paths)?,
142 None => KeepNode::All,
143 };
144
145 let pruned: Vec<Option<BTreeMap<String, Value>>> = unique_records
147 .par_iter()
148 .map(|rec| prune_map(rec, &keep_root))
149 .collect();
150
151 let mut old_to_new = vec![0u32; unique_records.len() + 1];
153 let mut dedup: HashMap<BTreeMap<String, Value>, u32> = HashMap::new();
154 let mut new_records: Vec<BTreeMap<String, Value>> = Vec::new();
155
156 for (idx, opt_rec) in pruned.into_iter().enumerate() {
157 if let Some(rec) = opt_rec {
158 let new_id = if let Some(&existing) = dedup.get(&rec) {
159 existing
160 } else {
161 let id = (new_records.len() + 1) as u32;
162 dedup.insert(rec.clone(), id);
163 new_records.push(rec);
164 id
165 };
166 old_to_new[idx + 1] = new_id;
167 } else {
168 old_to_new[idx + 1] = 0;
170 }
171 }
172
173 v4_intervals.retain_mut(|iv| {
175 iv.record_idx = old_to_new[iv.record_idx as usize];
176 iv.record_idx != 0
177 });
178 v6_intervals.retain_mut(|iv| {
179 iv.record_idx = old_to_new[iv.record_idx as usize];
180 iv.record_idx != 0
181 });
182 for iv in v6_host_ext.iter_mut() {
184 iv.record_idx = old_to_new[iv.record_idx as usize];
185 }
186
187 Ok(new_records)
188}