byteable/
byte_array.rs

1//! Byte array trait and implementations.
2//!
3//! This module defines the `ByteableByteArray` trait which provides methods
4//! for creating zero-filled byte arrays and accessing them as byte slices.
5
6/// Trait for working with byte arrays.
7///
8/// This trait provides methods for creating zero-filled byte arrays and
9/// accessing them as mutable or immutable byte slices. It is primarily
10/// used as an associated type for the `Byteable` trait.
11pub trait ByteableByteArray: Copy {
12    const BINARY_SIZE: usize;
13    /// Creates a new byte array filled with zeros.
14    fn create_zeroed() -> Self;
15    /// Returns a mutable slice reference to the underlying byte array.
16    fn as_byteslice_mut(&mut self) -> &mut [u8];
17    /// Returns an immutable slice reference to the underlying byte array.
18    fn as_byteslice(&self) -> &[u8];
19}
20
21/// Implements `ByteableByteArray` for fixed-size arrays `[u8; SIZE]`.
22impl<const SIZE: usize> ByteableByteArray for [u8; SIZE] {
23    const BINARY_SIZE: usize = SIZE;
24
25    fn create_zeroed() -> Self {
26        [0; SIZE]
27    }
28
29    fn as_byteslice_mut(&mut self) -> &mut [u8] {
30        self
31    }
32
33    fn as_byteslice(&self) -> &[u8] {
34        self
35    }
36}
37
38#[cfg(test)]
39mod tests {
40    use super::ByteableByteArray;
41
42    #[test]
43    fn test_create_zeroed() {
44        let arr: [u8; 5] = ByteableByteArray::create_zeroed();
45        assert_eq!(arr, [0, 0, 0, 0, 0]);
46    }
47
48    #[test]
49    fn test_as_byteslice() {
50        let arr: [u8; 4] = [1, 2, 3, 4];
51        let slice = arr.as_byteslice();
52        assert_eq!(slice, &[1, 2, 3, 4]);
53    }
54
55    #[test]
56    fn test_as_byteslice_mut() {
57        let mut arr: [u8; 3] = [1, 2, 3];
58        let slice = arr.as_byteslice_mut();
59        slice[1] = 99;
60        assert_eq!(arr, [1, 99, 3]);
61    }
62}