Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ pub use crate::ops::wrapping::{
WrappingAdd, WrappingMul, WrappingNeg, WrappingShl, WrappingShr, WrappingSub,
};
pub use crate::pow::{checked_pow, pow, Pow};
pub use crate::sign::{abs, abs_sub, signum, Signed, Unsigned};
pub use crate::sign::{abs, abs_sub, signum, Signed, Unsigned, UnsignedAbs};

#[macro_use]
mod macros;
Expand Down
44 changes: 43 additions & 1 deletion src/sign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use core::num::Wrapping;
use core::ops::Neg;

use crate::float::FloatCore;
use crate::Num;
use crate::{Num, PrimInt};

/// Useful functions for signed numbers (i.e. numbers that can be negative).
pub trait Signed: Sized + Num + Neg<Output = Self> {
Expand Down Expand Up @@ -214,3 +214,45 @@ fn signed_wrapping_is_signed() {
fn require_signed<T: Signed>(_: &T) {}
require_signed(&Wrapping(-42));
}

/// A trait for values which can be converted to an unsigned type with the unsigned_abs utility method.
pub trait UnsignedAbs {
type Unsigned: PrimInt + Unsigned;

fn unsigned_abs(&self) -> Self::Unsigned;
}

macro_rules! unsigned_abs_impl {
($($t:ty:$ut:ty),*) => ($(
impl UnsignedAbs for $t {
type Unsigned = $ut;

#[inline(always)]
fn unsigned_abs(&self) -> Self::Unsigned {
<$t>::unsigned_abs(*self)
}
}
)*)
}

unsigned_abs_impl!(i8:u8, i16:u16, i32:u32, i64:u64, i128:u128, isize:usize);

#[test]
fn unsigned_abs_test() {
fn require_unsigned_abs<T: UnsignedAbs>(_: &T) {}

require_unsigned_abs(&-42_i8);
require_unsigned_abs(&-42_i16);
require_unsigned_abs(&-42_i32);
require_unsigned_abs(&-42_i64);
require_unsigned_abs(&-42_i128);
require_unsigned_abs(&-42_isize);

assert_eq!((-42_i8).unsigned_abs(), 42_u8);
assert_eq!(42_i8.unsigned_abs(), 42_u8);
assert_eq!(i8::MIN.unsigned_abs(), 128_u8);

assert_eq!((-42_i32).unsigned_abs(), 42_u32);
assert_eq!(42_i32.unsigned_abs(), 42_u32);
assert_eq!(i32::MIN.unsigned_abs(), 2147483648_u32);
}