Skip to content

Commit b356429

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

File tree

1 file changed

+35
-44
lines changed

1 file changed

+35
-44
lines changed

src/int/mod.rs

Lines changed: 35 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -10,28 +10,25 @@ 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+
int_impl!(i128, u128, 128);
31+
3532
/// Trait to convert an integer to/from smaller parts
3633
pub trait LargeInt {
3734
type LowHalf;
@@ -42,32 +39,26 @@ pub trait LargeInt {
4239
fn from_parts(low: Self::LowHalf, high: Self::HighHalf) -> Self;
4340
}
4441

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;
42+
macro_rules! large_int {
43+
($ty:ty, $tylow:ty, $tyhigh:ty, $halfbits:expr) => {
44+
impl LargeInt for $ty {
45+
type LowHalf = $tylow;
46+
type HighHalf = $tyhigh;
4947

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)
48+
fn low(self) -> $tylow {
49+
self as $tylow
50+
}
51+
fn high(self) -> $tyhigh {
52+
(self >> $halfbits) as $tyhigh
53+
}
54+
fn from_parts(low: $tylow, high: $tyhigh) -> $ty {
55+
low as $ty | ((high as $ty) << $halfbits)
56+
}
57+
}
5858
}
5959
}
60-
impl LargeInt for i64 {
61-
type LowHalf = u32;
62-
type HighHalf = i32;
6360

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-
}
61+
large_int!(u64, u32, u32, 32);
62+
large_int!(i64, u32, i32, 32);
63+
large_int!(u128, u64, u64, 64);
64+
large_int!(i128, u64, i64, 64);

0 commit comments

Comments
 (0)