Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Traits for converting from/into bytes #408

Open
JonathanWoollett-Light opened this issue Aug 22, 2021 · 1 comment
Open

Traits for converting from/into bytes #408

JonathanWoollett-Light opened this issue Aug 22, 2021 · 1 comment

Comments

@JonathanWoollett-Light
Copy link

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>()];
}
@bradleyharden
Copy link

bradleyharden commented Jan 30, 2022

@JonathanWoollett-Light, would #100 be sufficient for your use case? Are you familiar with bytemuck?

Wait, never mind. This is a more general request. For some reason I thought this was specific to Complex<T>.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants