use std::collections::BTreeMap;
use crate::error::{ReaderError, Result};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProjectionNode {
All,
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)),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Projection {
pub(crate) root: ProjectionNode,
}
impl Projection {
pub fn all() -> Self {
Self {
root: ProjectionNode::All,
}
}
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..]);
}
}
}
}