kalosm_sample/structured_parser/
float.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
use crate::{CreateParserState, ParseStatus, Parser};
use std::ops::RangeInclusive;

#[derive(Debug, PartialEq, Eq, Default, Copy, Clone)]
enum FloatParserProgress {
    #[default]
    Initial,
    AfterSign,
    AfterDigit,
    AfterDecimalPoint {
        digits_after_decimal_point: u32,
    },
}

impl FloatParserProgress {
    fn is_after_digit(&self) -> bool {
        matches!(
            self,
            FloatParserProgress::AfterDigit | FloatParserProgress::AfterDecimalPoint { .. }
        )
    }
}

/// The state of an integer parser.
#[derive(Debug, PartialEq, Copy, Clone)]
pub struct FloatParserState {
    state: FloatParserProgress,
    value: f64,
    positive: bool,
}

impl Default for FloatParserState {
    fn default() -> Self {
        Self {
            state: FloatParserProgress::Initial,
            value: 0.0,
            positive: true,
        }
    }
}

/// A parser for a float.
#[derive(Debug, PartialEq, Clone)]
pub struct FloatParser {
    range: RangeInclusive<f64>,
}

impl FloatParser {
    /// Create a new float parser.
    pub fn new(range: RangeInclusive<f64>) -> Self {
        if range.start() > range.end() {
            Self {
                range: *range.end()..=*range.start(),
            }
        } else {
            Self { range }
        }
    }
}

impl CreateParserState for FloatParser {
    fn create_parser_state(&self) -> <Self as Parser>::PartialState {
        FloatParserState::default()
    }
}

impl FloatParser {
    fn sign_valid(&self, positive: bool) -> bool {
        if positive {
            *self.range.start() >= 0.0
        } else {
            *self.range.end() <= 0.0
        }
    }

    fn is_number_valid(&self, value: f64) -> bool {
        self.range.contains(&value)
    }

    fn could_number_become_valid_before_decimal(
        &self,
        value: f64,
        state: FloatParserProgress,
    ) -> bool {
        if self.is_number_valid(value) {
            true
        } else {
            let num_with_extra_digit = value * 10.;
            if value < 0. {
                if *self.range.start() > num_with_extra_digit {
                    return false;
                }
            } else if *self.range.end() < num_with_extra_digit {
                return false;
            }
            let value_string = value.abs().to_string();
            let start_value_string = self.range.start().abs().to_string();
            let end_value_string = self.range.end().abs().to_string();
            match state {
                FloatParserProgress::AfterDigit | FloatParserProgress::AfterSign => {
                    // Check if the digits are within the range so far
                    let digits = value_string.chars();
                    let start_digits = start_value_string.chars();
                    let end_digits = end_value_string.chars();
                    for (digit, (start_digit, end_digit)) in
                        digits.zip(start_digits.zip(end_digits))
                    {
                        if digit < start_digit || digit > end_digit {
                            return false;
                        }
                    }
                }
                _ => {}
            }
            true
        }
    }

    fn could_number_become_valid_after_decimal(
        &self,
        value: f64,
        digits_after_decimal_point: u32,
    ) -> bool {
        let distance = if value < 0.0 {
            *self.range.start() - value
        } else {
            *self.range.end() - value
        };
        println!("Distance: {}", distance);

        distance < 10.0_f64.powi(-(digits_after_decimal_point as i32))
    }
}

/// An error that can occur while parsing a float literal when the number starts with a leading zero.
#[derive(Debug)]
pub struct LeadingZeroError;

impl std::fmt::Display for LeadingZeroError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Found leading zero. Leading zeros are not allowed when parsing a number"
        )
    }
}

impl std::error::Error for LeadingZeroError {}

/// An error that can occur while parsing a float literal when the number is out of range.
#[derive(Debug)]
pub struct OutOfRangeError;

impl std::fmt::Display for OutOfRangeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Attempted to parse a number that was out of range")
    }
}

impl std::error::Error for OutOfRangeError {}

/// An error that can occur while parsing a float literal when the number contains a decimal point in the wrong place.
#[derive(Debug)]
pub struct InvalidDecimalLocation;

impl std::fmt::Display for InvalidDecimalLocation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Failed to parse a number with a decimal before the first digit or multiple decimals"
        )
    }
}

impl std::error::Error for InvalidDecimalLocation {}

/// An error that can occur while parsing a float literal when the number contains a sign in the wrong place.
#[derive(Debug)]
pub struct InvalidSignLocation;

impl std::fmt::Display for InvalidSignLocation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Failed to parse a number with a sign after the first character"
        )
    }
}

impl std::error::Error for InvalidSignLocation {}

/// An error that can occur while parsing a float literal when trying to parse a number with no characters.
#[derive(Debug)]
pub struct EmptyNumber;

impl std::fmt::Display for EmptyNumber {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Failed to parse a number with no digits")
    }
}

impl std::error::Error for EmptyNumber {}

