Reputation: 669
I want to have a Rust function that allows adding an u32
(u64
, u128
) type to an i32
(i64
, i128
) type while checking for overflow.
My implementation:
/// Add u32 to i32. In case of an overflow, return None.
fn checked_add_i32_u32(a: i32, b: u32) -> Option<i32> {
let b_half = (b / 2) as i32;
let b_rem = (b % 2) as i32;
Some(a.checked_add(b_half)?.checked_add(b_half)?
.checked_add(b_rem)?)
}
/// Add u64 to i64. In case of an overflow, return None.
fn checked_add_i64_u64(a: i64, b: u64) -> Option<i64> {
let b_half = (b / 2) as i64;
let b_rem = (b % 2) as i64;
Some(a.checked_add(b_half)?.checked_add(b_half)?
.checked_add(b_rem)?)
}
I have another similar one that does the same for u128
and i128
. I feel like I am repeating myself. My tests for those functions also look very similar.
Is there a way I could refactor my code and have just one function instead? I am not sure how to generalize over the relationship between u32
and i32
(or u64
and i64
, u128
and i128
).
Upvotes: 6
Views: 1071
Reputation: 42749
You can use a macro:
trait CustomAdd: Copy {
type Unsigned;
fn my_checked_add(self, b: Self::Unsigned) -> Option<Self>;
}
macro_rules! impl_custom_add {
( $i:ty, $u:ty ) => {
impl CustomAdd for $i {
type Unsigned = $u;
fn my_checked_add(self, b: $u) -> Option<$i> {
let b_half = (b / 2) as $i;
let b_rem = (b % 2) as $i;
Some(self.checked_add(b_half)?.checked_add(b_half)?
.checked_add(b_rem)?)
}
}
}
}
impl_custom_add!(i32, u32);
impl_custom_add!(i64, u64);
// etc.
#[test]
fn tests() {
assert_eq!(123.my_checked_add(10_u32), Some(133));
}
Upvotes: 7