Skip to main content

collections/
byte_array.rs

1// SPDX-License-Identifier: Apache-2.0
2//
3// Written in 2020-2026 by Dr. Maxim Orlovsky <orlovsky@ubideco.org>
4//
5// Copyright 2020-2026 Laboratories for Ubiquitous and Deterministic Computing,
6// Institute for Distributed and Cognitive Computing (InDCS), Switzerland.
7// All rights reserved.
8//
9// Copyright (C) 2020-2026 Dr Maxim Orlovsky.
10// All rights reserved.
11//
12// Licensed under the Apache License, Version 2.0 (the "License"); you may not
13// use this file except in compliance with the License. You may obtain a copy of
14// the License at <http://www.apache.org/licenses/LICENSE-2.0>
15//
16// Unless required by applicable law or agreed to in writing, software
17// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
18// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
19// License for the specific language governing permissions and limitations under
20// the License.
21
22use core::fmt::{self, Display, Formatter};
23
24/// Error when slice size mismatches array length.
25#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)]
26pub struct FromSliceError {
27    /// Expected slice length.
28    pub expected: usize,
29    /// Actual slice length.
30    pub actual: usize,
31}
32
33impl Display for FromSliceError {
34    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
35        write!(
36            f,
37            "the provided slice length {} doesn't match array size {}",
38            self.actual, self.expected
39        )
40    }
41}
42
43impl core::error::Error for FromSliceError {}
44
45/// Trait for fixed-size byte array types and wrappers around them.
46pub trait ByteArray<const LEN: usize>: Sized {
47    /// Constructs a value from a byte array.
48    fn from_byte_array(val: impl Into<[u8; LEN]>) -> Self;
49
50    /// Constructs a byte array value from a slice.
51    ///
52    /// Errors if the slice length doesn't match the `LEN` constant generic.
53    fn from_slice(slice: impl AsRef<[u8]>) -> Result<Self, FromSliceError>;
54
55    /// Constructs a byte array value from a slice, panicking if the slice
56    /// length doesn't match the `LEN` constant generic.
57    fn from_slice_checked(slice: impl AsRef<[u8]>) -> Self {
58        Self::from_slice(slice).expect("slice length not matching type requirements")
59    }
60
61    /// Returns the fixed-size byte array representation of `self`.
62    fn to_byte_array(&self) -> [u8; LEN];
63}
64
65impl<const LEN: usize> ByteArray<LEN> for [u8; LEN] {
66    #[inline]
67    fn from_byte_array(val: impl Into<[u8; LEN]>) -> Self {
68        val.into()
69    }
70
71    #[inline]
72    fn from_slice(slice: impl AsRef<[u8]>) -> Result<Self, FromSliceError> {
73        let slice = slice.as_ref();
74        Self::try_from(slice).map_err(|_| FromSliceError {
75            expected: LEN,
76            actual: slice.len(),
77        })
78    }
79
80    #[inline]
81    fn to_byte_array(&self) -> [u8; LEN] {
82        *self
83    }
84}
85
86#[cfg(test)]
87mod test {
88    use super::*;
89
90    #[test]
91    fn raw_array_implements_byte_array() {
92        let arr = <[u8; 4]>::from_byte_array([1, 2, 3, 4]);
93        assert_eq!(arr.to_byte_array(), [1, 2, 3, 4]);
94        assert_eq!(<[u8; 4]>::from_slice([1, 2, 3, 4]), Ok(arr));
95        assert_eq!(<[u8; 4]>::from_slice_checked([1, 2, 3, 4]), arr);
96        assert_eq!(
97            <[u8; 4]>::from_slice([1, 2, 3]),
98            Err(FromSliceError {
99                expected: 4,
100                actual: 3,
101            })
102        );
103    }
104
105    #[test]
106    #[should_panic(expected = "slice length not matching type requirements")]
107    fn from_slice_checked_panics_on_mismatch() {
108        let _ = <[u8; 4]>::from_slice_checked([1, 2]);
109    }
110}