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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
use core::{cmp::Ordering, convert::TryFrom, fmt, ops::{Deref, DerefMut}};

use ref_cast::RefCast;

use super::{Array, Bits, Convenient, Digit, Number, NumberMut, Odd, Prime, Unsigned};
use crate::{Error, Result, Wrapping};


#[cfg(target_pointer_width = "32")]
impl Bits for usize {
    const BITS: usize = 32;
}

#[cfg(target_pointer_width = "64")]
impl Bits for usize {
    const BITS: usize = 64;
}

impl Bits for u32 {
    const BITS: usize = 32;
}

impl Bits for u64 {
    const BITS: usize = 64;
}

impl Bits for u128 {
    const BITS: usize = 128;
}

impl<T: Number> Bits for T {
    const BITS: usize = T::BITS;
}

impl<const D: usize, const E: usize> Deref for Unsigned<D, E> {
    type Target = [Digit];
    fn deref(&self) -> &Self::Target {
        Number::deref(self)
    }
}

impl<const D: usize, const E: usize> DerefMut for Unsigned<D, E> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        Number::deref_mut(self)
    }
}

impl<const D: usize, const E: usize, const L: usize> Deref for Array<D, E, L> {
    type Target = [Digit];
    fn deref(&self) -> &Self::Target {
        Number::deref(self)
    }
}

impl<const D: usize, const E: usize, const L: usize> DerefMut for Array<D, E, L> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        Number::deref_mut(self)
    }
}

// TODO: Maybe Deref to &[Digit] directly?
// And add some From/Into games.

impl<const D: usize, const E: usize> Deref for Convenient<D, E> {
    type Target = Unsigned<D, E>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<const D: usize, const E: usize> DerefMut for Convenient<D, E> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<const D: usize, const E: usize> Deref for Odd<D, E> {
    type Target = Unsigned<D, E>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<const D: usize, const E: usize> DerefMut for Odd<D, E> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<const D: usize, const E: usize> Deref for Prime<D, E> {
    type Target = Convenient<D, E>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<const D: usize, const E: usize> DerefMut for Prime<D, E> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<const D: usize, const E: usize> AsRef<crate::Convenient<D, E>> for Prime<D, E> {
    fn as_ref(&self) -> &crate::Convenient<D, E> {
        &self.0
    }
}

impl<const D: usize, const E: usize> AsRef<crate::Unsigned<D, E>> for Convenient<D, E> {
    fn as_ref(&self) -> &crate::Unsigned<D, E> {
        &self.0.0
    }
}

impl<T: Number> Deref for Wrapping<T> {
    type Target = [Digit];
    fn deref(&self) -> &Self::Target {
        &*self.0
    }
}

impl<T: Number + NumberMut> DerefMut for Wrapping<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut *self.0
    }
}

unsafe impl<T: Number> Number for Wrapping<T> {}
impl<T: Number + NumberMut> NumberMut for Wrapping<T> {}


impl<const D: usize, const E: usize> TryFrom<Unsigned<D, E>> for Odd<D, E> {
    type Error = Error;
    /// Enforces odd parity.
    fn try_from(unsigned: Unsigned<D, E>) -> Result<Self> {
        unsigned.is_odd().then(|| Odd(unsigned)).ok_or(Error)
    }
}

impl<'a, const D: usize, const E: usize> TryFrom<&'a Unsigned<D, E>> for &'a Odd<D, E> {
    type Error = Error;
    /// Enforces odd parity.
    fn try_from(unsigned: &'a Unsigned<D, E>) -> Result<Self> {
        unsigned.is_odd().then(|| Odd::ref_cast(unsigned)).ok_or(Error)
    }
}

impl<const D: usize, const E: usize> From<Odd<D, E>> for Unsigned<D, E> {
    fn from(odd: Odd<D, E>) -> Self {
        odd.0
    }
}

impl<const D: usize, const E: usize> TryFrom<Unsigned<D, E>> for Convenient<D, E> {
    type Error = Error;
    /// Enforces odd parity.
    fn try_from(unsigned: Unsigned<D, E>) -> Result<Self> {
        if !unsigned.is_odd() {
            return Err(Error);
        }

        if unsigned.significant_digits().len() != Unsigned::<D, E>::DIGITS {
            #[cfg(test)]
            println!("unsigned = {:?}, len = {}, DIGITS = {}",
                &unsigned,
                unsigned.significant_digits().len(),
                Unsigned::<D, E>::DIGITS,
            );
            panic!("logic error");
            // return Err(Error);
        }

        // if unsigned.leading_digit().unwrap().leading_zeros() != 0 {
        //     return Err(Error);
        // }
        let top_bit = unsigned.leading_digit().unwrap() >> (Digit::BITS - 1);
        if top_bit == 0 {
            return Err(Error);
        }

        Ok(Self(Odd(Unsigned::try_from_slice(&unsigned)?)))
    }
}

