Skip to main content

radiate_expr/
set.rs

1use crate::Expr;
2use radiate_utils::SmallStr;
3#[cfg(feature = "serde")]
4use serde::{Deserialize, Serialize};
5use std::collections::HashMap;
6
7#[derive(Clone, Debug, PartialEq, Default)]
8#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
9pub struct ExprSet {
10    exprs: HashMap<SmallStr, Expr>,
11}
12
13impl ExprSet {
14    pub fn new(exprs: Vec<Expr>) -> Self {
15        Self {
16            exprs: exprs
17                .into_iter()
18                .map(|e| (e.name().into(), e.compile()))
19                .collect(),
20        }
21    }
22
23    pub fn get(&self, name: impl AsRef<str>) -> Option<&Expr> {
24        let name = name.as_ref();
25        self.exprs.get(name)
26    }
27
28    pub fn len(&self) -> usize {
29        self.exprs.len()
30    }
31
32    pub fn is_empty(&self) -> bool {
33        self.exprs.is_empty()
34    }
35
36    pub fn push(&mut self, expr: impl Into<Expr>) {
37        let expr = expr.into();
38        self.exprs.insert(expr.name().into(), expr);
39    }
40
41    pub fn insert(&mut self, name: impl Into<SmallStr>, expr: impl Into<Expr>) {
42        let expr = expr.into();
43        self.exprs.insert(name.into(), expr);
44    }
45
46    pub fn iter(&self) -> impl Iterator<Item = (&SmallStr, &Expr)> {
47        self.exprs.iter()
48    }
49
50    pub fn iter_mut(&mut self) -> impl Iterator<Item = (&SmallStr, &mut Expr)> {
51        self.exprs.iter_mut()
52    }
53}
54
55impl From<Expr> for ExprSet {
56    fn from(expr: Expr) -> Self {
57        Self::new(vec![expr])
58    }
59}
60
61impl<const N: usize> From<[Expr; N]> for ExprSet {
62    fn from(exprs: [Expr; N]) -> Self {
63        Self::new(exprs.into_iter().collect())
64    }
65}
66
67impl From<Vec<Expr>> for ExprSet {
68    fn from(exprs: Vec<Expr>) -> Self {
69        Self::new(exprs)
70    }
71}
72
73impl From<Vec<(SmallStr, Expr)>> for ExprSet {
74    fn from(exprs: Vec<(SmallStr, Expr)>) -> Self {
75        let named_exprs = exprs
76            .into_iter()
77            .map(|(name, expr)| expr.alias(name))
78            .collect();
79        Self::new(named_exprs)
80    }
81}