Crate byte_slice_cast [−] [src]
Safely cast bytes slices from/to slices of built-in fundamental numeric types.
The provided traits here allow safe casting between byte slices and slices of fundamental numeric types, like integers and floating point numbers. During casting, checks are performed to ensure that the output slice is safe to use: the input slice must be properly aligned for the output type and contain an integer number of values.
The content of the output slice will be bitwise equivalent to the input slice, as such extra care has to be taken with regard to endianness.
Example
use byte_slice_cast::*; let slice = [1u8, 2u8, 3u8, 4u8, 5u8, 6u8]; let converted_slice = slice.as_slice_of::<u16>().unwrap(); if cfg!(target_endian = "big") { assert_eq!(converted_slice, &[0x0102, 0x0304, 0x0506]); } else { assert_eq!(converted_slice, &[0x0201, 0x0403, 0x0605]); } let converted_back_slice = converted_slice.as_byte_slice().unwrap(); assert_eq!(converted_back_slice, &slice);
Example with mutable slices
use byte_slice_cast::*; let mut slice = [0u8; 4]; { let mut converted_slice = slice.as_mut_slice_of::<u32>().unwrap(); converted_slice[0] = 0x12345678; } if cfg!(target_endian = "big") { assert_eq!(&slice, &[0x12, 0x34, 0x56, 0x78]); } else { assert_eq!(&slice, &[0x78, 0x56, 0x34, 0x12]); }
Enums
Error |
Possible errors during slice conversion. |
Traits
AsSliceOf |
Trait for converting from a byte slice to a slice of another fundamental, built-in numeric
type. This trait is usually more convenient to use than |
FromByteSlice |
Trait for converting from a byte slice to a slice of another fundamental, built-in numeric
type. Usually using the |
ToByteSlice |
Trait for converting from a slice of a fundamental, built-in numeric type to a byte slice. |