Impl Add for std::num::NonZeroU<*>

When adding two NonZero unsigned integers, the outcome will always be positive.

Currently std::num::NonZeroUsize and other unsigned variations do not implement the Add trait, and I'm not sure why. Is there something here I'm missing?

1 Like

This isn't true in the case of wrapping arithmetic. Arithmatic overflow panics (by default*) in debug mode, but it wraps (by default*) in release mode. That means that MAX + 1 gives 0.

Saturating<NonZeroUnn> could potentially be Add.


* this is a configurable setting separately from optimization and debug assertions IIRC, but in most cases it's just left to these defaults.

5 Likes

As CAD97 correctly pointed out, this is only true in the absence of overflow.

You'll notice that they do have checked_add and saturating_mul and such, just not the operators themselves.

1 Like