1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
#![no_std]

//! # pow_of_2
//! 
//! Integer-like types which can only represent powers of 2. Internally,
//! they are stored as a one-byte exponent. This allows them to implement
//! arithmetic operators with other, simpler artithmetic operators.

#[cfg(test)]
mod tests;

use core::{
    u8,
    ops::{Shl, Mul, Div, MulAssign, DivAssign},
    mem::size_of,
    fmt::{self, Formatter, Display, Debug},
    any::type_name,
    marker::PhantomData,
};


pub trait UInt: Copy + Shl<Output=Self> + Display {
    fn one() -> Self;
    fn from_u8(b: u8) -> Self;
}

macro_rules! impl_uint {
    ($($t:ty),*)=>{$(
        impl UInt for $t {
            #[inline(always)] fn one() -> $t { 1 } 
            #[inline(always)] fn from_u8(b: u8) -> $t { b as $t }
        }
    )*};
}
impl_uint!(usize, u8, u16, u32, u64, u128);


/// Unsigned integer powers of 2.
///
/// Internally just an exponent. Consequentially takes 
/// advantage of bit-manipulation. Runtime-checked to be 
/// valid values of `T`. 
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct PowOf2<T: UInt> {
    exp: u8,
    p: PhantomData<T>,
}

impl<T: UInt> PowOf2<T> {
    /// Fails if above `T`s domains.
    #[inline(always)]
    pub fn try_from_exp(exp: u8) -> Option<Self> {
        if (exp as usize) < (size_of::<T>() * 8) {
            Some(PowOf2 { exp, p: PhantomData })
        } else { None }
    }
    
    /// Panics if above `T`s domains.
    #[inline(always)]
    pub fn from_exp(exp: u8) -> Self {
        PowOf2::try_from_exp(exp)
            .unwrap_or_else(|| panic!("exponent {} beyond domain of {}", 
                exp, type_name::<T>()))
    }
    
    /// Raise self to a power.
    /// 
    /// Fails if above `T`'s domain.
    #[inline(always)]
    pub fn try_pow(self, p: u8) -> Option<Self> {
        u8::checked_add(self.exp, p)
            .and_then(PowOf2::try_from_exp)
    }
    
    /// Raise self to a power.
    /// 
    /// Panics if above `T`'s domain.
    #[inline(always)]
    pub fn pow(self, p: u8) -> Self {
        let exp2 = u8::checked_add(self.exp, p)
            .unwrap_or_else(|| panic!("sum of exponents {} and {} cannot \
                be represented by u8", self.exp, p));
        PowOf2::from_exp(exp2)
    }
    
    /// Raise self to a negative power.
    ///
    /// Should not panic, simply bottoms out at zero.
    #[inline(always)]
    pub fn pow_neg(self, p: u8) -> Self {
        PowOf2 { 
            exp: u8::saturating_sub(self.exp, p),
            p: PhantomData,
        }
    }
    
    /// Represent as non-exponent.
    ///
    /// Should not fail at this point (would fail earlier).
    #[inline(always)]
    pub fn to_uint(self) -> T {
        T::one() << T::from_u8(self.exp)
    }
    
    /// Get exponent.
    #[inline(always)]
    pub fn exp(self) -> u8 {
        self.exp
    }
}


// ==== type-enhanced arithmetic ====


impl<T: UInt> Mul<PowOf2<T>> for PowOf2<T> {
    type Output = PowOf2<T>;
    
    #[inline(always)]
    fn mul(self, rhs: PowOf2<T>) -> PowOf2<T> {
        self.pow(rhs.exp)
    }
}

impl<T: UInt> MulAssign<PowOf2<T>> for PowOf2<T> {
    #[inline(always)]
    fn mul_assign(&mut self, rhs: PowOf2<T>) {
        *self = *self * rhs;
    }
}

impl<T: UInt> Div<PowOf2<T>> for PowOf2<T> {
    type Output = PowOf2<T>;
    
    #[inline(always)]
    fn div(self, rhs: PowOf2<T>) -> PowOf2<T> {
        self.pow_neg(rhs.exp)
    }
}

impl<T: UInt> DivAssign<PowOf2<T>> for PowOf2<T> {
    #[inline(always)]
    fn div_assign(&mut self, rhs: PowOf2<T>) {
        *self = *self / rhs;
    }
}


