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+ }
112
213pub mod mul;
314pub mod sdiv;
@@ -6,32 +17,33 @@ pub mod udiv;
617
718/// Trait for some basic operations on integers
819pub trait Int {
20+ /// Type with the same width but other signedness
21+ type OtherSign ;
922 /// Returns the bitwidth of the int type
1023 fn bits ( ) -> u32 ;
1124}
1225
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+ }
3240 }
3341}
3442
43+ int_impl ! ( i32 , u32 , 32 ) ;
44+ int_impl ! ( i64 , u64 , 64 ) ;
45+ int_impl ! ( i128 , u128 , 128 ) ;
46+
3547/// Trait to convert an integer to/from smaller parts
3648pub trait LargeInt {
3749 type LowHalf ;
@@ -42,32 +54,26 @@ pub trait LargeInt {
4254 fn from_parts ( low : Self :: LowHalf , high : Self :: HighHalf ) -> Self ;
4355}
4456
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;
4962
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+ }
5873 }
5974}
60- impl LargeInt for i64 {
61- type LowHalf = u32 ;
62- type HighHalf = i32 ;
6375
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