Skip to main content

toasty_core/stmt/
entry_mut.rs

1use super::{Expr, Value};
2
3/// A mutable reference to either an [`Expr`] or a [`Value`] within a
4/// composite structure.
5///
6/// This is the mutable counterpart to [`Entry`](super::Entry), used for
7/// in-place modification of nested expressions or values.
8///
9/// # Examples
10///
11/// ```ignore
12/// use toasty_core::stmt::{EntryMut, Expr, Value};
13///
14/// let mut expr = Expr::from(Value::from(42_i64));
15/// let mut entry = EntryMut::from(&mut expr);
16/// assert!(matches!(entry, EntryMut::Expr(_)));
17/// ```
18#[derive(Debug)]
19pub enum EntryMut<'a> {
20    /// A mutable reference to an expression.
21    Expr(&'a mut Expr),
22    /// A mutable reference to a value.
23    Value(&'a mut Value),
24}
25
26impl EntryMut<'_> {
27    /// Returns `true` if this entry holds a concrete value.
28    pub fn is_value(&self) -> bool {
29        matches!(self, EntryMut::Value(_) | EntryMut::Expr(Expr::Value(_)))
30    }
31
32    /// Returns `true` if this entry holds a null value.
33    pub fn is_value_null(&self) -> bool {
34        matches!(
35            self,
36            EntryMut::Value(Value::Null) | EntryMut::Expr(Expr::Value(Value::Null))
37        )
38    }
39
40    /// Returns `true` if this entry holds a record, either as an
41    /// `Expr::Record`, an `Expr::Value(Value::Record)`, or a bare
42    /// `Value::Record`.
43    pub fn is_record(&self) -> bool {
44        match self {
45            EntryMut::Expr(Expr::Record(_)) => true,
46            EntryMut::Expr(Expr::Value(value)) => value.is_record(),
47            EntryMut::Value(value) => value.is_record(),
48            EntryMut::Expr(_) => false,
49        }
50    }
51
52    /// Returns `true` if this entry is `Expr::Default`.
53    pub fn is_default(&self) -> bool {
54        matches!(self, EntryMut::Expr(Expr::Default))
55    }
56
57    /// Takes the contained expression or value, replacing it with a default.
58    pub fn take(&mut self) -> Expr {
59        match self {
60            EntryMut::Expr(expr) => expr.take(),
61            EntryMut::Value(value) => value.take().into(),
62        }
63    }
64
65    /// Replaces the contents of this entry with `expr`.
66    ///
67    /// # Panics
68    ///
69    /// Panics if this is a `Value` entry and `expr` is not `Expr::Value`.
70    pub fn insert(&mut self, expr: Expr) {
71        match self {
72            EntryMut::Expr(e) => **e = expr,
73            EntryMut::Value(e) => match expr {
74                Expr::Value(value) => **e = value,
75                _ => panic!("cannot store expression in value entry"),
76            },
77        }
78    }
79}
80
81impl<'a> From<&'a mut Expr> for EntryMut<'a> {
82    fn from(value: &'a mut Expr) -> Self {
83        EntryMut::Expr(value)
84    }
85}
86
87impl<'a> From<&'a mut Value> for EntryMut<'a> {
88    fn from(value: &'a mut Value) -> Self {
89        EntryMut::Value(value)
90    }
91}