tuwunel_core/utils/math/expected.rs
1use num_traits::ops::checked::{CheckedAdd, CheckedDiv, CheckedMul, CheckedRem, CheckedSub};
2
3use crate::expected;
4
5/// Provides checked arithmetic for operations expected to succeed.
6///
7/// Each method delegates to the corresponding `Checked*` trait. A failed check
8/// is treated as a violated program invariant and panics.
9pub trait Expected {
10 /// Adds `rhs` with an expectation that the operation is valid.
11 ///
12 /// A successful checked addition returns its value unchanged.
13 ///
14 /// # Panics
15 ///
16 /// Panics when the underlying [`CheckedAdd`] operation returns `None`.
17 #[inline]
18 #[must_use]
19 fn expected_add(self, rhs: Self) -> Self
20 where
21 Self: CheckedAdd + Sized,
22 {
23 expected!(self + rhs)
24 }
25
26 /// Subtracts `rhs` with an expectation that the operation is valid.
27 ///
28 /// A successful checked subtraction returns its value unchanged.
29 ///
30 /// # Panics
31 ///
32 /// Panics when the underlying [`CheckedSub`] operation returns `None`.
33 #[inline]
34 #[must_use]
35 fn expected_sub(self, rhs: Self) -> Self
36 where
37 Self: CheckedSub + Sized,
38 {
39 expected!(self - rhs)
40 }
41
42 /// Multiplies by `rhs` with an expectation that the operation is valid.
43 ///
44 /// A successful checked multiplication returns its value unchanged.
45 ///
46 /// # Panics
47 ///
48 /// Panics when the underlying [`CheckedMul`] operation returns `None`.
49 #[inline]
50 #[must_use]
51 fn expected_mul(self, rhs: Self) -> Self
52 where
53 Self: CheckedMul + Sized,
54 {
55 expected!(self * rhs)
56 }
57
58 /// Divides by `rhs` with an expectation that the operation is valid.
59 ///
60 /// A successful checked division returns its value unchanged.
61 ///
62 /// # Panics
63 ///
64 /// Panics when the underlying [`CheckedDiv`] operation returns `None`.
65 #[inline]
66 #[must_use]
67 fn expected_div(self, rhs: Self) -> Self
68 where
69 Self: CheckedDiv + Sized,
70 {
71 expected!(self / rhs)
72 }
73
74 /// Computes the remainder with an expectation that the operation is valid.
75 ///
76 /// A successful checked remainder returns its value unchanged.
77 ///
78 /// # Panics
79 ///
80 /// Panics when the underlying [`CheckedRem`] operation returns `None`.
81 #[inline]
82 #[must_use]
83 fn expected_rem(self, rhs: Self) -> Self
84 where
85 Self: CheckedRem + Sized,
86 {
87 expected!(self % rhs)
88 }
89}
90
91impl<T> Expected for T {}