How to implement a trait with `to_little_endian`?

Consider the trait whose objects know how to convert themselves to bytes in little endian. I am trying to write one, as I need it for types that can do that.

What I have so far:

pub trait NativeType:
    Sized + Copy + std::fmt::Debug + std::fmt::Display + PartialEq + Default + 'static
{
    fn to_le_bytes(&self) -> &[u8];
}

impl NativeType for u8 {
    fn to_le_bytes(&self) -> &[u8] {
        &u8::to_le_bytes(*self)
    }
}

impl NativeType for u16 {
    fn to_le_bytes(&self) -> &[u8] {
        &u16::to_le_bytes(*self)
    }
}

The problem here is that I am borrow a ref to a temporary object. Is there a way of writing this nicely in stable rust? I could use a Vector, but heap for such a small op could be overkill.

You could try delaying the borrow:

pub trait NativeType:
    Sized + Copy + std::fmt::Debug + std::fmt::Display + PartialEq + Default + 'static
{
    type Bytes: AsRef<[u8]>;
    fn to_le_bytes(&self) -> Self::Bytes;
}

impl NativeType for u8 {
    type Bytes = [u8; 1];
    fn to_le_bytes(&self) -> Self::Bytes {
        u8::to_le_bytes(*self)
    }
}

impl NativeType for u16 {
    type Bytes = [u8; 2];
    fn to_le_bytes(&self) -> Self::Bytes {
        u16::to_le_bytes(*self)
    }
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=609759b6415ec627bf89bc97c32af608

3 Likes

That is a freaking neat solution. Thank you very much!