1use alloc::string::String;
5use core::{
6 cmp::Ordering,
7 fmt,
8 hash::{Hash, Hasher},
9};
10
11use super::{cast::is_pg_space, interval::strtod};
12
13#[derive(Debug, Clone, PartialEq, Eq, Hash, thiserror::Error)]
25pub enum Float8Error {
26 #[error("invalid input syntax for type double precision")]
28 InvalidInputSyntax,
29 #[error("\"{0}\" is out of range for type double precision")]
32 OutOfRange(String),
33}
34
35#[derive(Debug, Clone, Copy)]
60pub struct PgFloat8(f64);
61
62impl PgFloat8 {
63 pub fn parse(text: &str) -> Result<Self, Float8Error> {
70 let bytes = text.as_bytes();
71 let start = bytes.iter().take_while(|&&byte| is_pg_space(byte)).count();
72 let sign = usize::from(bytes.get(start) == Some(&b'+'));
73 if sign == 1 && bytes.get(start + 1) == Some(&b'-') {
74 return Err(Float8Error::InvalidInputSyntax);
75 }
76 let (value, end, out_of_range) =
77 strtod(bytes, start + sign).ok_or(Float8Error::InvalidInputSyntax)?;
78 if out_of_range && (value == 0.0 || value.is_infinite()) {
79 return Err(Float8Error::OutOfRange(String::from(&text[start..end])));
80 }
81 if !bytes[end..].iter().all(|&byte| is_pg_space(byte)) {
82 return Err(Float8Error::InvalidInputSyntax);
83 }
84 Ok(Self(value))
85 }
86
87 #[must_use]
89 pub const fn value(self) -> f64 {
90 self.0
91 }
92}
93
94impl From<f64> for PgFloat8 {
95 fn from(value: f64) -> Self {
96 Self(value)
97 }
98}
99
100impl fmt::Display for PgFloat8 {
101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102 let value = self.0;
103 if value.is_nan() {
104 return f.write_str("NaN");
105 }
106 if value.is_sign_negative() {
107 f.write_str("-")?;
108 }
109 if value.is_infinite() {
110 return f.write_str("Infinity");
111 }
112 if value == 0.0 {
113 return f.write_str("0");
114 }
115 let (digits, last_power) = shortest(value.abs());
116 let mut text = StackText::default();
117 fmt::Write::write_fmt(&mut text, format_args!("{digits}"))?;
118 let length = i32::try_from(text.length).expect("a u64 has at most 20 digits");
119 write_decimal(f, text.as_str(), last_power + length - 1)
120 }
121}
122
123fn shortest(value: f64) -> (u64, i32) {
128 let fewest = decimal(value, None).0.ilog10() + 1;
130 let found = (fewest..=17).find_map(|count| {
131 let nearest = decimal(value, Some(count));
132 [nearest, next(nearest, count), previous(nearest, count)]
133 .into_iter()
134 .find(|&candidate| strictly_between_midpoints(value, candidate))
135 });
136 found.expect("17 digits always fit strictly between the midpoints")
137}
138
139fn decimal(value: f64, count: Option<u32>) -> (u64, i32) {
143 let mut text = StackText::default();
144 let written = match count {
145 Some(count) => {
146 let fraction = usize::try_from(count - 1).expect("at most 16 fraction digits");
147 fmt::Write::write_fmt(&mut text, format_args!("{value:.fraction$e}"))
148 }
149 None => fmt::Write::write_fmt(&mut text, format_args!("{value:e}")),
150 };
151 written.expect("a double's exponential form fits 32 bytes");
152 let (significand, exponent) = text
153 .as_str()
154 .split_once('e')
155 .expect("an exponent is written");
156 let exponent: i32 = exponent.parse().expect("the exponent is an integer");
157 let (mut digits, mut fraction_digits) = (0_u64, 0);
158 for (index, digit) in significand.bytes().filter(u8::is_ascii_digit).enumerate() {
159 digits = digits * 10 + u64::from(digit - b'0');
160 fraction_digits = index;
161 }
162 let fraction_digits = i32::try_from(fraction_digits).expect("at most 16 fraction digits");
163 (digits, exponent - fraction_digits)
164}
165
166fn next((digits, last_power): (u64, i32), count: u32) -> (u64, i32) {
168 if digits + 1 == 10_u64.pow(count) {
169 (10_u64.pow(count - 1), last_power + 1)
170 } else {
171 (digits + 1, last_power)
172 }
173}
174
175fn previous((digits, last_power): (u64, i32), count: u32) -> (u64, i32) {
177 if digits == 10_u64.pow(count - 1) {
178 (10_u64.pow(count) - 1, last_power - 1)
179 } else {
180 (digits - 1, last_power)
181 }
182}
183
184fn strictly_between_midpoints(value: f64, (digits, last_power): (u64, i32)) -> bool {
186 let mut text = StackText::default();
187 fmt::Write::write_fmt(&mut text, format_args!("{digits}e{last_power}"))
188 .expect("a decimal of at most 17 digits fits 32 bytes");
189 let reads_back = text.as_str().parse::<f64>() == Ok(value);
190 let bits = value.to_bits();
191 let (fraction, biased) = (bits & ((1 << 52) - 1), (bits >> 52) & 0x7ff);
192 let (significand, power) = if biased == 0 {
194 (fraction, -1074)
195 } else {
196 let biased = i32::try_from(biased).expect("an 11-bit exponent");
197 (fraction | 1 << 52, biased - 1075)
198 };
199 let above = (2 * significand + 1, power - 1);
200 let below = if fraction == 0 && biased > 1 {
202 (4 * significand - 1, power - 2)
203 } else {
204 (2 * significand - 1, power - 1)
205 };
206 reads_back
207 && !equals_dyadic((digits, last_power), above)
208 && !equals_dyadic((digits, last_power), below)
209}
210
211fn equals_dyadic((digits, last_power): (u64, i32), (odd, power): (u64, i32)) -> bool {
214 let (digits, twos, digit_fives) = split_two_five(digits);
215 let (odd, _, odd_fives) = split_two_five(odd);
216 digits == odd && twos + last_power == power && digit_fives + last_power == odd_fives
217}
218
219fn split_two_five(mut value: u64) -> (u64, i32, i32) {
221 let (mut twos, mut fives) = (0, 0);
222 while value.is_multiple_of(2) {
223 value /= 2;
224 twos += 1;
225 }
226 while value.is_multiple_of(5) {
227 value /= 5;
228 fives += 1;
229 }
230 (value, twos, fives)
231}
232
233#[derive(Default)]
235struct StackText {
236 bytes: [u8; 32],
237 length: usize,
238}
239
240impl StackText {
241 fn as_str(&self) -> &str {
242 core::str::from_utf8(&self.bytes[..self.length]).expect("only ASCII is written")
243 }
244}
245
246impl fmt::Write for StackText {
247 fn write_str(&mut self, text: &str) -> fmt::Result {
248 let end = self.length + text.len();
249 let slot = self.bytes.get_mut(self.length..end).ok_or(fmt::Error)?;
250 slot.copy_from_slice(text.as_bytes());
251 self.length = end;
252 Ok(())
253 }
254}
255
256fn write_decimal(f: &mut fmt::Formatter<'_>, digits: &str, exponent: i32) -> fmt::Result {
259 let length = i32::try_from(digits.len()).expect("a double has at most 17 digits");
260 if !(-4..15).contains(&exponent) {
261 let (first, rest) = digits.split_at(1);
262 f.write_str(first)?;
263 if !rest.is_empty() {
264 write!(f, ".{rest}")?;
265 }
266 let sign = if exponent < 0 { '-' } else { '+' };
267 return write!(f, "e{sign}{:02}", exponent.unsigned_abs());
268 }
269 if exponent < 0 {
270 f.write_str("0.")?;
271 for _ in 0..(-exponent - 1) {
272 f.write_str("0")?;
273 }
274 return f.write_str(digits);
275 }
276 if exponent >= length - 1 {
277 f.write_str(digits)?;
278 for _ in 0..(exponent - length + 1) {
279 f.write_str("0")?;
280 }
281 return Ok(());
282 }
283 let point = usize::try_from(exponent + 1).expect("the exponent is nonnegative here");
284 let (whole, fraction) = digits.split_at(point);
285 write!(f, "{whole}.{fraction}")
286}
287
288impl PartialEq for PgFloat8 {
289 fn eq(&self, other: &Self) -> bool {
290 self.cmp(other) == Ordering::Equal
291 }
292}
293
294impl Eq for PgFloat8 {}
295
296impl PartialOrd for PgFloat8 {
297 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
298 Some(self.cmp(other))
299 }
300}
301
302impl Ord for PgFloat8 {
303 fn cmp(&self, other: &Self) -> Ordering {
304 match (self.0.is_nan(), other.0.is_nan()) {
305 (true, true) => Ordering::Equal,
306 (true, false) => Ordering::Greater,
307 (false, true) => Ordering::Less,
308 (false, false) => self
309 .0
310 .partial_cmp(&other.0)
311 .expect("two doubles that are not NaN are ordered"),
312 }
313 }
314}
315
316impl Hash for PgFloat8 {
317 fn hash<H: Hasher>(&self, state: &mut H) {
318 let canonical = if self.0.is_nan() {
320 f64::NAN
321 } else if self.0 == 0.0 {
322 0.0
323 } else {
324 self.0
325 };
326 canonical.to_bits().hash(state);
327 }
328}