Skip to content

Commit c6e06f4

Browse files
author
Jorge Aparicio
committed
refactor 'impl Int'
1 parent 09d2f2f commit c6e06f4

File tree

1 file changed

+29
-52
lines changed

1 file changed

+29
-52
lines changed

src/int/mod.rs

+29-52
Original file line numberDiff line numberDiff line change
@@ -38,67 +38,44 @@ pub trait Int {
3838
fn extract_sign(self) -> (bool, Self::UnsignedInt);
3939
}
4040

41-
// TODO: Once i128/u128 support lands, we'll want to add impls for those as well
42-
impl Int for u32 {
43-
type OtherSign = i32;
44-
type UnsignedInt = u32;
45-
46-
fn bits() -> u32 {
47-
32
48-
}
49-
50-
fn extract_sign(self) -> (bool, u32) {
51-
(false, self)
52-
}
53-
}
54-
55-
impl Int for i32 {
56-
type OtherSign = u32;
57-
type UnsignedInt = u32;
58-
59-
fn bits() -> u32 {
60-
32
61-
}
41+
macro_rules! int_impl {
42+
($ity:ty, $uty:ty, $bits:expr) => {
43+
impl Int for $uty {
44+
type OtherSign = $ity;
45+
type UnsignedInt = $uty;
46+
47+
fn bits() -> u32 {
48+
$bits
49+
}
6250

63-
fn extract_sign(self) -> (bool, u32) {
64-
if self < 0 {
65-
(true, !(self as u32) + 1)
66-
} else {
67-
(false, self as u32)
51+
fn extract_sign(self) -> (bool, $uty) {
52+
(false, self)
53+
}
6854
}
69-
}
70-
}
71-
72-
impl Int for u64 {
73-
type OtherSign = i64;
74-
type UnsignedInt = u64;
75-
76-
fn bits() -> u32 {
77-
64
78-
}
7955

80-
fn extract_sign(self) -> (bool, u64) {
81-
(false, self)
82-
}
83-
}
56+
impl Int for $ity {
57+
type OtherSign = $uty;
58+
type UnsignedInt = $uty;
8459

85-
impl Int for i64 {
86-
type OtherSign = u64;
87-
type UnsignedInt = u64;
88-
89-
fn bits() -> u32 {
90-
64
91-
}
60+
fn bits() -> u32 {
61+
$bits
62+
}
9263

93-
fn extract_sign(self) -> (bool, u64) {
94-
if self < 0 {
95-
(true, !(self as u64) + 1)
96-
} else {
97-
(false, self as u64)
64+
fn extract_sign(self) -> (bool, $uty) {
65+
if self < 0 {
66+
(true, !(self as $uty) + 1)
67+
} else {
68+
(false, self as $uty)
69+
}
70+
}
9871
}
9972
}
10073
}
10174

75+
int_impl!(i32, u32, 32);
76+
int_impl!(i64, u64, 64);
77+
int_impl!(i128, u128, 128);
78+
10279
/// Trait to convert an integer to/from smaller parts
10380
pub trait LargeInt {
10481
type LowHalf;

0 commit comments

Comments
 (0)