rust-num / num-traits

Numeric traits for generic mathematics in Rust
Apache License 2.0
721 stars 134 forks source link

Saturating cast support #181

Open wolfiestyle opened 4 years ago

wolfiestyle commented 4 years ago

In Rust 1.45, the as operator was changed to be a saturating cast for numeric types, but the num_traits library currently only seems to support checked casts (returning Option<T>). Maybe it would be possible to add a saturating_cast function to the library?

cuviper commented 4 years ago

You can use AsPrimitive to get generic support for whatever the compiler does with as, but those saturating casts will have undefined behavior on earlier compilers.

It could make sense to have a new trait that does saturating casts in a broader sense -- not only float to int, but also int to int.

noloerino commented 3 years ago

I've got some code that's generic over unsigned integer types, and I want to truncate a u64 when I'm casting to these potentially smaller types. I can't use AsPrimitive for this because my casts are of the form u64 -> U where U is u8, u16, etc.; FromPrimitive is returning None because it does checked casts, so having saturating casts would be pretty helpful.

If you think this feature is worth adding, I can try and put together some code for it some time (otherwise, I have some workarounds I can use for my own project).