Skip to content

Traits for converting from/into bytes #408

Open
@JonathanWoollett-Light

Description

@JonathanWoollett-Light

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

bradleyharden

bradleyharden commented on Jan 30, 2022

@bradleyharden

@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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @bradleyharden@JonathanWoollett-Light

        Issue actions

          Traits for converting from/into bytes · Issue #408 · rust-num/num