Skip to main content

sql_values/postgres/
float8.rs

1//! PostgreSQL 18's `double precision`, read as `float8in` reads it, printed as `float8out` prints
2//! it under the default `extra_float_digits` of 1, and ordered as `float8_cmp_internal` orders it.
3
4use 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/// Why `float8in` refuses a text, one variant per message it raises.
14///
15/// ```
16/// use sql_values::postgres::{Float8Error, PgFloat8};
17///
18/// assert_eq!(PgFloat8::parse("1.5x"), Err(Float8Error::InvalidInputSyntax));
19/// assert_eq!(
20///     PgFloat8::parse(" 1e400 ").unwrap_err().to_string(),
21///     "\"1e400\" is out of range for type double precision",
22/// );
23/// ```
24#[derive(Debug, Clone, PartialEq, Eq, Hash, thiserror::Error)]
25pub enum Float8Error {
26    /// Text that is not one number between optional blanks.
27    #[error("invalid input syntax for type double precision")]
28    InvalidInputSyntax,
29    /// A number beyond the finite doubles, or a nonzero one that rounds to zero, naming the
30    /// number as written.
31    #[error("\"{0}\" is out of range for type double precision")]
32    OutOfRange(String),
33}
34
35/// A PostgreSQL `double precision`, equal, ordered and hashed as `float8_cmp_internal` compares
36/// it, with `NaN` equal to itself and above `Infinity`, and `-0` equal to `0`.
37///
38/// Its [`Display`](fmt::Display) is `float8out`, the shortest text that reads back to the same
39/// double, in fixed notation for decimal exponents from -4 to 14 and in exponential notation
40/// otherwise.
41///
42/// ```
43/// use sql_values::postgres::PgFloat8;
44///
45/// let float8 = |text| PgFloat8::parse(text).unwrap();
46/// assert_eq!(float8(" 0.1 ").to_string(), "0.1");
47/// assert_eq!(float8("1e15").to_string(), "1e+15");
48/// assert_eq!(float8("0.00001").to_string(), "1e-05");
49/// assert_eq!(float8("-inf").to_string(), "-Infinity");
50/// assert_eq!(float8("0x1.8p1").value(), 3.0);
51/// assert_eq!(float8("-0"), float8("0"));
52/// assert!(float8("NaN") > float8("Infinity"));
53/// assert_eq!(PgFloat8::from(2.5).to_string(), "2.5");
54///
55/// let distinct: std::collections::HashSet<_> =
56///     ["0", "-0", "1", "1.0", "NaN", "-nan"].map(|text| float8(text)).into_iter().collect();
57/// assert_eq!(distinct.len(), 3);
58/// ```
59#[derive(Debug, Clone, Copy)]
60pub struct PgFloat8(f64);
61
62impl PgFloat8 {
63    /// Read `text` as `float8in` reads it, C's `strtod` between blanks, refusing a nonzero number
64    /// that rounds to zero and one beyond the finite doubles.
65    ///
66    /// # Errors
67    ///
68    /// The [`Float8Error`] whose message PostgreSQL raises for `text`.
69    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    /// The double.
88    #[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
123/// The decimal `float8out` prints for a positive finite nonzero `value`, as digits and the power
124/// of ten of the last. PostgreSQL's Ryu takes the fewest digits strictly between the midpoints to
125/// the neighbouring doubles, never a midpoint itself, and among those the one nearest `value`
126/// (ties to even). The fewest digits never end in a zero, which a shorter spelling would drop.
127fn shortest(value: f64) -> (u64, i32) {
128    // Rust's shortest form also accepts a midpoint, so no spelling with fewer digits exists.
129    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
139/// `value` as Rust spells it in exponential notation, the shortest form that reads back when
140/// `count` is `None`, else rounded to `count` significant digits with ties to even, as digits
141/// and the power of ten of the last.
142fn 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
166/// The `count`-digit decimal one unit above `(digits, last_power)`.
167fn 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
175/// The `count`-digit decimal one unit below `(digits, last_power)`.
176fn 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
184/// Whether the decimal reads back to `value` without lying on a midpoint to a neighbour.
185fn 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    // `value` is `significand * 2^power`, and a midpoint is an odd multiple of a lower power.
193    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    // The gap below a power of two is half the gap above it.
201    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
211/// Whether `digits * 10^last_power` equals `odd * 2^power`, comparing the parts of each that
212/// are prime to ten and their powers of two and of five.
213fn 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
219/// `value` as `rest * 2^twos * 5^fives` with `rest` prime to ten.
220fn 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/// ASCII text of at most 32 bytes, room for any decimal this module writes.
234#[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
256/// `to_chars`, `digits` with the first at power `exponent` of ten, in fixed notation for
257/// exponents from -4 to 14 as `printf` chooses, else as `d.ddde±XX`.
258fn 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        // Equal values hash alike: every NaN as one, and `-0` as `0`.
319        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}