1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
pub trait From_<F>: Sized {
fn from_(value: F) -> Self;
}
pub trait Into_<T>
where
T: Sized,
{
fn into_(self) -> T;
}
impl<T, F> Into_<T> for F
where
T: From_<F>,
{
#[inline]
fn into_(self) -> T { T::from_(self) }
}
pub trait TryFrom_<T>: Sized {
type Error;
fn try_from_(value: T) -> Result<Self, Self::Error>;
}
pub trait TryInto_<T>
where
T: Sized,
{
type Error;
fn try_into_(self) -> Result<T, Self::Error>;
}
impl<T, F> TryInto_<T> for F
where
T: TryFrom_<F>,
{
type Error = <T as TryFrom_<F>>::Error;
#[inline]
fn try_into_(self) -> Result<T, Self::Error> { T::try_from_(self) }
}
#[derive(Debug)]
pub struct TryFromSliceError(());
macro_rules! impl_array_try_from {
($ty:ty, $len:expr) => {
impl<'a> TryFrom_<&'a [$ty]> for &'a [$ty; $len] {
type Error = TryFromSliceError;
#[inline]
fn try_from_(slice: &'a [$ty]) -> Result<Self, Self::Error> {
unsafe { transmute_slice::<[$ty; $len], $ty>(slice, $len) }
}
}
impl<'a> TryFrom_<&'a mut [$ty]> for &'a mut [$ty; $len] {
type Error = TryFromSliceError;
#[inline]
fn try_from_(slice: &'a mut [$ty]) -> Result<Self, Self::Error> {
unsafe { transmute_slice_mut::<[$ty; $len], $ty>(slice, $len) }
}
}
};
}
impl_array_try_from!(u8, 12);
impl_array_try_from!(u8, 16);
impl_array_try_from!(u8, 32);
impl_array_try_from!(u8, 64);
#[inline]
unsafe fn transmute_slice<A, T>(slice: &[T], expected_len: usize) -> Result<&A, TryFromSliceError> {
if slice.len() != expected_len {
return Err(TryFromSliceError(()));
}
Ok(core::mem::transmute(slice.as_ptr()))
}
unsafe fn transmute_slice_mut<A, T>(
slice: &mut [T], expected_len: usize,
) -> Result<&mut A, TryFromSliceError> {
if slice.len() != expected_len {
return Err(TryFromSliceError(()));
}
Ok(core::mem::transmute(slice.as_ptr()))
}
macro_rules! impl_array_split {
($ty:ty, $first:expr, $second:expr) => {
impl From_<&[$ty; $first + $second]> for (&[$ty; $first], &[$ty; $second]) {
#[inline]
fn from_(to_split: &[$ty; $first + $second]) -> Self {
let first: *const u8 = &to_split[0];
let split_at: *const u8 = &to_split[$first];
unsafe { (core::mem::transmute(first), core::mem::transmute(split_at)) }
}
}
impl From_<&mut [$ty; $first + $second]> for (&mut [$ty; $first], &mut [$ty; $second]) {
#[inline]
fn from_(to_split: &mut [$ty; $first + $second]) -> Self {
let first: *mut u8 = &mut to_split[0];
let split_at: *mut u8 = &mut to_split[$first];
unsafe { (core::mem::transmute(first), core::mem::transmute(split_at)) }
}
}
};
}
impl_array_split!(u8, 32, 32);