rust-num / num-traits

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

why checked mul requires impl uncheked mul? #212

Open dzmitry-lahoda opened 3 years ago

dzmitry-lahoda commented 3 years ago

i want to provide type safe fixed point 256 bit type and force usage only of type safe ops, but cannot impl it using num trait as it requries unchecked variants either be part of api

cuviper commented 3 years ago

That goes way back to rust-num/num#30, which itself is preceded by rust-lang/rust#8408. Unfortunately I don't see any discussion there -- I'm not sure if it was discussed anywhere else.

https://github.com/rust-lang/rust/pull/8408/files#diff-e6466fe2114f90b29c87d7599d14c829eb2a7429a87ca5c25a15283e7ba0b8c9R793-R795

It's simply never been reconsidered, as we haven't made breaking changes in num nor in num-traits after this was split out.

I suppose your use case makes sense, but I wonder if that type would actually be used much in a generic context that may also take other checked types. If not, it would be easier to define an inherent fn checked_mul on your type so you don't need to import a trait to call it, or even implement Mul with type Output = Option<Self> so you can use the operator.

dzmitry-lahoda commented 3 years ago

define an inherent fn checked_mul on your type so you don't need to import a trait to call it

currently we have that

even implement Mul with type Output = Option so you can use the operator.

very interesting options, thanks for suggestion

we have 256 bit decimal(fixed points) and u64/u128 numbers. we want to mix and match them as fluent as possible, but retain all calculations beign checked and in 256 bit.

mvanbem commented 1 year ago

I found this issue while I was considering filing one of my own about the checked/wrapping/saturating ops traits and their supertrait constraints.

My use case is a mix of embedded and kernel work where panicking operations are expensive in binary size and tend to represent latent denial-of-service bugs. I find it inconvenient that the standard primitive integer types offer panicking operators and I'm considering ways to prohibit their use or increase friction.

I have some types that do not impl Add or any of the core::ops traits that might panic, but they do provide checked_add inherent methods. The CheckedAdd trait and several others in num would be a perfect fit for these types if they had no supertrait constraint, but for now I will have to declare my own incompatible trait.

I recognize that revising these traits would be a breaking change. But I would be happy to see it happen.