-
Notifications
You must be signed in to change notification settings - Fork 48
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
feat: add checked add/mul/sub #108
base: main
Are you sure you want to change the base?
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
against my will
impl CheckedMul for Felt { | ||
fn checked_mul(&self, v: &Self) -> Option<Self> { | ||
let res = self * v; | ||
if res < *self { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I believe that implementation is wrong,
Felt::TWO * Felt::MAX will probably not work, in the same way 2u32.wrapping_mul(u32::MAX)
doesn't and just returns 1
.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You are right. It should check against max(self, v)
I fixed it and added a test
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
but now there is a bug for mul by zero
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
fixed
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I do not believe this is a good enough check for the CheckedMul.
Here is another case:
println!("{:?}", Felt::from(u128::MAX).checked_mul(&Felt::from(u128::MAX)));
This I believe overflows, but does not return None.
Checking for overflow on the multiply operation after the fact is tricky. I don't know any way to do it if we don't have the divide operation.
What is the current behavior?
Checked operation traits are not available for Felt.
What is the new behavior?
Following traits are implemented
Does this introduce a breaking change?
No
Other information
It would make sense to impl CheckedDiv too. But the trait requires that
Div
be implemented. Something we chose to not do so far. It may be worth reconsidering this.