tuwunel_core/utils/math/tried.rs
1use num_traits::ops::checked::{CheckedAdd, CheckedDiv, CheckedMul, CheckedRem, CheckedSub};
2
3use crate::{Result, checked};
4
5/// Provides checked arithmetic that reports overflow and invalid operations.
6///
7/// Each method delegates to the corresponding `Checked*` trait. A successful
8/// operation returns its value through the crate's result type.
9pub trait Tried {
10 /// Adds `rhs` with checked arithmetic.
11 ///
12 /// Values that the underlying [`CheckedAdd`] implementation accepts are
13 /// returned unchanged. Overflow is represented by the crate's arithmetic
14 /// error.
15 #[inline]
16 fn try_add(self, rhs: Self) -> Result<Self>
17 where
18 Self: CheckedAdd + Sized,
19 {
20 checked!(self + rhs)
21 }
22
23 /// Subtracts `rhs` with checked arithmetic.
24 ///
25 /// Values that the underlying [`CheckedSub`] implementation accepts are
26 /// returned unchanged. Overflow is represented by the crate's arithmetic
27 /// error.
28 #[inline]
29 fn try_sub(self, rhs: Self) -> Result<Self>
30 where
31 Self: CheckedSub + Sized,
32 {
33 checked!(self - rhs)
34 }
35
36 /// Multiplies by `rhs` with checked arithmetic.
37 ///
38 /// Values that the underlying [`CheckedMul`] implementation accepts are
39 /// returned unchanged. Overflow is represented by the crate's arithmetic
40 /// error.
41 #[inline]
42 fn try_mul(self, rhs: Self) -> Result<Self>
43 where
44 Self: CheckedMul + Sized,
45 {
46 checked!(self * rhs)
47 }
48
49 /// Divides by `rhs` with checked arithmetic.
50 ///
51 /// Values that the underlying [`CheckedDiv`] implementation accepts are
52 /// returned unchanged. Division by zero or overflow becomes the crate's
53 /// arithmetic error.
54 #[inline]
55 fn try_div(self, rhs: Self) -> Result<Self>
56 where
57 Self: CheckedDiv + Sized,
58 {
59 checked!(self / rhs)
60 }
61
62 /// Computes the remainder by `rhs` with checked arithmetic.
63 ///
64 /// Values that the underlying [`CheckedRem`] implementation accepts are
65 /// returned unchanged. A failed checked remainder, including a zero divisor
66 /// or overflow, becomes the crate's arithmetic error.
67 #[inline]
68 fn try_rem(self, rhs: Self) -> Result<Self>
69 where
70 Self: CheckedRem + Sized,
71 {
72 checked!(self % rhs)
73 }
74}
75
76impl<T> Tried for T {}