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 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 49 additions & 1 deletion crates/starknet-types-core/src/felt/num_traits_impl.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use super::Felt;
use num_bigint::{ToBigInt, ToBigUint};
use num_traits::{FromPrimitive, Inv, One, Pow, ToPrimitive, Zero};
use num_traits::{
CheckedAdd, CheckedMul, CheckedSub, FromPrimitive, Inv, One, Pow, ToPrimitive, Zero,
};

impl ToBigInt for Felt {
/// Converts the value of `self` to a [`BigInt`].
Expand Down Expand Up @@ -121,6 +123,39 @@ impl Pow<u128> for Felt {
}
}

impl CheckedAdd for Felt {
fn checked_add(&self, v: &Self) -> Option<Self> {
let res = self + v;
if res < *self {
None
} else {
Some(res)
}
}
}

impl CheckedMul for Felt {
fn checked_mul(&self, v: &Self) -> Option<Self> {
let res = self * v;
if res < *self {
None
} else {
Some(res)
}
}
}

impl CheckedSub for Felt {
fn checked_sub(&self, v: &Self) -> Option<Self> {
let res = self - v;
if res > *self {
None
} else {
Some(res)
}
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand All @@ -139,4 +174,17 @@ mod tests {
fn default_is_zero() {
assert!(Felt::default().is_zero());
}

#[test]
fn checked_ops() {
assert_eq!(Felt::ONE.checked_add(&Felt::TWO), Some(Felt::THREE));
assert!(Felt::MAX.checked_add(&Felt::ONE).is_none());
assert_eq!(
Felt::TWO.checked_mul(&Felt::THREE),
Some(Felt::from_hex_unchecked("0x6"))
);
assert!(Felt::MAX.checked_mul(&Felt::TWO).is_none());
assert_eq!(Felt::THREE.checked_sub(&Felt::TWO), Some(Felt::ONE));
assert!(Felt::ONE.checked_sub(&Felt::TWO).is_none());
}
}
Loading