1
+ macro_rules! hty {
2
+ ( $ty: ty) => {
3
+ <$ty as LargeInt >:: HighHalf
4
+ }
5
+ }
6
+
7
+ macro_rules! os_ty {
8
+ ( $ty: ty) => {
9
+ <$ty as Int >:: OtherSign
10
+ }
11
+ }
1
12
2
13
pub mod mul;
3
14
pub mod sdiv;
@@ -6,32 +17,33 @@ pub mod udiv;
6
17
7
18
/// Trait for some basic operations on integers
8
19
pub trait Int {
20
+ /// Type with the same width but other signedness
21
+ type OtherSign ;
9
22
/// Returns the bitwidth of the int type
10
23
fn bits ( ) -> u32 ;
11
24
}
12
25
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
26
+ macro_rules! int_impl {
27
+ ( $ity: ty, $sty: ty, $bits: expr) => {
28
+ impl Int for $ity {
29
+ type OtherSign = $sty;
30
+ fn bits( ) -> u32 {
31
+ $bits
32
+ }
33
+ }
34
+ impl Int for $sty {
35
+ type OtherSign = $ity;
36
+ fn bits( ) -> u32 {
37
+ $bits
38
+ }
39
+ }
32
40
}
33
41
}
34
42
43
+ int_impl ! ( i32 , u32 , 32 ) ;
44
+ int_impl ! ( i64 , u64 , 64 ) ;
45
+ int_impl ! ( i128 , u128 , 128 ) ;
46
+
35
47
/// Trait to convert an integer to/from smaller parts
36
48
pub trait LargeInt {
37
49
type LowHalf ;
@@ -42,32 +54,26 @@ pub trait LargeInt {
42
54
fn from_parts ( low : Self :: LowHalf , high : Self :: HighHalf ) -> Self ;
43
55
}
44
56
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 ;
57
+ macro_rules! large_int {
58
+ ( $ty: ty, $tylow: ty, $tyhigh: ty, $halfbits: expr) => {
59
+ impl LargeInt for $ty {
60
+ type LowHalf = $tylow;
61
+ type HighHalf = $tyhigh;
49
62
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 )
63
+ fn low( self ) -> $tylow {
64
+ self as $tylow
65
+ }
66
+ fn high( self ) -> $tyhigh {
67
+ ( self >> $halfbits) as $tyhigh
68
+ }
69
+ fn from_parts( low: $tylow, high: $tyhigh) -> $ty {
70
+ low as $ty | ( ( high as $ty) << $halfbits)
71
+ }
72
+ }
58
73
}
59
74
}
60
- impl LargeInt for i64 {
61
- type LowHalf = u32 ;
62
- type HighHalf = i32 ;
63
75
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
- }
76
+ large_int ! ( u64 , u32 , u32 , 32 ) ;
77
+ large_int ! ( i64 , u32 , i32 , 32 ) ;
78
+ large_int ! ( u128 , u64 , u64 , 64 ) ;
79
+ large_int ! ( i128 , u64 , i64 , 64 ) ;
0 commit comments