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
use std::num;

/// The default limit when parsing via [`ParseNumber`].
pub const MAX_PARSE_VALUE: i32 = i32::MAX;

/// Parses a `&str` to a number and makes sure it doesn't exceed a limit.
pub trait ParseNumber: Sized {
    /// Parses a number without exceeding [`MAX_PARSE_VALUE`].
    fn parse(s: &str) -> Result<Self, ParseNumberError>;

    /// Parses a number without exceeding the given limit.
    fn parse_with_limits(s: &str, limit: Self) -> Result<Self, ParseNumberError>;
}

thiserror! {
    /// All the ways that parsing with [`ParseNumber`] can fail.
    #[derive(Debug)]
    pub enum ParseNumberError {
        #[error("invalid float")]
        InvalidFloat(#[from] num::ParseFloatError),
        #[error("invalid integer")]
        InvalidInteger(#[from] num::ParseIntError),
        #[error("not a number")]
        NaN,
        #[error("value is too high")]
        NumberOverflow,
        #[error("value is too low")]
        NumberUnderflow,
    }
}

impl ParseNumber for i32 {
    fn parse(s: &str) -> Result<Self, ParseNumberError> {
        Self::parse_with_limits(s, MAX_PARSE_VALUE)
    }

    fn parse_with_limits(s: &str, limit: Self) -> Result<Self, ParseNumberError> {
        let n: Self = s.trim().parse()?;

        if n < -limit {
            Err(ParseNumberError::NumberUnderflow)
        } else if n > limit {
            Err(ParseNumberError::NumberOverflow)
        } else {
            Ok(n)
        }
    }
}

impl ParseNumber for f32 {
    fn parse(s: &str) -> Result<Self, ParseNumberError> {
        Self::parse_with_limits(s, MAX_PARSE_VALUE as Self)
    }

    fn parse_with_limits(s: &str, limit: Self) -> Result<Self, ParseNumberError> {
        let n: Self = s.trim().parse()?;

        if n < -limit {
            Err(ParseNumberError::NumberUnderflow)
        } else if n > limit {
            Err(ParseNumberError::NumberOverflow)
        } else if n.is_nan() {
            Err(ParseNumberError::NaN)
        } else {
            Ok(n)
        }
    }
}

impl ParseNumber for f64 {
    fn parse(s: &str) -> Result<Self, ParseNumberError> {
        Self::parse_with_limits(s, Self::from(MAX_PARSE_VALUE))
    }

    fn parse_with_limits(s: &str, limit: Self) -> Result<Self, ParseNumberError> {
        let n: Self = s.trim().parse()?;

        if n < -limit {
            Err(ParseNumberError::NumberUnderflow)
        } else if n > limit {
            Err(ParseNumberError::NumberOverflow)
        } else if n.is_nan() {
            Err(ParseNumberError::NaN)
        } else {
            Ok(n)
        }
    }
}