Currently there are three ways to convert between integer types:
- lossless (
from(); requires range inclusion)
- faulty (
- unconstrained, error-prone (
There is no satisfying way to convert between signed and unsigned integers of the same size.
as is error-prone because it doesn't distinguish between injective and information-loosing cases: if the type of
x changes from
u64, you'll get no warning from the compiler that
x as i32 should be probably updated to
x as i64.
I propose to add
.to_signed() method to
usize; and to add
.to_unsigned() method to
I think it's valuable to have it in the standard library to make clippy lints possible ("you wrote
x as i32 where
x: u32, did you mean
x.to_signed()?"). Besides, conversions between signed and unsigned representations of the same size is much more common than conversions between big-endian and little-endian, and that's in the standard library.
Variable design dimensions (bikeshedding points)
Should it be regular methods or traits
ToUnsigned? I don't see a use case for parametric polymorphism here, so probably regular methods.
Should there be
u32::from_signed(x: i32)? Maybe for symmetry.
Should unsigned types support tautological
to_unsigned()? I don't see the point, probably not.