Skip to main content

FromByteSlice

Trait FromByteSlice 

Source
pub trait FromByteSlice: Sized {
    // Required methods
    fn from_be_slice(bytes: &[u8]) -> Result<Self, ByteSliceError>;
    fn from_le_slice(bytes: &[u8]) -> Result<Self, ByteSliceError>;
}
Expand description

Parses an unsigned integer from a byte slice of arbitrary length.

Input shorter than the target width is zero-extended (leading zeros for big-endian, trailing for little-endian); input wider than the target is rejected with ByteSliceErrorKind::Overflow — never truncated. An empty slice is ByteSliceErrorKind::Empty, not 0.

Required Methods§

Source

fn from_be_slice(bytes: &[u8]) -> Result<Self, ByteSliceError>

Parses from a big-endian byte slice.

use const_num_traits::FromByteSlice;

assert_eq!(<u32 as FromByteSlice>::from_be_slice(&[0x12, 0x34]), Ok(0x1234));
assert_eq!(<u32 as FromByteSlice>::from_be_slice(&[1, 2, 3, 4]), Ok(0x0102_0304));
assert!(<u16 as FromByteSlice>::from_be_slice(&[1, 2, 3]).is_err()); // too wide
assert!(<u32 as FromByteSlice>::from_be_slice(&[]).is_err());        // empty
Source

fn from_le_slice(bytes: &[u8]) -> Result<Self, ByteSliceError>

Parses from a little-endian byte slice.

use const_num_traits::FromByteSlice;

assert_eq!(<u32 as FromByteSlice>::from_le_slice(&[0x34, 0x12]), Ok(0x1234));
assert_eq!(<u32 as FromByteSlice>::from_le_slice(&[1, 2, 3, 4]), Ok(0x0403_0201));

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementations on Foreign Types§

Source§

impl FromByteSlice for u8

Source§

impl FromByteSlice for u16

Source§

impl FromByteSlice for u32

Source§

impl FromByteSlice for u64

Source§

impl FromByteSlice for u128

Source§

impl FromByteSlice for usize

Implementors§