Hi *,
I'm pretty new to Rust. After coding these two functions:
pub fn four_byte_le_to_u32(data: &[u8]) -> u32 {
let size: usize = 4;
if data.len() != size {
panic!("Length of input-data is not {}: {}", size, data.len());
}
let mut result: u32 = 0;
for x in 0..size {
result += (data[x] as u32 * (1 << (x * 8)));
}
return result;
}
pub fn eight_byte_le_to_u64(data: &[u8]) -> u64 {
let size: usize = 8;
if data.len() != size {
panic!("Length of input-data is not {}: {}", size, data.len());
}
let mut result: u64 = 0;
for x in 0..size {
result += (data[x] as u64 * (1 << (x * 8)));
}
return result;
}
i came to the believe, that now's the time to learn something about Rust Generics.
After some 4 hours which have been a rather rough ride i came up with this generic version, which compiles and works:
pub fn byte_converter<T>(data: &[u8]) -> T where T: default::Default + From<u8> + ops::AddAssign + ops::Mul<Output = T> + num::NumCast + ops::Shl<T, Output = T> {
let size: usize = mem::size_of::<T>();
if data.len() != size {
panic!("Length of input-data is not {}: {}", size, data.len());
}
let mut result: T = Default::default();
for x in 0..size {
let g = <T as From<u8>>::from(data[x]);
let one: T = NumCast::from(1).unwrap();
let eight: T = NumCast::from(8).unwrap();
let xx: T = NumCast::from(x).unwrap();
result += (g * (one << (xx * eight)));
}
return result;
}
Alas, it looks kinda complicated and ugly. Sorting out the necessary traits was really cumbersome.
Since I'm a real Rust newbie here's the question:
Could this be done cleaner, better, shorter?