1 use std::convert::TryInto; 2 use std::mem::size_of; 3 read_ne_u8(input: &mut &[u8]) -> u84pub fn read_ne_u8(input: &mut &[u8]) -> u8 { 5 let (int_bytes, rest) = input.split_at(size_of::<u8>()); 6 *input = rest; 7 u8::from_ne_bytes(int_bytes.try_into().unwrap()) 8 } 9 read_ne_u32(input: &mut &[u8]) -> u3210pub fn read_ne_u32(input: &mut &[u8]) -> u32 { 11 let (int_bytes, rest) = input.split_at(size_of::<u32>()); 12 *input = rest; 13 u32::from_ne_bytes(int_bytes.try_into().unwrap()) 14 } 15 read_ne_usize(input: &mut &[u8]) -> usize16pub fn read_ne_usize(input: &mut &[u8]) -> usize { 17 let (int_bytes, rest) = input.split_at(size_of::<usize>()); 18 *input = rest; 19 usize::from_ne_bytes(int_bytes.try_into().unwrap()) 20 } 21 read_string(input: &mut &[u8], len: usize) -> Option<String>22pub fn read_string(input: &mut &[u8], len: usize) -> Option<String> { 23 let (string_bytes, rest) = input.split_at(len); 24 *input = rest; 25 String::from_utf8(string_bytes.to_vec()).ok() 26 } 27 28 /// Casts a &[T] to a [&u8] without copying. 29 /// Inspired by cast_slice from the bytemuck crate. Drop this copy once external crates are supported. 30 /// 31 /// # Safety 32 /// 33 /// T must not contain any uninitialized bytes such as padding. 34 #[inline] as_byte_slice<T>(t: &[T]) -> &[u8]35pub unsafe fn as_byte_slice<T>(t: &[T]) -> &[u8] { 36 let new_len = core::mem::size_of_val(t) / core::mem::size_of::<u8>(); 37 unsafe { core::slice::from_raw_parts(t.as_ptr() as *const u8, new_len) } 38 } 39