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    fn from(value: [Type; N]) -> Self {return Array::from_iter(value)}
28}
29
30//> FROM -> FUNCTION
31impl<Type, const N: usize, Generator: FnMut(usize) -> Type> From<Generator> for Array<Type, N> {
32    fn from(mut value: Generator) -> Self {
33        let mut array = Self::new();
34        for index in 0..N {
35            array.push(value(index));
36        };
37        return array;
38    }
39}
40
41//> FROM -> VEC
42impl<Type, const N: usize> TryFrom<Vec<Type>> for Array<Type, N> {
43    type Error = Issue;
44    fn try_from(value: Vec<Type>) -> Result<Self, Self::Error> {return if value.len() > N {Err(Issue {
45        name: "Conversion from `Vec` to `Array` failed",
46        description: Some(format!("Vec of length {} but N = {N}", value.len())),
47        severity: Severity::Error
48    })} else {Ok(Self::from_iter(value.into_iter()))}}
49}
50
51
52//^
53//^ INTO
54//^
55
56//> INTO -> VEC
57impl<Type, const N: usize> Into<Vec<Type>> for Array<Type, N> {
58    fn into(self) -> Vec<Type> {return Vec::from_iter(self.into_iter())}
59}