financial_ops/core/checked/impl_checked_arithmetic_macro.rs
1/// Implements checked arithmetic operations for the specified types.
2///
3/// This macro generates implementations of the `CheckedAdd`, `CheckedSub`,
4/// `CheckedMul`, `CheckedDiv`, and `CheckedRem` traits for the given types.
5/// These traits provide methods for performing arithmetic operations that
6/// return an `Option` containing the result, instead of panicking on overflow
7/// or division by zero.
8///
9/// # Examples
10///
11// `impl_checked_arithmetic!(u8 u16 u32 u64 i8 i16 i32 i64);`
12///
13/// In this example, the `impl_checked_arithmetic` macro is used to generate
14/// implementations of the `CheckedAdd`, `CheckedSub`, `CheckedMul`,
15/// `CheckedDiv`, and `CheckedRem` traits for the types `u8`, `u16`, `u32`,
16/// `u64`, `i8`, `i16`, `i32`, and `i64`.
17///
18/// The generated implementations provide methods like `checked_add`, `checked_sub`,
19/// `checked_mul`, `checked_div`, and `checked_rem` that can be used to perform
20/// arithmetic operations that return an `Option` containing the result.
21///
22/// # Safety
23///
24/// The generated implementations rely on the underlying arithmetic operations
25/// provided by the types. It is important to ensure that the types being used
26/// implement the necessary arithmetic operations correctly and handle overflow
27/// and division by zero appropriately.
28///
29/// # Panics
30///
31/// The generated implementations do not panic on overflow or division by zero.
32/// Instead, they return `None` to indicate that the operation could not be
33/// performed without overflowing or dividing by zero.
34#[macro_export]
35macro_rules! impl_checked_arithmetic {
36 ($($t:ty)*) => ($(
37 impl crate::core::CheckedAdd for $t {
38 fn checked_add(&self, v: &Self) -> Option<Self> {
39 <$t>::checked_add(*self, *v)
40 }
41 }
42 impl crate::core::CheckedSub for $t {
43 fn checked_sub(&self, v: &Self) -> Option<Self> {
44 <$t>::checked_sub(*self, *v)
45 }
46 }
47 impl crate::core::CheckedMul for $t {
48 fn checked_mul(&self, v: &Self) -> Option<Self> {
49 <$t>::checked_mul(*self, *v)
50 }
51 }
52 impl crate::core::CheckedDiv for $t {
53 fn checked_div(&self, v: &Self) -> Option<Self> {
54 <$t>::checked_div(*self, *v)
55 }
56 }
57 impl crate::core::CheckedRem for $t {
58 fn checked_rem(&self, v: &Self) -> Option<Self> {
59 <$t>::checked_rem(*self, *v)
60 }
61 }
62 )*)
63}