From 5ae47072e36dc2cbf72748fc56f8e83f148b7510 Mon Sep 17 00:00:00 2001 From: yihuang Date: Sat, 27 Mar 2021 00:39:50 +0800 Subject: [PATCH] add methods for explicit overflow control --- packages/std/src/math.rs | 47 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/packages/std/src/math.rs b/packages/std/src/math.rs index d7baab40ce..8ec2f83f05 100644 --- a/packages/std/src/math.rs +++ b/packages/std/src/math.rs @@ -209,6 +209,13 @@ impl Uint128 { .ok_or_else(|| StdError::devide_by_zero(self)) } + pub fn checked_div_euclid(self, other: Self) -> StdResult { + self.0 + .checked_div_euclid(other.0) + .map(Self) + .ok_or_else(|| StdError::devide_by_zero(self)) + } + pub fn checked_rem(self, other: Self) -> StdResult { self.0 .checked_rem(other.0) @@ -216,6 +223,26 @@ impl Uint128 { .ok_or_else(|| StdError::devide_by_zero(self)) } + pub fn checked_add(self, other: Self) -> Option { + self.0.checked_add(other.0).map(Self) + } + + pub fn checked_sub(self, other: Self) -> Option { + self.0.checked_sub(other.0).map(Self) + } + + pub fn checked_mul(self, other: Self) -> Option { + self.0.checked_mul(other.0).map(Self) + } + + pub fn checked_div(self, other: Self) -> Option { + self.0.checked_div(other.0).map(Self) + } + + pub fn checked_rem(self, other: Self) -> Option { + self.0.checked_rem(other.0).map(Self) + } + pub fn wrapping_add(self, other: Self) -> Self { Self(self.0.wrapping_add(other.0)) } @@ -228,14 +255,30 @@ impl Uint128 { Self(self.0.wrapping_mul(other.0)) } + pub fn wrapping_neg(self) -> Self { + Self(self.0.wrapping_neg()) + } + pub fn wrapping_div(self, other: Self) -> Self { Self(self.0.wrapping_div(other.0)) } + pub fn wrapping_div_euclid(self, other: Self) -> Self { + Self(self.0.wrapping_div_euclid(other.0)) + } + pub fn wrapping_rem(self, other: Self) -> Self { Self(self.0.wrapping_rem(other.0)) } + pub fn wrapping_rem_euclid(self, other: Self) -> Self { + Self(self.0.wrapping_rem_euclid(other.0)) + } + + pub fn wrapping_pow(self, other: u32) -> Self { + Self(self.0.wrapping_pow(other)) + } + pub fn saturating_add(self, other: Self) -> Self { Self(self.0.saturating_add(other.0)) } @@ -247,6 +290,10 @@ impl Uint128 { pub fn saturating_mul(self, other: Self) -> Self { Self(self.0.saturating_mul(other.0)) } + + pub fn saturating_pow(self, other: u32) -> Self { + Self(self.0.saturating_pow(other)) + } } // `From` is implemented manually instead of