I have a simple function that encodes an i64 to a byte stream.
fn write_integer(out: &mut Cursor<Vec<u8>>, value: i64, width: u8) -> Result<()> {
let mut value = value;
// while there's stuff outside the 7 LSBs
while value & !0x7F != 0 {
// write the 7 LSBs, with the 8th bit set
out.write_u8((value as u8) & 0x7F | 0x80);
value >>= 7;
}
out.write_u8(value as u8);
Ok(())
}
Instead of reimplementing this to handle all integer sizes, I've attempted to make this generic...
use num_traits::PrimInt;
fn write_integer_g<T: PrimInt>(out: &mut Cursor<Vec<u8>>, value: T, width: u8) -> Result<()> {
let mut value = value;
// while there's stuff outside the 7 LSBs
while value & !0x7F != 0 {
// write the bottom 7 bits, with the 8th bit set
out.write_u8((value as u8) & 0x7F | 0x80);
value >>= 7;
}
out.write_u8(value as u8);
Ok(())
}
however with less than perfect results..
error[E0308]: mismatched types
--> src/encoded_data.rs:31:23
|
27 | fn write_integer_g<T: PrimInt>(out: &mut Cursor<Vec<u8>>, value: T, width: u8) -> Result<()> {
| - this type parameter
...
31 | while value & !0x7F != 0 {
| ^^^^^ expected type parameter `T`, found integer
|
= note: expected type parameter `T`
found type `{integer}`
Clearly my integer literals need converting to values of type T. How can I do this?