DanielKeep / rust-conv

Conversion traits for Rust
MIT License
48 stars 9 forks source link

SaturatingInto #15

Open That3Percent opened 3 years ago

That3Percent commented 3 years ago

Would you be open to a PR that adds SaturatingInto / SaturatingFrom traits?

Eg:

trait SaturatingInto<T> {
    fn saturating_into(self) -> T;
}

impl SaturatingFrom<usize> for u64 {
    fn saturating_from(self) -> T {
        self.try_into().unwrap_or_else(u64::MAX)
    }
}

This would allow more straightforward conversions so that instead of using:

assert_eq!(u8::value_from(-1i16).unwrap_or_saturate(),  0u8);

One may write:

assert_eq!(-1i16.saturating_into(),  0u8);

I would be happy to contribute this PR.