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
#![deny(unsafe_code)]
#![deny(missing_docs)]
#![warn(clippy::dbg_macro)]
use std::{fmt, error};
mod parse_utils;
use parse_utils::*;
mod fpformat;
pub use fpformat::FPFormat;
#[derive(Debug)]
pub enum ConversionResult<T> {
Precise(T),
Imprecise(T),
}
impl<T> ConversionResult<T> {
pub fn inner(self) -> T {
match self {
ConversionResult::Precise(f) => f,
ConversionResult::Imprecise(f) => f,
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ParseError {
MissingPrefix,
MissingDigits,
MissingExponent,
ExponentOverflow,
ExtraData,
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ParseError::MissingPrefix => write!(f, "literal must have hex prefix"),
ParseError::MissingDigits => write!(f, "literal must have digits"),
ParseError::MissingExponent => write!(f, "exponent not present"),
ParseError::ExponentOverflow => write!(f, "exponent too large to fit in integer"),
ParseError::ExtraData => {
write!(f, "extra bytes were found at the end of float literal")
}
}
}
}
impl From<std::num::ParseIntError> for ParseError {
fn from(_error: std::num::ParseIntError) -> ParseError {
ParseError::ExponentOverflow
}
}
impl error::Error for ParseError {}
#[derive(Debug, Clone)]
pub struct FloatLiteral {
is_positive: bool,
digits: Vec<u8>,
decimal_offset: i32,
exponent: i32,
}
impl FloatLiteral {
pub fn convert<F: FPFormat>(self) -> ConversionResult<F> {
F::from_literal(self)
}
pub fn from_bytes(data: &[u8]) -> Result<FloatLiteral, ParseError> {
let (is_positive, data) = match data.get(0) {
Some(b'+') => (true, &data[1..]),
Some(b'-') => (false, &data[1..]),
_ => (true, data),
};
let data = match data.get(0..2) {
Some(b"0X") | Some(b"0x") => &data[2..],
_ => return Err(ParseError::MissingPrefix),
};
let (ipart, data) = consume_hex_digits(data);
let (fpart, data): (&[_], _) = if data.get(0) == Some(&b'.') {
let (fpart, data) = consume_hex_digits(&data[1..]);
(fpart, data)
} else {
(b"", data)
};
if fpart.is_empty() && ipart.is_empty() {
return Err(ParseError::MissingDigits);
}
let (exponent, data) = match data.get(0) {
Some(b'P') | Some(b'p') => {
let data = &data[1..];
let sign_offset = match data.get(0) {
Some(b'+') | Some(b'-') => 1,
_ => 0,
};
let exponent_digits_offset = data[sign_offset..]
.iter()
.position(|&b| match b {
b'0'..=b'9' => false,
_ => true,
})
.unwrap_or_else(|| data[sign_offset..].len());
if exponent_digits_offset == 0 {
return Err(ParseError::MissingExponent);
}
let exponent: i32 =
std::str::from_utf8(&data[..sign_offset + exponent_digits_offset])
.expect("exponent did not contain valid utf-8")
.parse()?;
(exponent, &data[sign_offset + exponent_digits_offset..])
}
_ => (0, data),
};
if !data.is_empty() {
return Err(ParseError::ExtraData);
}
let mut raw_digits = ipart.to_vec();
raw_digits.extend_from_slice(fpart);
let first_digit = raw_digits.iter().position(|&d| d != b'0');
let (digits, decimal_offset) = if let Some(first_digit) = first_digit {
let last_digit = raw_digits.iter().rposition(|&d| d != b'0').unwrap();
let decimal_offset = (ipart.len() as i32) - (first_digit as i32);
raw_digits.truncate(last_digit + 1);
raw_digits.drain(..first_digit);
for item in raw_digits.iter_mut() {
*item = hex_digit_to_int(*item).unwrap();
}
(raw_digits, decimal_offset)
} else {
(Vec::new(), 0)
};
Ok(FloatLiteral {
is_positive,
digits,
decimal_offset,
exponent,
})
}
}
impl std::str::FromStr for FloatLiteral {
type Err = ParseError;
fn from_str(s: &str) -> Result<FloatLiteral, ParseError> {
FloatLiteral::from_bytes(s.as_bytes())
}
}
impl Into<f32> for FloatLiteral {
fn into(self) -> f32 {
self.convert().inner()
}
}
impl Into<f64> for FloatLiteral {
fn into(self) -> f64 {
self.convert().inner()
}
}
#[cfg(test)]
mod tests;