impl<const D: usize, const E: usize> From<Convenient<D, E>> for Unsigned<D, E> {
    fn from(convenient: Convenient<D, E>) -> Self {
        convenient.0.0
    }
}

// Since we store little-endian, comparison needs to start at the last
// digit, instead of at the first as the derived / default implementation would.
impl<const D: usize, const E: usize> Ord for Unsigned<D, E> {
    fn cmp(&self, other: &Self) -> Ordering {
        Number::cmp(self, other)
    }
}

// Probably not very kosher ;)
// We can't do the entire `ct_eq`, `ct_gt` dance on Number::cmp level
// as subtle assume type(LHS) = type(RHS).

#[cfg(feature = "ct-maybe")]
impl<const D: usize, const E: usize> subtle::ConstantTimeEq for Unsigned<D, E> {
    fn ct_eq(&self, other: &Self) -> subtle::Choice {
        subtle::Choice::from((Number::cmp(self, other) == Ordering::Equal) as u8)
    }
}

#[cfg(feature = "ct-maybe")]
impl<const D: usize, const E: usize> subtle::ConstantTimeGreater for Unsigned<D, E> {
    fn ct_gt(&self, other: &Self) -> subtle::Choice {
        subtle::Choice::from((Number::cmp(self, other) == Ordering::Greater) as u8)
    }
}

#[cfg(feature = "ct-maybe")]
impl<const D: usize, const E: usize> subtle::ConstantTimeLess for Unsigned<D, E> {}

impl<T, const D: usize, const E: usize> PartialOrd<T> for Unsigned<D, E>
where
    T: Number,
{
    /// This is *little endian* ordering, as opposed to the default
    /// ordering on arrays and slices!
    fn partial_cmp(&self, other: &T) -> Option<Ordering> {
        Some(Number::cmp(self, other))
    }
}

impl<T, const D: usize, const E: usize, const L: usize> PartialOrd<T> for Array<D, E, L>
where
    T: Number,
{
    fn partial_cmp(&self, other: &T) -> Option<Ordering> {
        Some(Number::cmp(self, other))
    }
}

impl<T, const D: usize, const E: usize> PartialEq<T> for Unsigned<D, E>
where
    T: Number,
{
    fn eq(&self, other: &T) -> bool {
        Number::eq(self, other)
    }
}

impl<T, const D: usize, const E: usize, const L: usize> PartialEq<T> for Array<D, E, L>
where
    T: Number,
{
    fn eq(&self, other: &T) -> bool {
        Number::eq(self, other)
    }
}

impl<T, const D: usize, const E: usize> PartialEq<T> for Convenient<D, E>
where
    T: Number, //AsRef<S: Number>,
{
    fn eq(&self, other: &T) -> bool {
        Number::eq(&**self, other)//.as_ref())
    }
}


impl<const D: usize, const E: usize> Default for Unsigned<D, E> {
    fn default() -> Self {
        Self { lo: [0; D], hi: [0; E] }
    }
}

impl<const D: usize, const E: usize, const L: usize> Default for Array<D, E, L> {
    fn default() -> Self {
        Self { lo: [[0; D]; L], hi: [[0; E]; L] }
    }
}

impl<const D: usize, const E: usize> fmt::Debug for Unsigned<D, E> {
    /// TODO: Do we want debug output to be big-endian bytes (as currently implemented)?
    /// Or stick with internal representation?
    #[cfg(feature = "hex-debug")]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&delog::hex_str!(&*self.to_bytes(), 8), f)
    }
    #[cfg(not(feature = "hex-debug"))]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&*self.to_bytes(), f)
    }
}

impl<const D: usize, const E: usize, const L: usize> fmt::Debug for Array<D, E, L> {
    /// TODO: Do we want debug output to be big-endian bytes (as currently implemented)?
    /// Or stick with internal representation?
    #[cfg(feature = "hex-debug")]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&delog::hex_str!(&*self.to_bytes(), 8), f)
    }
    #[cfg(not(feature = "hex-debug"))]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&*self.to_bytes(), f)
    }
}