Skip to main content

surrealdb_types/value/
array.rs

1use std::ops::{Deref, DerefMut};
2
3use serde::{Deserialize, Serialize};
4
5use crate::sql::{SqlFormat, ToSql};
6use crate::{SurrealValue, Value};
7
8/// Represents an array of values in SurrealDB
9///
10/// An array is an ordered collection of values that can contain elements of any type.
11/// The underlying storage is a `Vec<Value>`.
12
13#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
14#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
15pub struct Array(pub(crate) Vec<Value>);
16
17impl Array {
18	/// Create a new empty array
19	pub fn new() -> Self {
20		Array(Vec::new())
21	}
22
23	/// Create a new array with capacity
24	pub fn with_capacity(len: usize) -> Self {
25		Self(Vec::with_capacity(len))
26	}
27
28	/// Convert the array into a vector of values.
29	pub fn into_vec(self) -> Vec<Value> {
30		self.0
31	}
32
33	/// Convert into the inner `Vec<Value>`
34	pub fn into_inner(self) -> Vec<Value> {
35		self.0
36	}
37}
38
39impl<T: SurrealValue> From<Vec<T>> for Array {
40	fn from(v: Vec<T>) -> Self {
41		v.into_iter().map(T::into_value).collect()
42	}
43}
44
45impl From<Array> for Vec<Value> {
46	fn from(s: Array) -> Self {
47		s.0
48	}
49}
50
51impl<T: SurrealValue> FromIterator<T> for Array {
52	fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
53		Array(iter.into_iter().map(T::into_value).collect())
54	}
55}
56
57impl Deref for Array {
58	type Target = Vec<Value>;
59	fn deref(&self) -> &Self::Target {
60		&self.0
61	}
62}
63
64impl DerefMut for Array {
65	fn deref_mut(&mut self) -> &mut Self::Target {
66		&mut self.0
67	}
68}
69
70impl IntoIterator for Array {
71	type Item = Value;
72	type IntoIter = std::vec::IntoIter<Self::Item>;
73	fn into_iter(self) -> Self::IntoIter {
74		self.0.into_iter()
75	}
76}
77
78impl<'a> IntoIterator for &'a Array {
79	type Item = &'a Value;
80	type IntoIter = std::slice::Iter<'a, Value>;
81	fn into_iter(self) -> Self::IntoIter {
82		self.0.iter()
83	}
84}
85
86impl<'a> IntoIterator for &'a mut Array {
87	type Item = &'a mut Value;
88	type IntoIter = std::slice::IterMut<'a, Value>;
89	fn into_iter(self) -> Self::IntoIter {
90		self.0.iter_mut()
91	}
92}
93
94impl ToSql for Array {
95	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
96		use crate::sql::fmt_sql_comma_separated;
97
98		f.push('[');
99		if !self.is_empty() {
100			let inner_fmt = fmt.increment();
101			fmt_sql_comma_separated(&self.0, f, inner_fmt);
102		}
103		f.push(']');
104	}
105}