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
use std::{fmt::Display, mem};

use num_rational::Rational64;
use num_traits::{CheckedAdd, CheckedMul, FromPrimitive, ToPrimitive, Zero};

#[derive(Debug)]
pub struct ParseIntError;

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
/// Unsigned integer for parsing
pub struct ParsedInt {
    digits: Vec<u8>,
}

impl ParsedInt {
    /// # 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())
    }

    #[must_use]
    pub fn is_zero(&self) -> bool {
        self.digits[0] == 0
    }

    #[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 std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}",
            self.digits
                .iter()
                .map(ToString::to_string)
                .collect::<String>()
        )
    }
}

#[derive(Debug, Default)]
pub struct ParsedIntBuilder {
    digits: Vec<u8>,
}

impl ParsedIntBuilder {
    #[must_use]
    pub fn new() -> Self {
        Self { digits: Vec::new() }
    }

    pub fn push_digit(&mut self, digit: u8) {
        self.digits.push(digit);
    }

    #[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 integer for parsing.
pub struct ParsedFloat {
    integral: ParsedInt,
    decimal: Vec<u8>,
}

impl ParsedFloat {
    /// # 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))
                })
    }

    #[must_use]
    pub fn is_zero(&self) -> bool {
        self.integral.is_zero() && self.decimal.is_empty()
    }

    #[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 std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}.{}",
            self.integral,
            self.decimal
                .iter()
                .map(ToString::to_string)
                .collect::<String>()
        )
    }
}

#[derive(Debug)]
pub struct ParsedFloatBuilder {
    integral: ParsedInt,
    digits: Vec<u8>,
}

impl ParsedFloatBuilder {
    pub fn push_digit(&mut self, digit: u8) {
        self.digits.push(digit);
    }

    #[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,
        }
    }
}

/// Number for computing
pub type CompFloat = f64;

/// Exponent type
pub type CompExponent = Rational64;