Hi, I checked the crate num_traits, it seems that I can use the trait bounds to create method conditionally, such as method for singed and another method for unsigned, but I didn't find any method like to_[ne/be/le]_bytes. Do you suggest that to create my own trait which implements the to_[ne/be/le]_bytes?
Rust traits work only when a trait is explicitly imported or required in a generic context. So if these methods were only in a trait, you'd need something like use std::num::TheTraitWithToBeBytes in every file that uses it.
There's been a proposal to for inherent traits that behave like both methods and traits, but it's nowhere near being a reality.
Where an implementer could substitute Element with Self.
But the compiler warned you in the first instance of the following:
error: generic parameters may not be used in const operations
2 | fn to_bytes(self) -> [u8; std::mem::size_of::<Self>()];
| ^^^^ cannot perform const operation using `Self`
= note: type parameters may not be used in const expressions
error: aborting due to previous error
Which is a current limitation of Rust's const generics. In other words, there is no way to say an equivalent to this in stable rust today.
To do this, I'd probably just stick to native endian and use something like bytemuck, or return a Vec or an ArrayVec or SmallVec.
bytemuck will allow you to get a reference to a slice from a reference to a number. It performs the following conversion: &T -> &[u8] where T: Pod (Plain old data, which isn't implemented for structures with, for example, pointers, such as String).
SmallVec stores a few elements inline before it spills onto the heap.
ArrayVec stores all of its elements in an array (inline) with a hard cap:
let mut av = ArrayVec::<u8, 2>::new();
// Will panic!