int module: macro-ify trait impls and add {u,i}128 support
This commit is contained in:
parent
a2e2ec1a18
commit
b356429374
@ -10,28 +10,25 @@ pub trait Int {
|
||||
fn bits() -> u32;
|
||||
}
|
||||
|
||||
// TODO: Once i128/u128 support lands, we'll want to add impls for those as well
|
||||
impl Int for u32 {
|
||||
fn bits() -> u32 {
|
||||
32
|
||||
}
|
||||
}
|
||||
impl Int for i32 {
|
||||
fn bits() -> u32 {
|
||||
32
|
||||
}
|
||||
}
|
||||
impl Int for u64 {
|
||||
fn bits() -> u32 {
|
||||
64
|
||||
}
|
||||
}
|
||||
impl Int for i64 {
|
||||
fn bits() -> u32 {
|
||||
64
|
||||
macro_rules! int_impl {
|
||||
($ity:ty, $sty:ty, $bits:expr) => {
|
||||
impl Int for $ity {
|
||||
fn bits() -> u32 {
|
||||
$bits
|
||||
}
|
||||
}
|
||||
impl Int for $sty {
|
||||
fn bits() -> u32 {
|
||||
$bits
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int_impl!(i32, u32, 32);
|
||||
int_impl!(i64, u64, 64);
|
||||
int_impl!(i128, u128, 128);
|
||||
|
||||
/// Trait to convert an integer to/from smaller parts
|
||||
pub trait LargeInt {
|
||||
type LowHalf;
|
||||
@ -42,32 +39,26 @@ pub trait LargeInt {
|
||||
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
|
||||
impl LargeInt for u64 {
|
||||
type LowHalf = u32;
|
||||
type HighHalf = u32;
|
||||
macro_rules! large_int {
|
||||
($ty:ty, $tylow:ty, $tyhigh:ty, $halfbits:expr) => {
|
||||
impl LargeInt for $ty {
|
||||
type LowHalf = $tylow;
|
||||
type HighHalf = $tyhigh;
|
||||
|
||||
fn low(self) -> u32 {
|
||||
self as u32
|
||||
}
|
||||
fn high(self) -> u32 {
|
||||
(self >> 32) as u32
|
||||
}
|
||||
fn from_parts(low: u32, high: u32) -> u64 {
|
||||
low as u64 | ((high as u64) << 32)
|
||||
fn low(self) -> $tylow {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl LargeInt for i64 {
|
||||
type LowHalf = u32;
|
||||
type HighHalf = i32;
|
||||
|
||||
fn low(self) -> u32 {
|
||||
self as u32
|
||||
}
|
||||
fn high(self) -> i32 {
|
||||
(self >> 32) as i32
|
||||
}
|
||||
fn from_parts(low: u32, high: i32) -> i64 {
|
||||
low as i64 | ((high as i64) << 32)
|
||||
}
|
||||
}
|
||||
large_int!(u64, u32, u32, 32);
|
||||
large_int!(i64, u32, i32, 32);
|
||||
large_int!(u128, u64, u64, 64);
|
||||
large_int!(i128, u64, i64, 64);
|
||||
|
Loading…
Reference in New Issue
Block a user