Skip to main content

surrealdb_expr/expr/
variables.rs

1use std::collections::BTreeMap;
2
3use surrealdb_strand::Strand;
4
5use crate::types::PublicVariables;
6use crate::val::convert_public::convert_public_value_to_internal;
7use crate::val::{Object, Value};
8
9#[derive(Clone, Debug, Default, Eq, PartialEq, Hash)]
10#[repr(transparent)]
11pub struct Variables(pub BTreeMap<Strand, Value>);
12
13impl Variables {
14	/// Create a new empty variables map.
15	#[allow(dead_code)]
16	pub fn new() -> Self {
17		Self(BTreeMap::new())
18	}
19
20	/// Insert a new variable into the map.
21	#[allow(dead_code)]
22	pub fn insert(&mut self, key: impl Into<Strand>, value: Value) {
23		self.0.insert(key.into(), value);
24	}
25}
26
27impl IntoIterator for Variables {
28	type Item = (Strand, Value);
29	type IntoIter = std::collections::btree_map::IntoIter<Strand, Value>;
30
31	#[inline]
32	fn into_iter(self) -> Self::IntoIter {
33		self.0.into_iter()
34	}
35}
36
37impl FromIterator<(Strand, Value)> for Variables {
38	fn from_iter<T: IntoIterator<Item = (Strand, Value)>>(iter: T) -> Self {
39		Self(iter.into_iter().collect())
40	}
41}
42
43impl FromIterator<(String, Value)> for Variables {
44	fn from_iter<T: IntoIterator<Item = (String, Value)>>(iter: T) -> Self {
45		Self(iter.into_iter().map(|(k, v)| (k.into(), v)).collect())
46	}
47}
48
49impl From<Object> for Variables {
50	fn from(obj: Object) -> Self {
51		Self(obj.0.into_iter().collect())
52	}
53}
54
55impl From<BTreeMap<String, Value>> for Variables {
56	fn from(map: BTreeMap<String, Value>) -> Self {
57		Self(map.into_iter().map(|(k, v)| (k.into(), v)).collect())
58	}
59}
60
61impl From<BTreeMap<Strand, Value>> for Variables {
62	fn from(map: BTreeMap<Strand, Value>) -> Self {
63		Self(map)
64	}
65}
66
67impl From<PublicVariables> for Variables {
68	fn from(vars: PublicVariables) -> Self {
69		let mut map = BTreeMap::new();
70		for (key, val) in vars {
71			let internal_val = convert_public_value_to_internal(val);
72			map.insert(key.into(), internal_val);
73		}
74		Self(map)
75	}
76}