From ad1253805ed84baef06896490b5cfe6e525a4312 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jose=CC=81=20Molina?= Date: Tue, 2 Apr 2024 14:53:35 +0200 Subject: [PATCH] implement Incrementable for native types --- uint/src/uint.rs | 20 ++++++++++++++++++++ uint/tests/uint_tests.rs | 11 +++++++++++ 2 files changed, 31 insertions(+) diff --git a/uint/src/uint.rs b/uint/src/uint.rs index 101cd995..c7073dcc 100644 --- a/uint/src/uint.rs +++ b/uint/src/uint.rs @@ -127,6 +127,22 @@ impl From for FromStrRadixErr { } } +macro_rules! impl_incrementable { + ($($type:ty),+) => { + $( + impl Incrementable for $type { + fn increment(&self) -> Option { + self.checked_add(1) + } + + fn initial_value() -> Option { + Some(0) + } + } + )+ + }; +} + /// A trait representing an incrementable type. /// /// The `increment` and `initial_value` functions are fallible. @@ -146,6 +162,10 @@ pub trait Incrementable fn initial_value() -> Option; } +impl_incrementable!(u8, u16, u32, u64, u128, i8, i16, i32, i64, i128); + + + /// Conversion from decimal string error #[derive(Debug, PartialEq, Eq)] pub enum FromDecStrErr { diff --git a/uint/tests/uint_tests.rs b/uint/tests/uint_tests.rs index 8ac7135f..ebfd6aa9 100644 --- a/uint/tests/uint_tests.rs +++ b/uint/tests/uint_tests.rs @@ -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()));