I wanted to check my implementation of an atomic integer that panics on overflow, so that I don't get dangerous logic errors where things that should have unique IDs do not. The following is my implementation:
static ID_FACTORY: AtomicU64 = std::sync::atomic::AtomicU64::new(0);
fn next_id() -> ConnId {
// We fetch the value, check it isn't overflow, then swap it with another value, repeating the
// process if it has changed in the mean time.
loop {
let current_val = ID_FACTORY.load(Ordering::Relaxed);
if current_val == u64::max_value() {
panic!("Connection id overflow");
}
if ID_FACTORY.compare_and_swap(current_val, current_val + 1, Ordering::Relaxed)
== current_val
{
// Nobody changed the value since our fetch.
break current_val + 1;
}
}
}
Is this the best way to implement such a type? Also, should something like this be in std
?