Is there a better way to implement a common conversion function over primitive number types? I've been struggling to create a more generic version of a trait, that converts a LE byte stream to specific type, and then returns an option float64. In this routine, if a number of specific type is max positive or max (positive-1), it is invalid. It seems this should be possible with a function that takes generics and uses a where clause, but I haven't been able to find a working solution.
struct U16([u8;2]);
struct U32([u8;4]);
struct I16([u8;2]);
struct I32([u8;4]);
trait CanNumber {
fn to_number(&self) -> Option<f64>;
}
impl CanNumber for U16 {
fn to_number(&self) -> Option<f64> {
type nt = u16;
let num: nt = nt::from_le_bytes(self.0);
if (num == nt::MAX) | (num == (nt::MAX-1)) {
None
}
else {
Some(num as f64)
}
}
}
impl CanNumber for I16 {
fn to_number(&self) -> Option<f64> {
type nt = i16;
let num: nt = nt::from_le_bytes(self.0);
if (num == nt::MAX) | (num == (nt::MAX-1)) {
None
}
else {
Some(num as f64)
}
}
}
fn main() {
let test0: f64 = U16([1,2]).to_number().unwrap();
let test1: f64 = I16([1,2]).to_number().unwrap();
println!("test!");
}