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
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).

use core::fmt;
use core::str::FromStr;

use crate::FixedDecimal;
use crate::FixedInteger;
use crate::ParseError;

/// A struct containing a [`FixedDecimal`] significand together with an exponent, representing a
/// number written in scientific notation, such as 1.729×10³.
///
/// This structure represents any 0s shown in the significand and exponent,
/// and an optional sign for both the significand and the exponent.
#[derive(Debug, Clone, PartialEq)]
pub struct ScientificDecimal {
    significand: FixedDecimal,
    exponent: FixedInteger,
}

impl ScientificDecimal {
    pub fn from(significand: FixedDecimal, exponent: FixedInteger) -> Self {
        ScientificDecimal {
            significand,
            exponent,
        }
    }
}

/// Render the [`ScientificDecimal`] as a string of ASCII digits with a possible decimal point,
/// followed by the letter 'e', and the exponent.
///
/// # Examples
///
/// ```
/// # use fixed_decimal::FixedDecimal;
/// # use fixed_decimal::FixedInteger;
/// # use fixed_decimal::ScientificDecimal;
/// # use std::str::FromStr;
/// # use writeable::assert_writeable_eq;
/// #
/// assert_writeable_eq!(
///     ScientificDecimal::from(
///         FixedDecimal::from(1729).multiplied_pow10(-3),
///         FixedInteger::from(3)
///     ),
///     "1.729e3"
/// );
/// assert_writeable_eq!(
///     ScientificDecimal::from(
///         FixedDecimal::from_str("+1.729").unwrap(),
///         FixedInteger::from_str("+03").unwrap()
///     ),
///     "+1.729e+03"
/// );
/// ```
impl writeable::Writeable for ScientificDecimal {
    fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
        self.significand.write_to(sink)?;
        sink.write_char('e')?;
        self.exponent.write_to(sink)
    }

    fn writeable_length_hint(&self) -> writeable::LengthHint {
        self.significand.writeable_length_hint() + 1 + self.exponent.writeable_length_hint()
    }
}

writeable::impl_display_with_writeable!(ScientificDecimal);

impl ScientificDecimal {
    #[inline]
    pub fn try_from_str(s: &str) -> Result<Self, ParseError> {
        Self::try_from_utf8(s.as_bytes())
    }

    pub fn try_from_utf8(code_units: &[u8]) -> Result<Self, ParseError> {
        // Fixed_Decimal::try_from supports scientific notation; ensure that
        // we don’t accept something like 1e1E1.  Splitting on 'e' ensures that
        // we disallow 1e1e1.
        if code_units.contains(&b'E') {
            return Err(ParseError::Syntax);
        }
        let mut parts = code_units.split(|&c| c == b'e');
        let significand = parts.next().ok_or(ParseError::Syntax)?;
        let exponent = parts.next().ok_or(ParseError::Syntax)?;
        if parts.next().is_some() {
            return Err(ParseError::Syntax);
        }
        Ok(ScientificDecimal::from(
            FixedDecimal::try_from_utf8(significand)?,
            FixedInteger::try_from_utf8(exponent)?,
        ))
    }
}

impl FromStr for ScientificDecimal {
    type Err = ParseError;
    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::try_from_str(s)
    }
}

#[test]
fn test_scientific_syntax_error() {
    #[derive(Debug)]
    struct TestCase {
        pub input_str: &'static str,
        pub expected_err: Option<ParseError>,
    }
    let cases = [
        TestCase {
            input_str: "5",
            expected_err: Some(ParseError::Syntax),
        },
        TestCase {
            input_str: "-123c4",
            expected_err: Some(ParseError::Syntax),
        },
        TestCase {
            input_str: "-123e",
            expected_err: Some(ParseError::Syntax),
        },
        TestCase {
            input_str: "1e10",
            expected_err: None,
        },
        TestCase {
            input_str: "1e1e1",
            expected_err: Some(ParseError::Syntax),
        },
        TestCase {
            input_str: "1e1E1",
            expected_err: Some(ParseError::Syntax),
        },
        TestCase {
            input_str: "1E1e1",
            expected_err: Some(ParseError::Syntax),
        },
        TestCase {
            input_str: "-1e+01",
            expected_err: None,
        },
        TestCase {
            input_str: "-1e+1.0",
            expected_err: Some(ParseError::Limit),
        },
        TestCase {
            input_str: "-1e+-1",
            expected_err: Some(ParseError::Syntax),
        },
        TestCase {
            input_str: "123E4",
            expected_err: Some(ParseError::Syntax),
        },
    ];
    for cas in &cases {
        match ScientificDecimal::from_str(cas.input_str) {
            Ok(dec) => {
                assert_eq!(cas.expected_err, None, "{cas:?}");
                assert_eq!(cas.input_str, dec.to_string(), "{cas:?}");
            }
            Err(err) => {
                assert_eq!(cas.expected_err, Some(err), "{cas:?}");
            }
        }
    }
}