Skip to main content

stack_array/
conversions.rs

1//^
2//^ HEAD
3//^
4
5//> HEAD -> SUPER
6use super::Array;
7
8//> HEAD -> ALLOC
9use alloc::vec::Vec;
10use constrangeiter::ConstIntoIterator;
11
12//> HEAD -> CORE
13use core::{
14    mem::{
15        MaybeUninit,
16        transmute_neo as transmute
17    },
18    array::from_fn as arrayfn,
19    marker::Destruct
20};
21
22
23//^
24//^ FROM
25//^
26
27//> FROM -> FIXED ARRAY
28const impl<
29    Type: [const] Destruct, 
30    const M: usize, 
31    const N: usize
32> From<[Type; N]> for Array<Type, M> where [(); M - N]: {
33    fn from(value: [Type; N]) -> Self {
34        let mut data = MaybeUninit::<[Type; M]>::uninit().transpose();
35        let mut index = 0;
36        let _ = value.map(const |element| {
37            data[index].write(element); 
38            index += 1;
39        });
40        return Array {
41            length: N,
42            data: data
43        };
44    }
45}
46
47//> FROM -> FUNCTION
48const impl<
49    Type: [const] Destruct, 
50    const N: usize, 
51    Generator: [const] FnMut(usize) -> Type + [const] Destruct
52> From<Generator> for Array<Type, N> {
53    fn from(mut value: Generator) -> Self {return Array {
54        length: N,
55        data: arrayfn(const |index| MaybeUninit::new(value(index)))
56    }}
57}
58
59//> FROM -> VEC
60const impl<Type, const N: usize> TryFrom<Vec<Type>> for Array<Type, N> {
61    type Error = &'static str;
62    fn try_from(value: Vec<Type>) -> Result<Self, Self::Error> {
63
64        let (pointer, length, _) = value.into_parts();
65        if length > N {return Err("vector doesn't fit into array, length > N")}
66        let mut array = Array {
67            length: length,
68            data: MaybeUninit::uninit().transpose()
69        };
70        for index in (0..length).const_into_iter() {
71            array.data[index].write(unsafe {pointer.add(index).read()});
72        }
73        return Ok(array);
74    }
75}
76
77//> FROM -> PARTS
78const impl<Type, const N: usize> From<(usize, [MaybeUninit<Type>; N])> for Array<Type, N> {
79    fn from(value: (usize, [MaybeUninit<Type>; N])) -> Self {return unsafe {transmute(value)}}
80}
81
82
83//^
84//^ INTO
85//^
86
87//> INTO -> VEC
88impl<Type, const N: usize> Into<Vec<Type>> for Array<Type, N> {
89    fn into(self) -> Vec<Type> {return Vec::from_iter(self.into_iter())}
90}
91
92//> INTO -> PARTS
93const impl<Type, const N: usize> Into<(usize, [MaybeUninit<Type>; N])> for Array<Type, N> {
94    fn into(self) -> (usize, [MaybeUninit<Type>; N]) {return unsafe {transmute(self)}}
95}