Open
Description
I recently made num-bytes for this purpose, I think its a fairly common usage so I just thought it worth suggesting as something that maybe should be added.
Used like:
let a = [8,0];
let b: i16 = from_generic(a);
assert_eq!(b,8);
fn from_generic<T: num_bytes::FromBytes<N>, const N: usize>(x: [u8;N]) -> T {
T::from_le_bytes(x)
}
and:
let a = 8i16;
let b = into_generic(a);
assert_eq!(b,[8,0]);
fn into_generic<T: num_bytes::IntoBytes<N>, const N: usize>(x: T) -> [u8;N] {
x.into_le_bytes()
}
Since rust-lang/rust#76560 remains incomplete and unstable, this is the reason the current implementation of the trait is a little awkward.
The future simpler implementation could look like:
pub trait FromBytes {
fn from_le_bytes(bytes: [u8; std::mem::size_of::<Self>()]) -> Self;
fn from_be_bytes(bytes: [u8; std::mem::size_of::<Self>()]) -> Self;
}
pub trait IntoBytes {
fn into_le_bytes(self) -> [u8; std::mem::size_of::<Self>()];
fn into_be_bytes(self) -> [u8; std::mem::size_of::<Self>()];
}
Activity
Complex<T>
withbytemuck
rust-num/num-complex#99bradleyharden commentedon Jan 30, 2022
@JonathanWoollett-Light, would #100 be sufficient for your use case? Are you familiar withbytemuck
?Wait, never mind. This is a more general request. For some reason I thought this was specific to
Complex<T>
.