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;
|
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) => {
|
||||||
fn bits() -> u32 {
|
impl Int for $ity {
|
||||||
32
|
fn bits() -> u32 {
|
||||||
}
|
$bits
|
||||||
}
|
}
|
||||||
impl Int for i32 {
|
}
|
||||||
fn bits() -> u32 {
|
impl Int for $sty {
|
||||||
32
|
fn bits() -> u32 {
|
||||||
}
|
$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) -> u32 {
|
fn high(self) -> $tyhigh {
|
||||||
(self >> 32) as u32
|
(self >> $halfbits) as $tyhigh
|
||||||
}
|
}
|
||||||
fn from_parts(low: u32, high: u32) -> u64 {
|
fn from_parts(low: $tylow, high: $tyhigh) -> $ty {
|
||||||
low as u64 | ((high as u64) << 32)
|
low as $ty | ((high as $ty) << $halfbits)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
Loading…
Reference in New Issue