/// Unitary representation of 2, for `PowOf2` arithmetic.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Two;

impl<T: UInt> Mul<Two> for PowOf2<T> {
    type Output = PowOf2<T>;
    
    #[inline(always)]
    fn mul(self, Two: Two) -> PowOf2<T> {
        self.pow(1)
    }
}

impl<T: UInt> MulAssign<Two> for PowOf2<T> {
    #[inline(always)]
    fn mul_assign(&mut self, Two: Two) {
        *self = *self * Two;
    }
}

impl<T: UInt> Div<Two> for PowOf2<T> {
    type Output = PowOf2<T>;
    
    #[inline(always)]
    fn div(self, Two: Two) -> PowOf2<T> {
        self.pow_neg(1)
    }
}

impl<T: UInt> DivAssign<Two> for PowOf2<T> {
    #[inline(always)]
    fn div_assign(&mut self, Two: Two) {
        *self = *self / Two;
    }
}


// ==== power of 2 constants ====

macro_rules! pow_of_2_consts {
    (#[$attr:meta] for $ty:ty {$( ($($t:tt)*) )*})=>{
        $( pow_of_2_consts!(@try_recurse ($($t)*) ); )*
        pow_of_2_consts!(@items #[$attr] $ty {} {$( ($($t)*) )*});
    };
    
    (@items #[$attr:meta] $ty:ty {$($accum:tt)*} 
            {})=>{ 
        impl PowOf2<$ty> {$($accum)*}
        
        #[$attr] impl PowOf2<usize> {$($accum)*}
        
        //#[cfg(target_pointer_width = stringify!($ty))]
        //impl PowOf2<usize> {$($accum)*}
    };
    (@items #[$attr:meta] $ty:ty {$($accum:tt)*} 
            {($name:ident : $exp:expr) $($t:tt)*})=>{
        pow_of_2_consts!(@items #[$attr] $ty { 
            $($accum)* 
            pub const $name: Self = PowOf2 {
                exp: $exp,
                p: PhantomData,
            };
        } { $($t)* });
    };
    (@items #[$attr:meta] $ty:ty {$($accum:tt)*} 
            {(#[$attr2:meta] for $ty2:ty {$( ($($t2:tt)*) )*}) $($t:tt)*})=>{
        pow_of_2_consts!(@items #[$attr] $ty
            {$($accum)*}
            {$( ( $($t2)* ) )* $($t)*});
    };
    
    (@try_recurse ( #[$attr:meta] for $ty:ty {$( ($($t:tt)*) )*} ))=>{
        pow_of_2_consts!( #[$attr] for $ty {$( ($( $t )*) )*} );
    };
    (@try_recurse ( $name:ident : $exp:expr ))=>{};
}

pow_of_2_consts! {
    #[cfg(target_pointer_width = "128")] for u128 {
        (#[cfg(target_pointer_width = "64")] for u64 {
            (#[cfg(target_pointer_width = "32")] for u32 {
                (#[cfg(target_pointer_width = "16")] for u16 {
                    (#[cfg(target_pointer_width = "8")] for u8 {
                        (_1: 0)
                        (_2: 1)
                        (_4: 2)
                        (_8: 3)
                        (_16: 4)
                        (_32: 5)
                        (_64: 6)
                        (_128: 7)
                    })
                    (_256: 8)
                    (_512: 9)
                    (KIBI: 10)
                })
                (MEBI: 20)
                (GIBI: 30)
            })
            (TEBI: 40)
            (PEBI: 50)
            (EXBI: 60)
            
        })
        (ZEBI: 70)
        (YOBI: 80)
        (_2E90: 90)
        (_2E100: 100)
        (_2E110: 110)
        (_2E120: 120)
    }
}

// ==== formatters ====

impl<T: UInt> Debug for PowOf2<T> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.debug_struct("PowOf2")
            .field("exp", &self.exp)
            .finish()
    }
}

impl<T: UInt> Display for PowOf2<T> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        Display::fmt(&format_args!("2^{}", self.exp), f)
    }
}

impl Debug for Two {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result { 
        Debug::fmt(&2, f)
    }
}

impl Display for Two {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result { 
        Display::fmt(&2, f)
    }
}