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 {
12    /// Creates a new byte array filled with zeros.
13    fn create_zeroed() -> Self;
14    /// Returns a mutable slice reference to the underlying byte array.
15    fn as_byteslice_mut(&mut self) -> &mut [u8];
16    /// Returns an immutable slice reference to the underlying byte array.
17    fn as_byteslice(&self) -> &[u8];
18}
19
20/// Implements `ByteableByteArray` for fixed-size arrays `[u8; SIZE]`.
21impl<const SIZE: usize> ByteableByteArray for [u8; SIZE] {
22    fn create_zeroed() -> Self {
23        [0; SIZE]
24    }
25
26    fn as_byteslice_mut(&mut self) -> &mut [u8] {
27        self
28    }
29
30    fn as_byteslice(&self) -> &[u8] {
31        self
32    }
33}
34
35#[cfg(test)]
36mod tests {
37    use super::ByteableByteArray;
38
39    #[test]
40    fn test_create_zeroed() {
41        let arr: [u8; 5] = ByteableByteArray::create_zeroed();
42        assert_eq!(arr, [0, 0, 0, 0, 0]);
43    }
44
45    #[test]
46    fn test_as_byteslice() {
47        let arr: [u8; 4] = [1, 2, 3, 4];
48        let slice = arr.as_byteslice();
49        assert_eq!(slice, &[1, 2, 3, 4]);
50    }
51
52    #[test]
53    fn test_as_byteslice_mut() {
54        let mut arr: [u8; 3] = [1, 2, 3];
55        let slice = arr.as_byteslice_mut();
56        slice[1] = 99;
57        assert_eq!(arr, [1, 99, 3]);
58    }
59}