Skip to content

Commit

Permalink
implement Incrementable for native types
Browse files Browse the repository at this point in the history
  • Loading branch information
Moliholy committed Apr 2, 2024
1 parent 2266572 commit ad12538
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
20 changes: 20 additions & 0 deletions uint/src/uint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,22 @@ impl From<FromHexError> for FromStrRadixErr {
}
}

macro_rules! impl_incrementable {
($($type:ty),+) => {
$(
impl Incrementable for $type {
fn increment(&self) -> Option<Self> {
self.checked_add(1)
}

fn initial_value() -> Option<Self> {
Some(0)
}
}
)+
};
}

/// A trait representing an incrementable type.
///
/// The `increment` and `initial_value` functions are fallible.
Expand All @@ -146,6 +162,10 @@ pub trait Incrementable
fn initial_value() -> Option<Self>;
}

impl_incrementable!(u8, u16, u32, u64, u128, i8, i16, i32, i64, i128);



/// Conversion from decimal string error
#[derive(Debug, PartialEq, Eq)]
pub enum FromDecStrErr {
Expand Down
11 changes: 11 additions & 0 deletions uint/tests/uint_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1194,6 +1194,17 @@ fn bit_assign() {

#[test]
fn increment() {
macro_rules! test_incrementable {
($($type:ident),+) => {
$(
assert_eq!($type::from(0 as $type).increment(), Some(1 as $type));
assert_eq!($type::max_value().increment(), None);
assert_eq!($type::initial_value(), Some(0 as $type));
)+
};
}
test_incrementable!(u8, u16, u32, u64, u128, i8, i16, i32, i64, i128);

assert_eq!(U256::from(0).increment(), Some(1.into()));
assert_eq!(U256::max_value().increment(), None);
assert_eq!(U256::initial_value(), Some(0.into()));
Expand Down

0 comments on commit ad12538

Please sign in to comment.