Open wolfiestyle opened 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.
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).
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 (returningOption<T>
). Maybe it would be possible to add asaturating_cast
function to the library?