array_object/convert/
from_string.rs1use 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<&$ty> for ArrayObject {
20 fn from(val: &$ty) -> Self {
21 let data: Vec<u8> = val.to_string().into_bytes().to_vec();
22 Self {
23 data,
24 shape: vec![],
25 datatype: DataType::String,
26 }
27 }
28 }
29 impl From<Vec<$ty>> for ArrayObject {
30 fn from(val: Vec<$ty>) -> Self {
31 let shape = vec![val.len() as u64];
32 let val: Vec<_> = val.into_iter().map(|x| x.to_string()).collect();
33 let data = val.into_iter().map(|x| x.as_bytes().to_vec()).collect::<Vec<_>>().join(&255u8);
34 Self {
35 data,
36 shape,
37 datatype: DataType::String,
38 }
39 }
40 }
41 impl From<&Vec<$ty>> for ArrayObject {
42 fn from(val: &Vec<$ty>) -> Self {
43 let shape = vec![val.len() as u64];
44 let val: Vec<_> = val.into_iter().map(|x| x.to_string()).collect();
45 let data = val.into_iter().map(|x| x.as_bytes().to_vec()).collect::<Vec<_>>().join(&255u8);
46 Self {
47 data,
48 shape,
49 datatype: DataType::String,
50 }
51 }
52 }
53 impl<const N: usize> From<[$ty; N]> for ArrayObject {
54 fn from(val: [$ty; N]) -> Self {
55 val.to_vec().into()
56 }
57 }
58 impl From<&[$ty]> for ArrayObject {
59 fn from(val: &[$ty]) -> Self {
60 val.to_vec().into()
61 }
62 }
63 impl TryFrom<VecShape<$ty>> for ArrayObject {
64 type Error = ArrayObjectError;
65 fn try_from(VecShape(val, shape): VecShape<$ty>) -> Result<Self, Self::Error> {
66 if val.len() != shape.product() as usize {
67 return Err(ArrayObjectError::NumberOfElementsMismatch(val.len(), shape.product() as usize));
68 }
69 if shape.len() > 15 {
70 return Err(ArrayObjectError::TooLargeDimension(shape.len()));
71 }
72 let mut temp: ArrayObject = val.into();
73 temp.shape = shape;
74 Ok(temp)
75 }
76 }
77 )*
78 };
79}
80
81from_text!(String, &str);