rust-num / num-traits

Numeric traits for generic mathematics in Rust
Apache License 2.0
694 stars 131 forks source link

Add `ConstZero` and `ConstOne` traits #303

Closed tarcieri closed 7 months ago

tarcieri commented 8 months ago

Adds traits which are alternatives to the more dynamic Zero/One traits which are useful for stack-allocated types where it's possible to define constant values for zero/one.

ZeroConstant ConstZero bounds on Zero as a supertrait, and OneConstant ConstOne on One, allowing them to be used as drop-in replacements.

When a type also impls PartialEq, then ZeroConstant also provides a blanket impl of Zero, and likewise for OneConstant/One, making it simple for stack-allocated integers to impl these traits as an alternative to Zero/One while still remaining fully compatible. (Edit: removed)

The internal impls of Zero/One on the numeric primitive types have been changed to use these traits, which should be a fully backwards-compatible change. (Edit: removed)

Alternative to #276.

cuviper commented 8 months ago

Do you also want to re-export these in the root? I think most people don't use the module hierarchy from here, which is honestly kind of a mess...

When a type also impls PartialEq, then ZeroConstant also provides a blanket impl of Zero, and likewise for OneConstant/One, making it simple for stack-allocated integers to impl these traits as an alternative to Zero/One while still remaining fully compatible.

The problem is that these are not perfectly overlapping, especially with generics, like:

impl<T: Zero> Zero for Complex<T> { ... }
impl<T: ZeroConstant> ZeroConstant for Complex<T> { ... }

The first would include non-const types, but a blanket impl<T: ZeroConstant> Zero for T makes these conflict.

It's similar to Niko's old post about wanting impl<T: Copy> Clone for T: https://smallcultfollowing.com/babysteps//blog/2016/09/24/intersection-impls/

tarcieri commented 8 months ago

I have removed the blanket impls, and in their place impl'd ZeroConstant for Wrapping instead.

Sidebar: would names like ZeroConst and OneConst be better?

cuviper commented 8 months ago

Sidebar: would names like ZeroConst and OneConst be better?

Probably yes, or ConstZero and ConstOne. There's not a lot of precedent that I can find, but some unstable APIs in std do use an abbreviated prefix, like ConstParamTy.