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::vec::Vec;
10
11//> HEAD -> CORE
12use core::{
13    mem::{
14        MaybeUninit,
15        transmute_neo as transmute
16    },
17    ptr::copy_nonoverlapping,
18    array::from_fn as arrayfn,
19    marker::Destruct
20};
21
22
23//^
24//^ FROM
25//^
26
27//> FROM -> FIXED ARRAY
28const impl<Type, const M: usize, const N: usize> From<[Type; N]> for Array<Type, M> where [(); M - N]: {
29    fn from(value: [Type; N]) -> Self {
30        let mut array = Array {
31            length: N,
32            data: MaybeUninit::uninit()
33        };
34        unsafe {array.data.as_mut_ptr().cast::<[Type; N]>().write(value)};
35        return array;
36    }
37}
38
39//> FROM -> FUNCTION
40const impl<
41    Type: [const] Destruct, 
42    const N: usize, 
43    Generator: [const] FnMut(usize) -> Type + [const] Destruct
44> From<Generator> for Array<Type, N> {
45    fn from(value: Generator) -> Self {return Array {
46        length: N,
47        data: MaybeUninit::new(arrayfn(value))
48    }}
49}
50
51//> FROM -> VEC
52const impl<Type, const N: usize> TryFrom<Vec<Type>> for Array<Type, N> {
53    type Error = &'static str;
54    fn try_from(value: Vec<Type>) -> Result<Self, Self::Error> {
55        let (pointer, length, _) = value.into_parts();
56        if length > N {return Err("vector doesn't fit into array, length > N")}
57        let mut array = Array {
58            length: length,
59            data: MaybeUninit::uninit()
60        };
61        unsafe {copy_nonoverlapping(pointer.as_ptr(), array.as_mut_ptr(), length)};
62        return Ok(array);
63    }
64}
65
66//> FROM -> PARTS
67const impl<Type, const N: usize> From<(usize, MaybeUninit<[Type; N]>)> for Array<Type, N> {
68    fn from(value: (usize, MaybeUninit<[Type; N]>)) -> Self {return unsafe {transmute(value)};}
69}
70
71
72//^
73//^ INTO
74//^
75
76//> INTO -> VEC
77impl<Type, const N: usize> Into<Vec<Type>> for Array<Type, N> {
78    fn into(self) -> Vec<Type> {return Vec::from_iter(self.into_iter())}
79}
80
81//> INTO -> PARTS
82const impl<Type, const N: usize> Into<(usize, MaybeUninit<[Type; N]>)> for Array<Type, N> {
83    fn into(self) -> (usize, MaybeUninit<[Type; N]>) {return unsafe {transmute(self)}}
84}