mod stuff { /* ... */ }
use stuff::{T, BITS};
fn read_numeric<T>(cursor: &mut dyn Read) -> Result<T, Error> {
let mut b: [T; BITS/8] = [0; BITS/8];
cursor.read_exact(&mut b)?; // read one value
Ok(T::from_be_bytes(b))
}
Or did you mean the actual size of the type, in bits? Why not use the size_of then?
trait BytesT: Sized {
fn bytes() -> usize {
std::mem::size_of::<Self>()
}
}
trait BitsT: Sized {
fn bits() -> usize {
std::mem::size_of::<Self>() * 8
}
}
enum Example {
One(String),
Two(i32, i32)
}
// implement only for types needed
impl BitsT for Example {}
impl BytesT for Example {}
// or make it genetic over T: Sized
impl<T: Sized> BitsT for T {}
impl<T: Sized> BytesT for T {}
fn main() {
let e = Example::bits();
println!("bits: {}", e);
let e = Example::bytes();
println!("bytes: {}", e);
}
Currently, from_be_bytes is an inherent method of numeric types so there's no way to call it in a generic context. You'd need to define a trait for that: