use std::collections::BTreeMap;
use serde_json::Value;
const MAX_DEPTH: usize = 32;
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Mask {
children: BTreeMap<String, Mask>,
whole: bool,
excluded: bool,
}
impl Mask {
#[must_use]
pub fn all() -> Self {
Self {
whole: true,
..Self::default()
}
}
#[must_use]
pub fn parse(fields: Option<&str>) -> Self {
let mut root = Self::default();
let mut any_included = false;
for path in fields.unwrap_or_default().split(',') {
let path = path.trim();
let (excluded, path) = match path.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, path),
};
let mut node = &mut root;
let mut walked = false;
for name in path
.split('.')
.map(str::trim)
.filter(|name| !name.is_empty())
.take(MAX_DEPTH)
{
node = node.children.entry(name.to_owned()).or_default();
walked = true;
}
if !walked {
continue;
}
if excluded {
node.excluded = true;
} else {
node.whole = true;
any_included = true;
}
}
if !any_included {
root.whole = true;
}
root
}
#[must_use]
pub fn is_all(&self) -> bool {
self.whole && self.children.is_empty()
}
#[must_use]
pub fn wants(&self, path: &str) -> bool {
let mut node = self;
let mut whole = self.whole;
for name in path.split('.') {
if node.excluded {
return false;
}
match node.children.get(name) {
Some(child) => {
node = child;
whole = whole || child.whole;
}
None => return whole,
}
}
!node.excluded && (whole || node.keeps_any())
}
fn keeps_any(&self) -> bool {
!self.excluded && (self.whole || self.children.values().any(Self::keeps_any))
}
#[must_use]
pub fn child(&self, name: &str) -> Self {
match self.children.get(name) {
Some(child) if child.excluded => Self::default(),
Some(child) => Self {
whole: child.whole || self.whole,
..child.clone()
},
None if self.whole => Self::all(),
None => Self::default(),
}
}
#[must_use]
pub fn stored<'a>(
&self,
fields: &[(&str, &'a str)],
always: &[&'a str],
) -> Option<Vec<&'a str>> {
let wanted: Vec<&'a str> = fields
.iter()
.filter(|(field, _)| self.wants(field))
.map(|(_, stored)| *stored)
.collect();
if wanted.len() == fields.len() {
return None;
}
let mut selected: Vec<&'a str> = Vec::with_capacity(always.len() + wanted.len());
for name in always.iter().copied().chain(wanted) {
if !selected.contains(&name) {
selected.push(name);
}
}
Some(selected)
}
pub fn apply(&self, value: &mut Value) {
self.apply_with(value, self.whole);
}
fn apply_with(&self, value: &mut Value, whole: bool) {
match value {
Value::Object(object) => {
object.retain(|name, _| match self.children.get(name) {
Some(child) => !child.excluded && (whole || child.keeps_any()),
None => whole,
});
for (name, child_value) in object.iter_mut() {
if let Some(child) = self.children.get(name) {
child.apply_with(child_value, whole || child.whole);
}
}
}
Value::Array(items) => {
for item in items {
self.apply_with(item, whole);
}
}
_ => {}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DynamoProjection {
expression: String,
names: Vec<(String, String)>,
}
impl DynamoProjection {
#[must_use]
pub fn new<'a>(paths: impl IntoIterator<Item = &'a str>) -> Self {
let mut names: Vec<(String, String)> = Vec::new();
let mut expression = String::new();
for path in paths {
if !expression.is_empty() {
expression.push_str(", ");
}
let placeholders: Vec<String> = path
.split('.')
.map(|segment| {
if let Some((placeholder, _)) = names.iter().find(|(_, name)| name == segment) {
return placeholder.clone();
}
let placeholder = format!("#p{}", names.len());
names.push((placeholder.clone(), segment.to_owned()));
placeholder
})
.collect();
expression.push_str(&placeholders.join("."));
}
Self { expression, names }
}
#[must_use]
pub fn expression(&self) -> &str {
&self.expression
}
#[must_use]
pub fn names(&self) -> &[(String, String)] {
&self.names
}
}
#[must_use]
pub fn sql_columns(columns: &[&str]) -> String {
columns
.iter()
.map(|column| format!("\"{}\"", column.replace('"', "\"\"")))
.collect::<Vec<_>>()
.join(", ")
}