spore_vm/val/
struct_val.rs

1use std::collections::HashMap;
2
3use super::{Symbol, UnsafeVal, Val};
4
5/// A container for a struct. A struct is a map from name to value.
6#[derive(Clone, Debug, Default)]
7pub struct StructVal {
8    inner: HashMap<Symbol, UnsafeVal>,
9}
10
11impl StructVal {
12    /// Create a new `StructVal`.
13    pub fn new() -> StructVal {
14        StructVal::with_capacity(0)
15    }
16
17    /// Create a new `StructVal` with capacity for `cap` amount of fields.
18    pub fn with_capacity(cap: usize) -> StructVal {
19        StructVal {
20            inner: HashMap::with_capacity(cap),
21        }
22    }
23
24    /// Get the number of fields.
25    pub fn len(&self) -> usize {
26        self.inner.len()
27    }
28
29    /// Returns `true` if the struct is empty.
30    pub fn is_empty(&self) -> bool {
31        self.inner.is_empty()
32    }
33
34    /// Set the value of `symbol` to `value`.
35    pub fn set(&mut self, symbol: Symbol, value: Val<'static>) {
36        self.inner.insert(symbol, value.inner);
37    }
38
39    /// Get the value of `symbol` or `None` if the value does not exist.
40    pub fn get(&self, symbol: Symbol) -> Option<UnsafeVal> {
41        self.inner.get(&symbol).copied()
42    }
43
44    /// Iterate over all symbol,values within `self`.
45    pub fn iter(&self) -> impl '_ + Iterator<Item = (Symbol, UnsafeVal)> {
46        self.inner.iter().map(|(k, v)| (*k, *v))
47    }
48
49    /// Iterate over all values within `self`.
50    pub fn values(&self) -> impl '_ + Iterator<Item = UnsafeVal> {
51        self.inner.values().copied()
52    }
53}