Skip to content

How to convert <T as funty::Numeric>::Bytes to Vec<u8>? #8

Description

@jBernavaPrah

Hi!
Thanks a lot for your effort on the crate!

I have difficulties understanding how to use the funty::Numeric or funty::Fondumental trait in my crate. This is for sure because of my lack of knowledge of Rust, I'm still learning it.

Little background

I'm creating an audio crate, and some functions accept a Numeric value (a Sample) that could be f32, u8, i16 etc. I don't care what type of value is passed, I need only to be sure is a numeric value, so I can convert it to a Vec of little-endian.

Problem

I cannot convert the <T as funty::Numeric>::Bytes, returned by .to_le_bytes() function to Vec<u8>.

Process

So my first intuition was to declare a new trait using this syntax:

pub trait Sample: funty::Numeric {}
impl Sample for u8 {}
impl Sample for u16 {}
impl Sample for u32 {}
impl Sample for u64 {}
impl Sample for u128 {}
impl Sample for usize {}
impl Sample for i8 {}
impl Sample for i16 {}
impl Sample for i32 {}
impl Sample for i64 {}
impl Sample for i128 {}
impl Sample for isize {}
impl Sample for f32 {}
impl Sample for f64 {}

And, if I understand Rust correctly, I can create functions in this way:

pub fn use_sample<T: Sample>(sample: T)  {
   sample.to_le_bytes()
}

// and this function can be called any combination: 
// use_sample(3) or use_sample(0.1233123)
println!("Result: {:?}", use_sample(3 as u8)) // Result: [3]
println!("Result: {:?}", use_sample(0.1233123)) // Result: [109, 205, 177, 23, 101, 145, 191, 63] 

My problem starts now. I'm not able to use the funty::Bytes (<T as funty::Numeric>::Bytes) returned by to_le_bytes function.

What I need is the possibility to do the following:

pub fn use_sample<T: Sample>(sample: T) -> Vec<u8> {
   sample.to_le_bytes().to_vec()
}

But the error triggered is:

sample.to_le_bytes().to_vec()
                                    ^^^^^^ method not found in `<T as Numeric>::Bytes`

So, after this introduction, the real question is:
how can I convert <T as Numeric>::Bytes into Vec<u8>?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions