This week, I twice needed to represent a difference between two unsigned numbers. Granted, one was for advent of code, but the other was typical systemsy code for list manipulation in a guts of a complicated data structure (source).
Unless I am missing something, there's no easy way to do this in Rust? The obvious solution is to say that a diff between two u32
is an i32
, and then use as
casts to do the computation. But this ugly, ignores overflows, and doesn't really work for u128
or usize
. Originally, I wanted to suggest adding
impl u32 {
fn [|overflowing|wrapping|checked]_add_signed(self, other: i32) -> u32
}
family of methods to primitives, but now I have some doubts.
The problem is that the magnitude of the difference between two u32
can be u32::max_value()
, so using i32
here is wrong. The right type for the difference would be (bool, u32)
. This isn't nice to work with (as you'd need to hard-code operations on differences yourself), and doesn't look like a pit of success.
At this point, I am feeling lost: this is clearly a problem and a friction point, but I have no ideas what the solution would look like. Any suggestions?