From 1a71798859786645ef8520c19ede5576b4d15bae Mon Sep 17 00:00:00 2001 From: Jason Volk Date: Wed, 1 Jan 2025 20:20:41 +0000 Subject: [PATCH] add Expected trait to utils; use (already transitive) num-traits. Signed-off-by: Jason Volk --- Cargo.lock | 1 + Cargo.toml | 3 ++ src/core/Cargo.toml | 1 + src/core/utils/math.rs | 3 ++ src/core/utils/math/expected.rs | 52 +++++++++++++++++++++++++++++++++ 5 files changed, 60 insertions(+) create mode 100644 src/core/utils/math/expected.rs diff --git a/Cargo.lock b/Cargo.lock index 7f9ef547..a8a6ae0a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -730,6 +730,7 @@ dependencies = [ "libloading", "log", "nix", + "num-traits", "rand", "regex", "reqwest", diff --git a/Cargo.toml b/Cargo.toml index c66dfcff..805c7d7c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -501,6 +501,9 @@ version = "0.8.1" [workspace.dependencies.libc] version = "0.2" +[workspace.dependencies.num-traits] +version = "0.2" + # # Patches # diff --git a/src/core/Cargo.toml b/src/core/Cargo.toml index 49874c9c..dd8f634a 100644 --- a/src/core/Cargo.toml +++ b/src/core/Cargo.toml @@ -77,6 +77,7 @@ itertools.workspace = true libc.workspace = true libloading.workspace = true log.workspace = true +num-traits.workspace = true rand.workspace = true regex.workspace = true reqwest.workspace = true diff --git a/src/core/utils/math.rs b/src/core/utils/math.rs index c5a785e2..a08cb206 100644 --- a/src/core/utils/math.rs +++ b/src/core/utils/math.rs @@ -1,7 +1,10 @@ +mod expected; + use std::{cmp, convert::TryFrom}; pub use checked_ops::checked_ops; +pub use self::expected::Expected; use crate::{debug::type_name, err, Err, Error, Result}; /// Checked arithmetic expression. Returns a Result diff --git a/src/core/utils/math/expected.rs b/src/core/utils/math/expected.rs new file mode 100644 index 00000000..f0f71854 --- /dev/null +++ b/src/core/utils/math/expected.rs @@ -0,0 +1,52 @@ +use num_traits::ops::checked::{CheckedAdd, CheckedDiv, CheckedMul, CheckedRem, CheckedSub}; + +use crate::expected; + +pub trait Expected { + #[inline] + #[must_use] + fn expected_add(self, rhs: Self) -> Self + where + Self: CheckedAdd + Sized, + { + expected!(self + rhs) + } + + #[inline] + #[must_use] + fn expected_sub(self, rhs: Self) -> Self + where + Self: CheckedSub + Sized, + { + expected!(self - rhs) + } + + #[inline] + #[must_use] + fn expected_mul(self, rhs: Self) -> Self + where + Self: CheckedMul + Sized, + { + expected!(self * rhs) + } + + #[inline] + #[must_use] + fn expected_div(self, rhs: Self) -> Self + where + Self: CheckedDiv + Sized, + { + expected!(self / rhs) + } + + #[inline] + #[must_use] + fn expected_rem(self, rhs: Self) -> Self + where + Self: CheckedRem + Sized, + { + expected!(self % rhs) + } +} + +impl Expected for T {}