int module: macro-ify trait impls and add {u,i}128 support

This commit is contained in:
est31 2017-01-04 01:52:47 +01:00
parent a2e2ec1a18
commit b356429374
1 changed files with 35 additions and 44 deletions

View File

@ -10,28 +10,25 @@ pub trait Int {
fn bits() -> u32; fn bits() -> u32;
} }
// TODO: Once i128/u128 support lands, we'll want to add impls for those as well macro_rules! int_impl {
impl Int for u32 { ($ity:ty, $sty:ty, $bits:expr) => {
impl Int for $ity {
fn bits() -> u32 { fn bits() -> u32 {
32 $bits
} }
} }
impl Int for i32 { impl Int for $sty {
fn bits() -> u32 { fn bits() -> u32 {
32 $bits
} }
} }
impl Int for u64 {
fn bits() -> u32 {
64
}
}
impl Int for i64 {
fn bits() -> u32 {
64
} }
} }
int_impl!(i32, u32, 32);
int_impl!(i64, u64, 64);
int_impl!(i128, u128, 128);
/// Trait to convert an integer to/from smaller parts /// Trait to convert an integer to/from smaller parts
pub trait LargeInt { pub trait LargeInt {
type LowHalf; type LowHalf;
@ -42,32 +39,26 @@ pub trait LargeInt {
fn from_parts(low: Self::LowHalf, high: Self::HighHalf) -> Self; fn from_parts(low: Self::LowHalf, high: Self::HighHalf) -> Self;
} }
// TODO: Once i128/u128 support lands, we'll want to add impls for those as well macro_rules! large_int {
impl LargeInt for u64 { ($ty:ty, $tylow:ty, $tyhigh:ty, $halfbits:expr) => {
type LowHalf = u32; impl LargeInt for $ty {
type HighHalf = u32; type LowHalf = $tylow;
type HighHalf = $tyhigh;
fn low(self) -> u32 { fn low(self) -> $tylow {
self as u32 self as $tylow
}
fn high(self) -> $tyhigh {
(self >> $halfbits) as $tyhigh
}
fn from_parts(low: $tylow, high: $tyhigh) -> $ty {
low as $ty | ((high as $ty) << $halfbits)
} }
fn high(self) -> u32 {
(self >> 32) as u32
} }
fn from_parts(low: u32, high: u32) -> u64 {
low as u64 | ((high as u64) << 32)
} }
} }
impl LargeInt for i64 {
type LowHalf = u32;
type HighHalf = i32;
fn low(self) -> u32 { large_int!(u64, u32, u32, 32);
self as u32 large_int!(i64, u32, i32, 32);
} large_int!(u128, u64, u64, 64);
fn high(self) -> i32 { large_int!(i128, u64, i64, 64);
(self >> 32) as i32
}
fn from_parts(low: u32, high: i32) -> i64 {
low as i64 | ((high as i64) << 32)
}
}