array_object/convert/
from_real.rs

1use crate::adaptor::*;
2use crate::error::ArrayObjectError;
3use crate::misc::Product;
4use crate::storage::*;
5
6macro_rules! from_float {
7    ($($ty:ty),*) => {
8        $(
9            impl From<$ty> for ArrayObject {
10                fn from(val: $ty) -> Self {
11                    let data = val.to_le_bytes().to_vec();
12                    Self {
13                        data,
14                        shape: vec![],
15                        datatype: DataType::Real,
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 mut data = Vec::<u8>::with_capacity(size_of::<$ty>() * val.len());
23                    for v in val {
24                        data.append(&mut v.to_le_bytes().to_vec());
25                    }
26                    Self {
27                        data,
28                        shape,
29                        datatype: DataType::Real,
30                    }
31                }
32            }
33            impl<const N: usize> From<[$ty; N]> for ArrayObject {
34                fn from(val: [$ty; N]) -> Self {
35                    val.to_vec().into()
36                }
37            }
38            impl From<&[$ty]> for ArrayObject {
39                fn from(val: &[$ty]) -> Self {
40                    val.to_vec().into()
41                }
42            }
43            impl TryFrom<VecShape<$ty>> for ArrayObject {
44                type Error = ArrayObjectError;
45                fn try_from(VecShape(val, shape): VecShape<$ty>) -> Result<Self, Self::Error> {
46                    if val.len() != shape.product() as usize {
47                        return Err(ArrayObjectError::NumberOfElementsMismatch(val.len(), shape.product() as usize));
48                    }
49                    if shape.len() > 15 {
50                        return Err(ArrayObjectError::TooLargeDimension(shape.len()));
51                    }
52                    let mut temp: ArrayObject = val.into();
53                    temp.shape = shape;
54                    Ok(temp)
55                }
56            }
57        )*
58    };
59}
60
61from_float!(f32, f64);