I want to implement an extension trait to std::io::Read in order to read arbitrary numbers. However I cannot find out, how to get the byte count of an arbitary number using the num_traits crate (or what other crate might provide this information):
use num_traits::FromBytes;
use std::io::{Read, Result};
pub trait ReadNums: Read {
fn read_num_be<N>(&mut self) -> Result<N>
where
N: FromBytes,
{
let mut buffer = [0; N::WHAT_HERE];
self.read_exact(&mut buffer)?;
Ok(N::from_be_bytes(&buffer))
}
}
impl<T> ReadNums for T where T: Read {}
[package]
name = "numtrait_test"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
num-traits = "0.2.17"
I don’t know what tu put at N::WHAT_HERE. I need the respective size of N in bytes here as a const.
Using nightly features is out of the question for my use case.
>Solution :
FromBytes provides the Bytes associated type, but since FromBytes is also meant to work with arbitrary-precision types like BigInt, the Bytes type is not necessarily fixed width.
You can, however, force the association to be an array, with a const generic for the size:
use num_traits::FromBytes;
use std::io::{Read, Result};
pub trait ReadNums: Read {
fn read_num_be<V, const N: usize>(&mut self) -> Result<V>
where
V: FromBytes<Bytes=[u8; N]>,
{
let mut buffer = [0; N];
self.read_exact(&mut buffer)?;
Ok(V::from_be_bytes(&buffer))
}
}
impl<T> ReadNums for T where T: Read {}
This will work with all of the primitive integer types, since their FromBytes implementation take in fixed-sized arrays.