add checked math wrapper
Signed-off-by: Jason Volk <jason@zemos.net>
This commit is contained in:
parent
98d8e5c63c
commit
80832cb0bb
2 changed files with 49 additions and 1 deletions
|
@ -1,10 +1,11 @@
|
|||
mod expected;
|
||||
mod tried;
|
||||
|
||||
use std::{cmp, convert::TryFrom};
|
||||
|
||||
pub use checked_ops::checked_ops;
|
||||
|
||||
pub use self::expected::Expected;
|
||||
pub use self::{expected::Expected, tried::Tried};
|
||||
use crate::{debug::type_name, err, Err, Error, Result};
|
||||
|
||||
/// Checked arithmetic expression. Returns a Result<R, Error::Arithmetic>
|
||||
|
|
47
src/core/utils/math/tried.rs
Normal file
47
src/core/utils/math/tried.rs
Normal file
|
@ -0,0 +1,47 @@
|
|||
use num_traits::ops::checked::{CheckedAdd, CheckedDiv, CheckedMul, CheckedRem, CheckedSub};
|
||||
|
||||
use crate::{checked, Result};
|
||||
|
||||
pub trait Tried {
|
||||
#[inline]
|
||||
fn try_add(self, rhs: Self) -> Result<Self>
|
||||
where
|
||||
Self: CheckedAdd + Sized,
|
||||
{
|
||||
checked!(self + rhs)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn try_sub(self, rhs: Self) -> Result<Self>
|
||||
where
|
||||
Self: CheckedSub + Sized,
|
||||
{
|
||||
checked!(self - rhs)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn try_mul(self, rhs: Self) -> Result<Self>
|
||||
where
|
||||
Self: CheckedMul + Sized,
|
||||
{
|
||||
checked!(self * rhs)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn try_div(self, rhs: Self) -> Result<Self>
|
||||
where
|
||||
Self: CheckedDiv + Sized,
|
||||
{
|
||||
checked!(self / rhs)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn try_rem(self, rhs: Self) -> Result<Self>
|
||||
where
|
||||
Self: CheckedRem + Sized,
|
||||
{
|
||||
checked!(self % rhs)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Tried for T {}
|
Loading…
Add table
Add a link
Reference in a new issue