Skip to content

Commit

Permalink
Add BITS associated constant
Browse files Browse the repository at this point in the history
Merges: #69
  • Loading branch information
chrysn authored Mar 1, 2024
2 parents f0c03bd + b74c374 commit bd22f23
Showing 1 changed file with 9 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ macro_rules! define_unsigned {
impl $name {
pub const MAX: Self = $name(((1 as $type) << $bits) -1 );
pub const MIN: Self = $name(0);
pub const BITS: u32 = $bits;

fn mask(self) -> Self {
$name(self.0 & ( ((1 as $type) << $bits).overflowing_sub(1).0))
Expand All @@ -67,6 +68,7 @@ macro_rules! define_signed {
impl $name {
pub const MAX: Self = $name(((1 as $type) << ($bits - 1)) - 1);
pub const MIN: Self = $name(-((1 as $type) << ($bits - 1)));
pub const BITS: u32 = $bits;

fn mask(self) -> Self {
if ( self.0 & (1<<($bits-1)) ) == 0 {
Expand Down Expand Up @@ -735,6 +737,13 @@ mod tests {
assert_eq!(i9::MIN, i9(-256));
}

#[test]
fn test_bits_values() {
assert_eq!(u1::BITS, 1);
assert_eq!(i7::BITS, 7);
assert_eq!(u127::BITS, 127);
}

#[test]
fn test_wrapping_add() {
assert_eq!(u1::MAX.wrapping_add(u1(1)), u1(0));
Expand Down

0 comments on commit bd22f23

Please sign in to comment.