geo_aid_script/token/
number.rs

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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! Functionality for parsing numbers, including managing operations with
//! arbitrary precision.

use num_bigint::BigInt;
use num_complex::Complex;
use std::cmp::Ordering;
use std::fmt::Formatter;
use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, SubAssign};
use std::{fmt::Display, mem};

use crate::geometry;
use crate::token::Number;
use num_rational::{BigRational, Rational64};
use num_traits::{CheckedAdd, CheckedMul, FromPrimitive, One, ToPrimitive, Zero};
use serde::Serialize;

/// An error while parsing an integer.
#[derive(Debug)]
pub struct ParseIntError;

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
/// Unsigned parsed integer of arbitrary size.
pub struct ParsedInt {
    /// Decimal digits of this number, most significant first.
    /// If a zero, has a single `0` digit. Otherwise no leading zeros.
    digits: Vec<u8>,
}

impl ParsedInt {
    /// Parse this number as the given type.
    ///
    /// # Errors
    /// Returns an error if the value is too big to fit in the given type.
    pub fn parse<T: Zero + CheckedMul + CheckedAdd + FromPrimitive>(
        &self,
    ) -> Result<T, ParseIntError> {
        let ten = T::from_u8(10).ok_or(ParseIntError)?;

        self.digits
            .iter()
            .copied()
            .try_fold(T::zero(), |v, item| {
                let item = T::from_u8(item)?;
                v.checked_mul(&ten).and_then(|x| x.checked_add(&item))
            })
            .ok_or(ParseIntError)
    }

    /// # Panics
    /// Should not.
    #[must_use]
    pub fn to_float(&self) -> f64 {
        self.digits
            .iter()
            .copied()
            .fold(0.0, |v, item| v * 10.0 + item.to_f64().unwrap())
    }

    /// Check if this number is a 0.
    #[must_use]
    pub fn is_zero(&self) -> bool {
        self.digits[0] == 0
    }

    /// Check if this number is a 1.
    #[must_use]
    pub fn is_one(&self) -> bool {
        self.digits[0] == 1 && self.digits.len() == 1
    }
}

impl Display for ParsedInt {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            self.digits
                .iter()
                .map(ToString::to_string)
                .collect::<String>()
        )
    }
}

/// A utility builder struct for parsing integers.
#[derive(Debug, Default)]
pub struct ParsedIntBuilder {
    /// Digits of the number, most significant first.
    /// Holds no other invariants.
    digits: Vec<u8>,
}

impl ParsedIntBuilder {
    /// Create a new, empty builder.
    #[must_use]
    pub fn new() -> Self {
        Self { digits: Vec::new() }
    }

    /// Push a digit at the end of this number.
    pub fn push_digit(&mut self, digit: u8) {
        self.digits.push(digit);
    }

    /// Validate the number.
    #[must_use]
    pub fn build(self) -> ParsedInt {
        ParsedInt {
            digits: self.digits,
        }
    }

    #[must_use]
    pub fn dot(self) -> ParsedFloatBuilder {
        ParsedFloatBuilder {
            integral: self.build(),
            digits: Vec::new(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
/// Signed arbitrary precision decimal for parsing.
pub struct ParsedFloat {
    /// The integer part
    integral: ParsedInt,
    /// Decimal digits, most significant first.
    decimal: Vec<u8>,
}

impl ParsedFloat {
    /// Parse this as a `f64`
    ///
    /// # Panics
    /// Should not.
    #[must_use]
    pub fn to_float(&self) -> f64 {
        self.integral.to_float()
            + self
                .decimal
                .iter()
                .copied()
                .enumerate()
                .fold(0.0, |v, (i, item)| {
                    v + item.to_f64().unwrap() * f64::powi(10.0, -(i.to_i32().unwrap() + 1))
                })
    }

    /// Check if this is a `0`.
    #[must_use]
    pub fn is_zero(&self) -> bool {
        self.integral.is_zero() && self.decimal.is_empty()
    }

    /// Check if this is a `1`
    #[must_use]
    pub fn is_one(&self) -> bool {
        self.integral.is_one() && self.decimal.is_empty()
    }
}

impl Display for ParsedFloat {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}.{}",
            self.integral,
            self.decimal
                .iter()
                .map(ToString::to_string)
                .collect::<String>()
        )
    }
}

/// A utility builder for decimal numbers.
#[derive(Debug)]
pub struct ParsedFloatBuilder {
    /// The integral part
    integral: ParsedInt,
    /// Digits, most significant first.
    digits: Vec<u8>,
}

impl ParsedFloatBuilder {
    /// Push a decimal digit at the end.
    pub fn push_digit(&mut self, digit: u8) {
        self.digits.push(digit);
    }

