Skip to content

Instantly share code, notes, and snippets.

@johnlees
Created January 2, 2022 18:55
Show Gist options
  • Save johnlees/49e6a7bd85b3545bba20e8670180f24a to your computer and use it in GitHub Desktop.
Save johnlees/49e6a7bd85b3545bba20e8670180f24a to your computer and use it in GitHub Desktop.
Rust generic return
// bitvec = "0.22.3"
use bitvec::prelude::*;
// These are two functions I'd like to template the input and output types of,
// function bodies are identical
fn bslice_to_int(bv: &BitSlice::<Lsb0, u8>) -> u32 {
let mut int = 0;
for bit in bv {
int = int << 1;
if bit == true {
int += 1;
}
}
return int;
}
fn bv_to_int(bv: &BitVec::<Lsb0, u8>) -> u64 {
let mut int = 0;
for bit in bv {
int = int << 1;
if bit == true {
int += 1;
}
}
return int;
}
// Trying to template the input type
/*
fn bv_to_int_generic_in<T>(bv: &T) -> u64 {
let mut int = 0;
for bit in bv {
int = int << 1;
if bit == true {
int += 1;
}
}
return int;
}
error[E0277]: `&T` is not an iterator
--> src/main.rs:29:14
|
29 | for bit in bv {
| ^^ `&T` is not an iterator
|
= help: the trait `Iterator` is not implemented for `&T`
= note: required because of the requirements on the impl of `IntoIterator` for `&T`
note: required by `into_iter`
--> /Users/jlees/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust/library/core/src/iter/traits/collect.rs:234:5
|
234 | fn into_iter(self) -> Self::IntoIter;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
*/
// Trying to template the output type
/*
fn bv_to_int_generic_out<T>(bv: &BitVec::<Lsb0, u8>) -> T {
let mut int: T = 0;
for bit in bv {
int = int << 1;
if bit == true {
int += 1;
}
}
return int;
}
error[E0308]: mismatched types
--> src/main.rs:55:20
|
54 | fn bv_to_int_generic_out<T>(bv: &BitVec::<Lsb0, u8>) -> T {
| - this type parameter
55 | let mut int: T = 0;
| - ^ expected type parameter `T`, found integer
| |
| expected due to this
|
= note: expected type parameter `T`
found type `{integer}`
error[E0369]: no implementation for `T << {integer}`
--> src/main.rs:57:15
|
57 | int = int << 1;
| --- ^^ - {integer}
| |
| T
|
help: consider restricting type parameter `T`
|
54 | fn bv_to_int_generic_out<T: std::ops::Shl<Output = {integer}>>(bv: &BitVec::<Lsb0, u8>) -> T {
| +++++++++++++++++++++++++++++++++++
error[E0368]: binary assignment operation `+=` cannot be applied to type `T`
--> src/main.rs:59:7
|
59 | int += 1;
| ---^^^^^
| |
| cannot use `+=` on type `T`
|
help: consider restricting type parameter `T`
|
54 | fn bv_to_int_generic_out<T: std::ops::AddAssign>(bv: &BitVec::<Lsb0, u8>) -> T {
| +++++++++++++++++++++
*/
fn main() {
let bits = bitvec![Lsb0, u8; 1,0,1,0];
let val1 = bslice_to_int(&bits[0..2]);
let val2 = bv_to_int(&bits);
//let val2 = bv_to_int_generic_in::<BitVec::<Lsb0, u8>>(&bits);
//let val2: u32 = bv_to_int_generic_out::<u32>(&bits);
println!("{} {}", val1, val2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment