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

feat: add checked add/mul/sub #108

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

tdelabro
Copy link
Collaborator

What is the current behavior?

Checked operation traits are not available for Felt.

What is the new behavior?

Following traits are implemented

  • CheckedAdd
  • CheckedMul
  • CheckedSub

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.

@tdelabro tdelabro added the enhancement New feature or request label Dec 25, 2024
Copy link
Collaborator

@0xLucqs 0xLucqs left a 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 {
Copy link

@cchudant cchudant Jan 28, 2025

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.

Copy link
Collaborator Author

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

Copy link
Collaborator Author

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

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed

Copy link

@cchudant cchudant left a 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.

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

Successfully merging this pull request may close these issues.

3 participants