Implementing core::num::Wrapping for a custom type

Hey, I'm stuck on how to add Wrapping<> support correctly to a custom math struct.

Seems like for all native int types, the Wrapping implementations reside in library/core/src/num/, and I can't work out if it is even possible to add similar semantics to a custom struct outside of there.

This playground is as far as i've gotten. I can successfully, but uselessly, implement an Add operand that looks like T + Wrapping<T> = Wrapping<T>, but for builtin integers the operand is Wrapping<T> + Wrapping<T> = Wrapping<T>

I.e. i can do this:

impl core::ops::Add<Wrapping<Foo>> for Foo

But i obviously can't do this:

impl core::ops::Add<Wrapping<Foo>> for Wrapping<Foo>

Not sure if there's any trait bounds or something that i can use to make things click ?

It's actually not so relevant for Add / Sub, because those already have usable wrapping_add / wrapping_sub, but for AddAssign an equivalent wrapping_add_assign doesn't exist, so the only way for client code to do wrapping add-assign is to go through Wrapping class.

Unfortunately, I don't think it's possible to re-use the Wrapping struct from the standard library properly for something like this. Of you want to support overloading operators, you can either define your own wrapper like Wrapping or just introduce two distinct types for wrapping and non-wrapping arithmetic.

Looks like there's no way indeed. The correct thing seems to be implementing WrappingAddAssign and WrappingNumAssignOps similar to what's already in num_traits for regular assign ops ( NumAssignOps ).

With a member function that is explicitly fn wrapping_add_assign(&mut self, other: Self)

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.