Skip to main content

libutils_array/
conversions.rs

1//^
2//^ HEAD
3//^
4
5//> HEAD -> SUPER
6use super::Array;
7
8//> HEAD -> ALLOC
9use alloc::{
10    vec::Vec,
11    format
12};
13
14//> HEAD -> ISSUE
15use libutils_issue::{
16    Issue,
17    Severity
18};
19
20
21//^
22//^ FROM
23//^
24
25//> FROM -> FIXED TO VARIABLE
26impl<Type, const M: usize, const N: usize> From<[Type; N]> for Array<Type, M> where [(); M - N]: {
27    #[inline]
28    fn from(value: [Type; N]) -> Self {return Array::from_iter(value)}
29}
30
31//> FROM -> FUNCTION
32impl<Type, const N: usize, Generator: FnMut(usize) -> Type> From<Generator> for Array<Type, N> {
33    #[inline]
34    fn from(mut value: Generator) -> Self {
35        let mut array = Self::new();
36        for index in 0..N {
37            array.push(value(index));
38        };
39        return array;
40    }
41}
42
43//> FROM -> VEC
44impl<Type, const N: usize> TryFrom<Vec<Type>> for Array<Type, N> {
45    type Error = Issue;
46    #[inline]
47    fn try_from(value: Vec<Type>) -> Result<Self, Self::Error> {return if value.len() > N {Err(Issue {
48        name: "Conversion from `Vec` to `Array` failed",
49        description: Some(format!("Vec of length {} but N = {N}", value.len())),
50        severity: Severity::Error
51    })} else {Ok(Self::from_iter(value.into_iter()))}}
52}
53
54
55//^
56//^ INTO
57//^
58
59//> INTO -> VEC
60impl<Type, const N: usize> Into<Vec<Type>> for Array<Type, N> {
61    #[inline]
62    fn into(self) -> Vec<Type> {return Vec::from_iter(self.into_iter())}
63}