Hi everyone,
I'm working on a Rust crate and need help with allowing users to pass a numeric parameter to a function. This parameter should implement the to_le_bytes()
method. I discovered that the funty
crate provides a Numeric
trait which seems to fit my needs. However, I'm having trouble understanding how to use it correctly.
My goal is to use the Numeric
trait to convert any numeric value to its little-endian byte representation (to_le_bytes()
) and obtain a Vec<u8>
from it.
Here is my current implementation:
/// Sample trait.
pub trait Sample: funty::Numeric + Send + 'static {
fn to_vec(self) -> Vec<u8>;
}
macro_rules! impl_to_le_bytes {
($($t:ty),*) => {
$(
impl Sample for $t {
fn to_vec(self) -> Vec<u8> {
<$t>::to_le_bytes(self).to_vec()
}
}
)*
};
}
impl_to_le_bytes!(u8, i8, u16, i16, u32, i32, f32, u64, i64, f64, u128, i128, usize, isize);
pub struct Source<T: Sample> {
receiver: tokio::sync::mpsc::Receiver<Vec<T>>,
}
impl<T: Sample> Source<T> {
pub fn new() -> (Self, tokio::sync::mpsc::Sender<Vec<T>>) {
let (sender, receiver) = tokio::sync::mpsc::channel::<Vec<T>>(1);
(Self { receiver }, sender)
}
pub async fn next(&mut self) -> Option<Vec<T>> {
self.receiver.recv().await
}
}
async fn test_importing_source<T: Sample>(mut source: Source<T>) {
let x = source.next().await.unwrap();
assert_eq!(x[0].to_vec(), vec![1, 0, 0, 0]);
assert_eq!(x[1].to_vec(), vec![2, 0, 0, 0]);
assert_eq!(x[2].to_vec(), vec![3, 0, 0, 0]);
}
#[cfg(test)]
mod tests {
#[tokio::test]
async fn it_works() {
let (source, sender) = super::Source::new();
sender.send(vec![1, 2, 3]).await.unwrap();
super::test_importing_source(source).await;
}
}
My main issue is that I want to avoid defining my own to_vec()
function for each numeric type. Instead, I'd like to directly use funty::Numeric
's to_le_bytes()
method, which already exists, but the resulting self::Bytes
type doesn't support to_vec()
directly.
How can I use the funty::Numeric
trait to achieve this without writing extra code for each numeric type? Any guidance or examples would be greatly appreciated.
Thank you!