coip_reader/
projection.rs1use std::collections::BTreeMap;
4
5use crate::error::{ReaderError, Result};
6
7#[derive(Debug, Clone, PartialEq, Eq)]
9pub enum ProjectionNode {
10 All,
12 Fields(BTreeMap<String, ProjectionNode>),
14}
15
16impl ProjectionNode {
17 #[inline]
18 pub fn child(&self, name: &str) -> Option<&ProjectionNode> {
19 match self {
20 Self::All => Some(&ProjectionNode::All),
21 Self::Fields(map) => map.get(name),
22 }
23 }
24
25 #[inline]
26 pub fn selects_any_of(&self, names: &[String]) -> bool {
27 match self {
28 Self::All => true,
29 Self::Fields(map) => names.iter().any(|n| map.contains_key(n)),
30 }
31 }
32}
33
34#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct Projection {
37 pub(crate) root: ProjectionNode,
38}
39
40impl Projection {
41 pub fn all() -> Self {
43 Self {
44 root: ProjectionNode::All,
45 }
46 }
47
48 pub fn from_paths<I, S>(paths: I) -> Result<Self>
51 where
52 I: IntoIterator<Item = S>,
53 S: AsRef<str>,
54 {
55 let mut root = ProjectionNode::Fields(BTreeMap::new());
56 let mut count = 0usize;
57 for raw_path in paths {
58 let path = raw_path.as_ref().trim();
59 if path.is_empty() {
60 return Err(ReaderError::InvalidProjection(
61 "empty projection path".into(),
62 ));
63 }
64 if path == "*" {
65 return Ok(Self::all());
66 }
67 let segments: Vec<&str> = path.split('.').collect();
68 if segments.iter().any(|s| s.is_empty()) {
69 return Err(ReaderError::InvalidProjection(format!(
70 "malformed projection path '{path}'"
71 )));
72 }
73 insert_path(&mut root, &segments);
74 count += 1;
75 }
76 if count == 0 {
77 return Err(ReaderError::InvalidProjection(
78 "at least one projection path is required".into(),
79 ));
80 }
81 Ok(Self { root })
82 }
83}
84
85fn insert_path(node: &mut ProjectionNode, segments: &[&str]) {
86 if segments.is_empty() {
87 *node = ProjectionNode::All;
88 return;
89 }
90 match node {
91 ProjectionNode::All => {}
92 ProjectionNode::Fields(map) => {
93 if segments.len() == 1 {
94 map.insert(segments[0].to_owned(), ProjectionNode::All);
95 } else {
96 let entry = map
97 .entry(segments[0].to_owned())
98 .or_insert_with(|| ProjectionNode::Fields(BTreeMap::new()));
99 insert_path(entry, &segments[1..]);
100 }
101 }
102 }
103}