impl Parser for FloatParser {
    type Output = f64;
    type PartialState = FloatParserState;

    fn parse<'a>(
        &self,
        state: &FloatParserState,
        input: &'a [u8],
    ) -> crate::ParseResult<ParseStatus<'a, Self::PartialState, Self::Output>> {
        let mut value = state.value;
        let mut positive = state.positive;
        let mut state = state.state;

        for index in 0..input.len() {
            let input_byte = input[index];
            let digit = match input_byte {
                b'0'..=b'9' => {
                    if (state == FloatParserProgress::Initial
                        || state == FloatParserProgress::AfterSign)
                        && input_byte == b'0'
                    {
                        crate::bail!(LeadingZeroError);
                    }
                    input_byte - b'0'
                }
                b'.' => {
                    let value_digits = value.abs().log10() + 1.;
                    let start_digits = self.range.start().abs().log10() + 1.;
                    let end_digits = self.range.end().abs().log10() + 1.;
                    if positive {
                        if value_digits > end_digits {
                            crate::bail!(OutOfRangeError);
                        }
                    } else if value_digits > start_digits {
                        crate::bail!(OutOfRangeError);
                    }
                    if state == FloatParserProgress::AfterDigit {
                        state = FloatParserProgress::AfterDecimalPoint {
                            digits_after_decimal_point: 0,
                        };
                        continue;
                    } else {
                        crate::bail!(InvalidDecimalLocation);
                    }
                }
                b'+' | b'-' => {
                    if state == FloatParserProgress::Initial {
                        state = FloatParserProgress::AfterSign;
                        positive = input_byte == b'+';

                        if !self.sign_valid(positive) {
                            crate::bail!(InvalidSignLocation);
                        }
                        continue;
                    } else {
                        crate::bail!(InvalidSignLocation);
                    }
                }
                _ => {
                    if state.is_after_digit() {
                        let result = value * if positive { 1.0 } else { -1.0 };
                        if self.is_number_valid(result) {
                            return Ok(ParseStatus::Finished {
                                result,
                                remaining: &input[index..],
                            });
                        }
                        return Ok(ParseStatus::Finished {
                            result,
                            remaining: &input[index..],
                        });
                    } else {
                        crate::bail!(EmptyNumber)
                    }
                }
            };

            match &mut state {
                FloatParserProgress::Initial => {
                    state = FloatParserProgress::AfterDigit;
                    value = f64::from(digit);
                }
                FloatParserProgress::AfterSign => {
                    state = FloatParserProgress::AfterDigit;
                    value = f64::from(digit);
                }
                FloatParserProgress::AfterDigit => {
                    value = value * 10.0 + f64::from(digit);

                    if !self.could_number_become_valid_before_decimal(
                        value * if positive { 1.0 } else { -1.0 },
                        FloatParserProgress::AfterDigit,
                    ) {
                        crate::bail!(OutOfRangeError);
                    }
                }
                FloatParserProgress::AfterDecimalPoint {
                    digits_after_decimal_point,
                } => {
                    value +=
                        f64::from(digit) / 10.0_f64.powi(*digits_after_decimal_point as i32 + 1);
                    *digits_after_decimal_point += 1;

                    let signed_value = value * if positive { 1.0 } else { -1.0 };
                    if !self.range.contains(&signed_value)
                        && !self.could_number_become_valid_after_decimal(
                            signed_value,
                            *digits_after_decimal_point,
                        )
                    {
                        crate::bail!(OutOfRangeError);
                    }
                }
            }
        }

        Ok(ParseStatus::Incomplete {
            new_state: FloatParserState {
                state,
                value,
                positive,
            },
            required_next: Default::default(),
        })
    }
}

#[test]
fn float_parser() {
    let parser = FloatParser {
        range: -100.0..=200.0,
    };
    let state = FloatParserState::default();
    assert_eq!(
        parser.parse(&state, b"123").unwrap(),
        ParseStatus::Incomplete {
            new_state: FloatParserState {
                state: FloatParserProgress::AfterDigit,
                value: 123.0,
                positive: true
            },
            required_next: Default::default()
        }
    );
    assert_eq!(
        parser.parse(&state, b"123.456").unwrap(),
        ParseStatus::Incomplete {
            new_state: FloatParserState {
                state: FloatParserProgress::AfterDecimalPoint {
                    digits_after_decimal_point: 3
                },
                value: 123.456,
                positive: true
            },
            required_next: Default::default()
        }
    );
    assert_eq!(
        parser
            .parse(
                &parser
                    .parse(&state, b"123.456")
                    .unwrap()
                    .unwrap_incomplete()
                    .0,
                b"789x"
            )
            .unwrap(),
        ParseStatus::Finished {
            result: 123.456789,
            remaining: b"x"
        }
    );
    assert_eq!(
        parser.parse(&state, b"123.456x").unwrap(),
        ParseStatus::Finished {
            result: 123.456,
            remaining: b"x"
        }
    );
    assert!(parser.parse(&state, b"abc").is_err());
}