libutils_array/
conversions.rs1use super::Array;
7
8use alloc::vec::Vec;
10
11use 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
23const 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
39const 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
51const 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
66const 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
72impl<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
81const 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}