    /// Build a valid decimal.
    #[must_use]
    pub fn build(self) -> ParsedFloat {
        let mut digits = Vec::new();
        let mut segment = Vec::new();

        for d in self.digits {
            if d == 0 {
                segment.push(d);
            } else {
                let taken = mem::take(&mut segment);
                digits.extend(taken);
                digits.push(d);
            }
        }

        ParsedFloat {
            integral: self.integral,
            decimal: digits,
        }
    }
}

/// A parsed number of arbitrary size and precision.
#[derive(Debug, Clone)]
pub enum Parsed {
    Int(ParsedInt),
    Float(ParsedFloat),
}

impl Display for Parsed {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Parsed::Int(v) => write!(f, "{v}"),
            Parsed::Float(v) => write!(f, "{v}"),
        }
    }
}

/// Arbitrary precision complex number for processing
#[derive(Debug, Clone, Hash, Serialize, PartialEq, Eq)]
pub struct ProcNum(Complex<BigRational>);

impl ProcNum {
    /// Turn this into a floating point 64-bit precision complex number.
    ///
    /// # Panics
    /// A panic is a bug
    #[must_use]
    pub fn to_complex(&self) -> geometry::Complex {
        geometry::Complex::new(self.0.re.to_f64().unwrap(), self.0.im.to_f64().unwrap())
    }

    /// Pi as this number type.
    ///
    /// # Panics
    /// A panic is a bug.
    #[must_use]
    pub fn pi() -> Self {
        Self(Complex::new(
            BigRational::from_f64(std::f64::consts::PI).unwrap(),
            BigRational::zero(),
        ))
    }
}

impl FromPrimitive for ProcNum {
    fn from_i64(n: i64) -> Option<Self> {
        Complex::from_i64(n).map(Self)
    }

    fn from_u64(n: u64) -> Option<Self> {
        Complex::from_u64(n).map(Self)
    }

    fn from_f32(n: f32) -> Option<Self> {
        Complex::from_f32(n).map(Self)
    }

    fn from_f64(n: f64) -> Option<Self> {
        Complex::from_f64(n).map(Self)
    }
}

impl SubAssign<&Self> for ProcNum {
    fn sub_assign(&mut self, rhs: &Self) {
        self.0 -= &rhs.0;
    }
}

impl AddAssign<&Self> for ProcNum {
    fn add_assign(&mut self, rhs: &Self) {
        self.0 += &rhs.0;
    }
}

impl Add for ProcNum {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        Self(self.0 + rhs.0)
    }
}

impl Add<&Self> for ProcNum {
    type Output = Self;

    fn add(self, rhs: &Self) -> Self::Output {
        Self(self.0 + &rhs.0)
    }
}

impl Mul for ProcNum {
    type Output = Self;

    fn mul(self, rhs: Self) -> Self::Output {
        Self(self.0 * rhs.0)
    }
}

impl Mul<&Self> for ProcNum {
    type Output = Self;

    fn mul(self, rhs: &Self) -> Self::Output {
        Self(self.0 * &rhs.0)
    }
}

impl MulAssign<&Self> for ProcNum {
    fn mul_assign(&mut self, rhs: &Self) {
        self.0 *= &rhs.0;
    }
}

impl Div<&Self> for ProcNum {
    type Output = Self;

    fn div(self, rhs: &Self) -> Self::Output {
        Self(self.0 / &rhs.0)
    }
}

impl DivAssign<&Self> for ProcNum {
    fn div_assign(&mut self, rhs: &Self) {
        self.0 /= &rhs.0;
    }
}

impl Zero for ProcNum {
    fn zero() -> Self {
        Self(Complex::zero())
    }

    fn is_zero(&self) -> bool {
        self.0.is_zero()
    }
}

impl One for ProcNum {
    fn one() -> Self {
        Self(Complex::one())
    }

    fn is_one(&self) -> bool
    where
        Self: PartialEq,
    {
        self.0.is_one()
    }
}

impl Display for ProcNum {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl PartialOrd for ProcNum {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for ProcNum {
    fn cmp(&self, other: &Self) -> Ordering {
        match self.0.re.cmp(&other.0.re) {
            Ordering::Equal => self.0.im.cmp(&other.0.im),
            ord => ord,
        }
    }
}

impl From<&Number> for ProcNum {
    fn from(value: &Number) -> Self {
        let ten = Complex::from_u8(10).unwrap();

        match value {
            Number::Integer(i) => {
                let mut x: Complex<BigRational> = Complex::zero();

                for digit in &i.parsed.digits {
                    x *= &ten;
                    x += Complex::from_u8(*digit).unwrap();
                }

                Self(x)
            }
            Number::Float(f) => {
                let mut integral: Complex<BigRational> = Complex::zero();
                let mut decimal: Complex<BigRational> = Complex::zero();
                let mut denominator = BigInt::one();

                for digit in &f.parsed.integral.digits {
                    integral *= &ten;
                    integral += Complex::from_u8(*digit).unwrap();
                }

                for digit in &f.parsed.decimal {
                    denominator *= BigInt::from_u8(10).unwrap();
                    decimal *= &ten;
                    decimal += Complex::from_u8(*digit).unwrap();
                }

                Self(integral + decimal)
            }
        }
    }
}

/// 64-bit float. Aliased for potential changes in the future
pub type CompFloat = f64;

/// Rational exponent type. 64-bit numerator and denumerator. Aliased for potential
/// changes in the future.
pub type CompExponent = Rational64;