array_object/convert/
from_string.rs

1use crate::adaptor::*;
2use crate::error::ArrayObjectError;
3use crate::misc::Product;
4use crate::storage::*;
5
6macro_rules! from_text {
7    ($($ty:ty),*) => {
8        $(
9            impl From<$ty> for ArrayObject {
10                fn from(val: $ty) -> Self {
11                    let data: Vec<u8> = val.to_string().into_bytes().to_vec();
12                    Self {
13                        data,
14                        shape: vec![],
15                        datatype: DataType::String,
16                    }
17                }
18            }
19            impl From<Vec<$ty>> for ArrayObject {
20                fn from(val: Vec<$ty>) -> Self {
21                    let shape = vec![val.len() as u64];
22                    let val: Vec<_> = val.into_iter().map(|x| x.to_string()).collect();
23                    let data = val.into_iter().map(|x| x.as_bytes().to_vec()).collect::<Vec<_>>().join(&255u8);
24                    Self {
25                        data,
26                        shape,
27                        datatype: DataType::String,
28                    }
29                }
30            }
31            impl<const N: usize> From<[$ty; N]> for ArrayObject {
32                fn from(val: [$ty; N]) -> Self {
33                    val.to_vec().into()
34                }
35            }
36            impl From<&[$ty]> for ArrayObject {
37                fn from(val: &[$ty]) -> Self {
38                    val.to_vec().into()
39                }
40            }
41            impl TryFrom<VecShape<$ty>> for ArrayObject {
42                type Error = ArrayObjectError;
43                fn try_from(VecShape(val, shape): VecShape<$ty>) -> Result<Self, Self::Error> {
44                    if val.len() != shape.product() as usize {
45                        return Err(ArrayObjectError::NumberOfElementsMismatch(val.len(), shape.product() as usize));
46                    }
47                    if shape.len() > 15 {
48                        return Err(ArrayObjectError::TooLargeDimension(shape.len()));
49                    }
50                    let mut temp: ArrayObject = val.into();
51                    temp.shape = shape;
52                    Ok(temp)
53                }
54            }
55        )*
56    };
57}
58
59from_text!(String, &str);