array_bytes/op/
slice.rs

1// self
2use crate::prelude::*;
3
4/// Convert `&[T]` to `[T; N]`.
5///
6/// # Examples
7/// ```
8/// assert_eq!(
9/// 	array_bytes::slice2array::<_, 8>(&[5, 2, 0, 1, 3, 1, 4, 0]),
10/// 	Ok([5, 2, 0, 1, 3, 1, 4, 0])
11/// );
12/// ```
13#[inline(always)]
14pub fn slice2array<T, const N: usize>(slice: &[T]) -> Result<[T; N]>
15where
16	T: Copy,
17{
18	slice.try_into().map_err(|_| Error::MismatchedLength { expect: N })
19}
20
21#[test]
22fn slice2array_should_work() {
23	assert_eq!(slice2array::<_, 8>(&[0; 8]), Ok([0; 8]));
24}
25
26/// Convert `&[T]` to `&[T; N]`.
27///
28/// # Examples
29/// ```
30/// assert_eq!(
31/// 	array_bytes::slice2array_ref::<_, 8>(&[5, 2, 0, 1, 3, 1, 4, 0]),
32/// 	Ok(&[5, 2, 0, 1, 3, 1, 4, 0])
33/// );
34/// ```
35pub fn slice2array_ref<T, const N: usize>(slice: &[T]) -> Result<&[T; N]>
36where
37	T: Copy,
38{
39	slice.try_into().map_err(|_| Error::MismatchedLength { expect: N })
40}
41
42/// Convert `&[T]` to `V` where `V: From<[T; N]>`.
43///
44/// # Examples
45/// ```
46/// #[derive(Debug, PartialEq)]
47/// struct Ljf([u8; 17]);
48/// impl From<[u8; 17]> for Ljf {
49/// 	fn from(array: [u8; 17]) -> Self {
50/// 		Self(array)
51/// 	}
52/// }
53///
54/// assert_eq!(
55/// 	array_bytes::slice_n_into::<u8, Ljf, 17>(b"Love Jane Forever"),
56/// 	Ok(Ljf(*b"Love Jane Forever"))
57/// );
58/// ```
59pub fn slice_n_into<T, V, const N: usize>(slice: &[T]) -> Result<V>
60where
61	T: Copy,
62	V: From<[T; N]>,
63{
64	Ok(slice2array(slice)?.into())
65}
66#[test]
67fn slice_n_into_should_work() {
68	assert_eq!(slice_n_into::<u8, Ljfn, 17>(b"Love Jane Forever"), Ok(Ljfn(*b"Love Jane Forever")));
69}