pub unsafe trait ByteArray: Copy {
const BYTE_SIZE: usize;
// Required methods
fn zeroed() -> Self;
fn as_byte_slice_mut(&mut self) -> &mut [u8] ⓘ;
fn as_byte_slice(&self) -> &[u8] ⓘ;
}Expand description
A trait for types that can be used as byte array representations.
This trait is used internally by the Byteable trait to abstract over different
byte array types. It provides methods for creating zeroed arrays and converting
between the array type and byte slices.
§Safety
This is an unsafe trait because implementations must guarantee:
- The type is
Copyand has a known, fixed size zeroed()creates a valid instance with all bytes set to zeroas_byte_slice()andas_byte_slice_mut()return slices of exactlyBYTE_SIZEbytes- The memory layout allows safe reinterpretation as a byte slice
§Implementations
This trait is implemented for:
[u8; N]for any constantN- representing a fixed-size byte array[T; N]whereT: ByteArray- representing nested arrays
Most users should not need to implement this trait manually, as the provided implementations cover common use cases.
§Examples
use byteable::ByteArray;
// Create a zeroed byte array
let arr: [u8; 4] = ByteArray::zeroed();
assert_eq!(arr, [0, 0, 0, 0]);
// Get byte size
assert_eq!(<[u8; 4]>::BYTE_SIZE, 4);
// Convert to byte slice
let mut arr = [1u8, 2, 3, 4];
let slice = arr.as_byte_slice();
assert_eq!(slice, &[1, 2, 3, 4]);§Nested arrays
use byteable::ByteArray;
// Nested arrays also work
let nested: [[u8; 2]; 3] = ByteArray::zeroed();
assert_eq!(nested, [[0, 0], [0, 0], [0, 0]]);
// Byte size is computed correctly
assert_eq!(<[[u8; 2]; 3]>::BYTE_SIZE, 6);Required Associated Constants§
Required Methods§
Sourcefn zeroed() -> Self
fn zeroed() -> Self
Creates a new instance with all bytes set to zero.
§Examples
use byteable::ByteArray;
let arr: [u8; 5] = ByteArray::zeroed();
assert_eq!(arr, [0, 0, 0, 0, 0]);Sourcefn as_byte_slice_mut(&mut self) -> &mut [u8] ⓘ
fn as_byte_slice_mut(&mut self) -> &mut [u8] ⓘ
Returns a mutable byte slice view of this array.
The returned slice has exactly BYTE_SIZE bytes.
§Examples
use byteable::ByteArray;
let mut arr: [u8; 3] = [1, 2, 3];
let slice = arr.as_byte_slice_mut();
slice[1] = 99;
assert_eq!(arr, [1, 99, 3]);Sourcefn as_byte_slice(&self) -> &[u8] ⓘ
fn as_byte_slice(&self) -> &[u8] ⓘ
Returns a byte slice view of this array.
The returned slice has exactly BYTE_SIZE bytes.
§Examples
use byteable::ByteArray;
let arr: [u8; 4] = [1, 2, 3, 4];
let slice = arr.as_byte_slice();
assert_eq!(slice, &[1, 2, 3, 4]);Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.