Non-negative integer types

This is my holy grail for a numeric type system. It'd be hard to represent in Rust today, but I'd love to just have Integer<MIN, MAX> with some sort of only-allowed-at-compile-time infinite-precision value for the bounds, where the compiler would just pick a reasonable backing store.

Then all the operators would just work without you ever needing to think about overflow behaviour, and questions about overflow would happen only at the end when you need to pass them to or store them in something with a restricted range, where you'd have the usual complement of into (for widening), try_into, saturating_into, wrapping_into, etc.

That way you'd never need to worry about whether a + b - c should really be a + (b - c) or b + (a - c) and stuff like that. And LLVM already knows to convert (x as u32 + y as u32) as u16 to x as u16 + y as u16 (in release where it's wrapping), so having the larger intermediate results would be zero-cost in the sense that if you didn't actually use the larger intermediate results then it wouldn't be more expensive than the normal way.

(There are a couple things that we be awkward with such things, like trying to do a for (int i = 0; i < n; i = i + 1) loop, but that's ok because we already discourage that, and we could have Integer<MIN, MAX>: Step so that for i in 0..n works for these types without exposing the unsafe dances need to implement that kind of thing.)

5 Likes