datex_core/values/core_values/
array.rs1use super::super::core_value_trait::CoreValueTrait;
2use crate::values::{
3 core_value::CoreValue,
4 traits::structural_eq::StructuralEq,
5 value_container::{ValueContainer, ValueError},
6};
7use std::{fmt, ops::Index};
8
9#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
10pub struct Array(pub Vec<ValueContainer>);
11impl Array {
12 pub fn len(&self) -> usize {
13 self.0.len()
14 }
15 pub fn is_empty(&self) -> bool {
16 self.0.is_empty()
17 }
18 pub fn get(&self, index: usize) -> Option<&ValueContainer> {
19 self.0.get(index)
20 }
21
22 pub fn push<T: Into<ValueContainer>>(&mut self, value: T) {
23 self.0.push(value.into());
24 }
25}
26impl CoreValueTrait for Array {}
27
28impl StructuralEq for Array {
29 fn structural_eq(&self, other: &Self) -> bool {
30 if self.len() != other.len() {
31 return false;
32 }
33 for (a, b) in self.0.iter().zip(other.0.iter()) {
34 if !a.structural_eq(b) {
35 return false;
36 }
37 }
38 true
39 }
40}
41
42impl fmt::Display for Array {
43 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
44 write!(f, "[")?;
45 for (i, value) in self.0.iter().enumerate() {
46 if i > 0 {
47 write!(f, ", ")?;
48 }
49 write!(f, "{value}")?;
50 }
51 write!(f, "]")
52 }
53}
54
55impl<T> From<Vec<T>> for Array
56where
57 T: Into<ValueContainer>,
58{
59 fn from(vec: Vec<T>) -> Self {
60 Array(vec.into_iter().map(Into::into).collect())
61 }
62}
63
64impl<T> FromIterator<T> for Array
65where
66 T: Into<ValueContainer>,
67{
68 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
69 Array(iter.into_iter().map(Into::into).collect())
70 }
71}
72
73impl Index<usize> for Array {
74 type Output = ValueContainer;
75
76 fn index(&self, index: usize) -> &Self::Output {
77 &self.0[index]
78 }
79}
80
81impl IntoIterator for Array {
82 type Item = ValueContainer;
83 type IntoIter = std::vec::IntoIter<ValueContainer>;
84
85 fn into_iter(self) -> Self::IntoIter {
86 self.0.into_iter()
87 }
88}
89
90impl<'a> IntoIterator for &'a Array {
91 type Item = &'a ValueContainer;
92 type IntoIter = std::slice::Iter<'a, ValueContainer>;
93
94 fn into_iter(self) -> Self::IntoIter {
95 self.0.iter()
96 }
97}
98
99#[macro_export]
100macro_rules! datex_array {
101 ( $( $x:expr ),* ) => {
102 {
103 let arr = vec![$( $crate::values::value_container::ValueContainer::from($x) ),*];
104 Array(arr)
105 }
106 };
107}
108
109impl TryFrom<CoreValue> for Array {
110 type Error = ValueError;
111 fn try_from(value: CoreValue) -> Result<Self, Self::Error> {
112 if let Some(array) = value.cast_to_array() {
113 return Ok(array);
114 }
115 Err(ValueError::TypeConversionError)
116 }
117}