Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide macro derive for CheckedAdd, CheckedSub, etc. #25

Open
esoterra opened this issue Apr 26, 2019 · 2 comments
Open

Provide macro derive for CheckedAdd, CheckedSub, etc. #25

esoterra opened this issue Apr 26, 2019 · 2 comments

Comments

@esoterra
Copy link

I would like to be able to derive the traits for CheckedAdd, CheckedSub, and the other checked arithmetic for structs whose members implement those traits.

A simple solution would be to generate impl blocks that look something like the following.

struct Position {
   x: u32,
   y: u32
}

impl CheckedSub for Position { 
   fn checked_sub(&self, v: &Self) -> Option<Self> {
      match ( self.x.checked_sub(v.x), self.y.checked_sub(v.y) ) {
         (Some(x), Some(y)) => Some( Position { x, y } ),
         _ => None
      } 
   }
}

I had initially suggested this be added to derive_more, but the owner has indicated that derive_more is meant to provide support for std traits not traits from crates like num-traits.
JelteF/derive_more#77

@cuviper
Copy link
Member

cuviper commented Apr 26, 2019

We have the num-derive crate for stuff like this -- I'll see if I can transfer this issue.

However, while this is simple enough for newtype wrappers of a single field, it's questionable with multiple fields. We don't really know in general that element-wise operations are correct, versus some other approach. For instance, CheckedMul may want to be more like a cross product instead of multiplying each element.

@cuviper cuviper transferred this issue from rust-num/num-traits Apr 26, 2019
@esoterra
Copy link
Author

Thanks for transferring the issue. I think that element-wise behavior is intuitive for add-like and subtract-like operations, but agree that multiply and divide might imply other semantics.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants