Skip to content

Commit 84ba770

Browse files
committed
int module: macro-ify trait impls and add {u,i}128 support
1 parent bdd3473 commit 84ba770

File tree

1 file changed

+38
-44
lines changed

1 file changed

+38
-44
lines changed

src/int/mod.rs

Lines changed: 38 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -10,28 +10,26 @@ pub trait Int {
1010
fn bits() -> u32;
1111
}
1212

13-
// TODO: Once i128/u128 support lands, we'll want to add impls for those as well
14-
impl Int for u32 {
15-
fn bits() -> u32 {
16-
32
17-
}
18-
}
19-
impl Int for i32 {
20-
fn bits() -> u32 {
21-
32
22-
}
23-
}
24-
impl Int for u64 {
25-
fn bits() -> u32 {
26-
64
27-
}
28-
}
29-
impl Int for i64 {
30-
fn bits() -> u32 {
31-
64
13+
macro_rules! int_impl {
14+
($ity:ty, $sty:ty, $bits:expr) => {
15+
impl Int for $ity {
16+
fn bits() -> u32 {
17+
$bits
18+
}
19+
}
20+
impl Int for $sty {
21+
fn bits() -> u32 {
22+
$bits
23+
}
24+
}
3225
}
3326
}
3427

28+
int_impl!(i32, u32, 32);
29+
int_impl!(i64, u64, 64);
30+
#[cfg(not(stage0))]
31+
int_impl!(i128, u128, 128);
32+
3533
/// Trait to convert an integer to/from smaller parts
3634
pub trait LargeInt {
3735
type LowHalf;
@@ -42,32 +40,28 @@ pub trait LargeInt {
4240
fn from_parts(low: Self::LowHalf, high: Self::HighHalf) -> Self;
4341
}
4442

45-
// TODO: Once i128/u128 support lands, we'll want to add impls for those as well
46-
impl LargeInt for u64 {
47-
type LowHalf = u32;
48-
type HighHalf = u32;
43+
macro_rules! large_int {
44+
($ty:ty, $tylow:ty, $tyhigh:ty, $halfbits:expr) => {
45+
impl LargeInt for $ty {
46+
type LowHalf = $tylow;
47+
type HighHalf = $tyhigh;
4948

50-
fn low(self) -> u32 {
51-
self as u32
52-
}
53-
fn high(self) -> u32 {
54-
(self >> 32) as u32
55-
}
56-
fn from_parts(low: u32, high: u32) -> u64 {
57-
low as u64 | ((high as u64) << 32)
49+
fn low(self) -> $tylow {
50+
self as $tylow
51+
}
52+
fn high(self) -> $tyhigh {
53+
(self >> $halfbits) as $tyhigh
54+
}
55+
fn from_parts(low: $tylow, high: $tyhigh) -> $ty {
56+
low as $ty | ((high as $ty) << $halfbits)
57+
}
58+
}
5859
}
5960
}
60-
impl LargeInt for i64 {
61-
type LowHalf = u32;
62-
type HighHalf = i32;
6361

64-
fn low(self) -> u32 {
65-
self as u32
66-
}
67-
fn high(self) -> i32 {
68-
(self >> 32) as i32
69-
}
70-
fn from_parts(low: u32, high: i32) -> i64 {
71-
low as i64 | ((high as i64) << 32)
72-
}
73-
}
62+
large_int!(u64, u32, u32, 32);
63+
large_int!(i64, u32, i32, 32);
64+
#[cfg(not(stage0))]
65+
large_int!(u128, u64, u64, 64);
66+
#[cfg(not(stage0))]
67+
large_int!(i128, u64, i64, 64);

0 commit comments

Comments
 (0)