Way to make fn generic

Hi, is there a way to make this fn fully generic? I've tried number of approaches, including implementing my own FromBytes for new_type but alas... failed...

fn from_bytes_hlpr<T: std::convert::From<i32/*here ideally I'd like to provide just some generic integer type*/>>() -> T {
    let mut buf = [0; 4];<< here instead of 4 I'd like to have size of the T

    let fr_bytes = i32::from_be_bytes(buf);<< here instead of i32 I'd like to use T

    fr_bytes.into()
}

Thank you

1 Like
#![feature(generic_const_exprs)]
#![allow(incomplete_features)]

use num_traits::ops::bytes::FromBytes;
use std::mem::size_of;

pub fn from_bytes_hlpr<T: FromBytes<Bytes = [u8; size_of::<T>()]>>() -> T {
    let buf = [0; size_of::<T>()];
    T::from_be_bytes(&buf)
}

https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=901516c47fd0d3a08d200ab4dea8a1b9

1 Like

Thank you

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.