calcopiritus@lemmy.worldtoProgrammer Humor@programming.dev•How should I increment an int?
6·
1 day agoC:
int increment(int i) {
return (int) (1[(void*) i])
However, if you wanna go blazingly fast you gotta implement O(n) algorithms in rust. Additionally you want safety in case of integer overflows.
use std::error::Error;
#[derive(Debug, Error)]
struct IntegerOverflowError;
struct Incrementor {
lookup_table: HashMap<i32, i33>
}
impl Incrementor {
fn new() -> Self {
let mut lut = HashMap::new();
for i in 0..i32::MAX {
lut.insert(i, i+1)
}
Incrementor { lookup_table: lut }
}
fn increment(&self, i: i32) -> Result<i32, IntegerOverflowError> {
self.lookup_table.get(i)
.map(|i| *i)
.ok_or(IntegerOverflowError)
}
On mobile so I don’t even know if they compile though.
I guess that’s another way to avoid the overflow problem