sql-values 0.4.0

SQL values, with PostgreSQL's value rules beside readers of the text PostgreSQL, MySQL and SQLite emit
Documentation
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! PostgreSQL `numeric` values as `numeric_in` reads them, `numeric_out` prints them,
//! `cmp_numerics` orders them and the `numeric()` length coercion rounds them.

use alloc::vec::Vec;
use core::{
    cmp::Ordering,
    fmt,
    hash::{Hash, Hasher},
};

use crate::cast::{CastError, PgType, is_pg_space};

/// `NUMERIC_DSCALE_MAX`, the most digits after the point PostgreSQL stores.
const MAX_DSCALE: i64 = 0x3FFF;
/// The decimal weight of the leading digit past which PostgreSQL's base-10000 weight leaves
/// `int16`, `(32767 + 1) * 4 - 1`.
const MAX_WEIGHT: i64 = 131_071;
/// `PG_INT32_MAX / 2`, the exponent `set_var_from_str` refuses beyond.
const MAX_EXPONENT: i64 = 1_073_741_823;
/// `NUMERIC_MAX_PRECISION`.
const MAX_PRECISION: u16 = 1000;
/// `NUMERIC_MIN_SCALE` and `NUMERIC_MAX_SCALE`.
const SCALE_RANGE: core::ops::RangeInclusive<i16> = -1000..=1000;

/// A PostgreSQL `numeric`, equal, ordered and hashed by value as `cmp_numerics` compares it, with
/// `NaN` equal to itself and above `Infinity`.
///
/// Its [`Display`](fmt::Display) is `numeric_out`, so equal values can print differently.
///
/// ```
/// use sql_values::{CastTarget, CastValue, Literal, cast_literal};
///
/// let numeric = |text| match cast_literal(Literal::Quoted(text), CastTarget::Numeric(None)) {
///     Ok(CastValue::Numeric(value)) => value,
///     other => panic!("{other:?}"),
/// };
/// assert_eq!(numeric("1.50"), numeric("1.5"));
/// assert_eq!(numeric("1.50").to_string(), "1.50");
/// assert!(numeric("NaN") > numeric("Infinity"));
/// assert!(numeric("-inf") < numeric("-1e1000"));
/// ```
#[derive(Debug, Clone)]
pub struct PgNumeric(Repr);

#[derive(Debug, Clone)]
enum Repr {
    NaN,
    Infinity { negative: bool },
    Finite(Finite),
}

/// A finite value as decimal digits, normalised so that equal values have equal fields except
/// `dscale`.
#[derive(Debug, Clone)]
struct Finite {
    /// Never set for zero.
    negative: bool,
    /// Digits `0..=9` with no leading or trailing zero, empty for zero.
    digits: Vec<u8>,
    /// The power of ten of `digits[0]`, `0` for zero.
    weight: i64,
    /// The digits printed after the point, never fewer than the value has.
    dscale: i64,
}

/// The modifier of a `numeric(p, s)` type, the precision and scale it rounds to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct NumericTypmod {
    precision: u16,
    scale: i16,
}

impl NumericTypmod {
    /// `numerictypmodin`, or `None` for a precision outside `1..=1000` or a scale outside
    /// `-1000..=1000`. `numeric(p)` is a scale of `0`.
    ///
    /// ```
    /// use sql_values::NumericTypmod;
    ///
    /// assert!(NumericTypmod::new(4, 1).is_some());
    /// assert!(NumericTypmod::new(2, -3).is_some());
    /// assert!(NumericTypmod::new(0, 0).is_none());
    /// assert!(NumericTypmod::new(1001, 0).is_none());
    /// ```
    #[must_use]
    pub fn new(precision: u16, scale: i16) -> Option<Self> {
        ((1..=MAX_PRECISION).contains(&precision) && SCALE_RANGE.contains(&scale))
            .then_some(Self { precision, scale })
    }
}

impl PgNumeric {
    /// `numeric_in` with no type modifier, as an unknown literal is read before its cast.
    pub(crate) fn parse(text: &str) -> Result<Self, CastError> {
        let syntax = CastError::InvalidInputSyntax(PgType::Numeric);
        let bytes = text.as_bytes();
        let start = bytes.iter().take_while(|&&b| is_pg_space(b)).count();
        let signed = &bytes[start..];
        let (negative, unsigned) = match signed.split_first() {
            Some((b'-', rest)) => (true, rest),
            Some((b'+', rest)) => (false, rest),
            _ => (false, signed),
        };
        let (value, rest) = match unsigned.first() {
            Some(b'0'..=b'9' | b'.') => {
                let (base, digits) = match unsigned {
                    [b'0', b'x' | b'X', digits @ ..] => (16, digits),
                    [b'0', b'o' | b'O', digits @ ..] => (8, digits),
                    [b'0', b'b' | b'B', digits @ ..] => (2, digits),
                    _ => (10, unsigned),
                };
                let (mut finite, rest) = if base == 10 {
                    parse_decimal(digits)?
                } else {
                    parse_non_decimal(digits, base)?
                };
                finite.negative = negative && !finite.digits.is_empty();
                (Repr::Finite(finite), rest)
            }
            _ => {
                if starts_with_ignore_case(signed, b"NaN") {
                    (Repr::NaN, &signed[3..])
                } else if starts_with_ignore_case(unsigned, b"Infinity") {
                    (Repr::Infinity { negative }, &unsigned[8..])
                } else if starts_with_ignore_case(unsigned, b"inf") {
                    (Repr::Infinity { negative }, &unsigned[3..])
                } else {
                    return Err(syntax);
                }
            }
        };
        if !rest.iter().all(|&b| is_pg_space(b)) {
            return Err(syntax);
        }
        if let Repr::Finite(finite) = &value {
            finite.check_storable()?;
        }
        Ok(Self(value))
    }

    /// `int8_numeric`.
    pub(crate) fn from_i64(value: i64) -> Self {
        let mut digits = Vec::new();
        let mut rest = value.unsigned_abs();
        while rest > 0 {
            // A remainder of ten is below `u8::MAX`.
            digits.push(u8::try_from(rest % 10).expect("a decimal digit fits u8"));
            rest /= 10;
        }
        digits.reverse();
        let weight = i64::try_from(digits.len()).expect("an i64 has 19 digits") - 1;
        let mut finite = Finite {
            negative: value < 0,
            digits,
            weight,
            dscale: 0,
        };
        finite.normalise();
        Self(Repr::Finite(finite))
    }

    /// The `numeric()` length coercion to `typmod`, rounding half away from zero.
    pub(crate) fn apply_typmod(self, typmod: NumericTypmod) -> Result<Self, CastError> {
        match self.0 {
            Repr::NaN => Ok(self),
            Repr::Infinity { .. } => Err(CastError::NumericFieldOverflow),
            Repr::Finite(mut finite) => {
                let scale = i64::from(typmod.scale);
                finite.round(scale);
                let integer_digits = i64::from(typmod.precision) - scale;
                if !finite.digits.is_empty() && finite.weight + 1 > integer_digits {
                    return Err(CastError::NumericFieldOverflow);
                }
                Ok(Self(Repr::Finite(finite)))
            }
        }
    }

    /// `numericvar_to_int64`, the value rounded half away from zero, or `None` for a value
    /// beyond `i64` or not finite.
    pub(crate) fn into_i64_rounded(self) -> Option<i64> {
        let Repr::Finite(mut rounded) = self.0 else {
            return None;
        };
        rounded.round(0);
        if rounded.weight >= 19 {
            return None;
        }
        let magnitude = (0..=rounded.weight).rev().fold(0i128, |magnitude, power| {
            magnitude * 10 + i128::from(rounded.digit_at(power))
        });
        i64::try_from(if rounded.negative {
            -magnitude
        } else {
            magnitude
        })
        .ok()
    }

    /// The order class of the value, rising from `-Infinity` through negative, zero, positive and
    /// `Infinity` to `NaN`.
    fn class(&self) -> i8 {
        match &self.0 {
            Repr::Infinity { negative: true } => -2,
            Repr::Finite(finite) if finite.digits.is_empty() => 0,
            Repr::Finite(finite) if finite.negative => -1,
            Repr::Finite(_) => 1,
            Repr::Infinity { negative: false } => 2,
            Repr::NaN => 3,
        }
    }
}

impl Finite {
    /// Drop leading and trailing zero digits, giving zero its unsigned form.
    fn normalise(&mut self) {
        let leading = self.digits.iter().take_while(|&&d| d == 0).count();
        self.digits.drain(..leading);
        self.weight -= i64::try_from(leading).expect("a digit count fits i64");
        let kept = self
            .digits
            .iter()
            .rposition(|&d| d != 0)
            .map_or(0, |last| last + 1);
        self.digits.truncate(kept);
        if self.digits.is_empty() {
            self.negative = false;
            self.weight = 0;
        }
    }

    /// The digit at `power` of ten.
    fn digit_at(&self, power: i64) -> u8 {
        usize::try_from(self.weight - power)
            .ok()
            .and_then(|index| self.digits.get(index).copied())
            .unwrap_or(0)
    }

    /// `round_var` to `scale` digits after the point, then `apply_typmod`'s non-negative display
    /// scale.
    fn round(&mut self, scale: i64) {
        self.dscale = scale.max(0);
        let kept = self.weight + scale + 1;
        let Ok(kept) = usize::try_from(kept) else {
            *self = Self::zero(self.dscale);
            return;
        };
        if kept >= self.digits.len() {
            return;
        }
        let round_up = self.digits[kept] >= 5;
        self.digits.truncate(kept);
        if round_up {
            let carried = self.digits.iter_mut().rev().try_for_each(|digit| {
                if *digit == 9 {
                    *digit = 0;
                    Ok(())
                } else {
                    *digit += 1;
                    Err(())
                }
            });
            if carried.is_ok() {
                self.digits.insert(0, 1);
                self.weight += 1;
            }
        }
        self.normalise();
    }

    const fn zero(dscale: i64) -> Self {
        Self {
            negative: false,
            digits: Vec::new(),
            weight: 0,
            dscale,
        }
    }

    /// `make_result`'s check that the weight and display scale fit their stored fields.
    fn check_storable(&self) -> Result<(), CastError> {
        let weight_fits = self.digits.is_empty() || self.weight <= MAX_WEIGHT;
        if weight_fits && self.dscale <= MAX_DSCALE {
            Ok(())
        } else {
            Err(CastError::NumericFormatOverflow)
        }
    }

    /// The magnitude order of two values of the same sign.
    fn cmp_magnitude(&self, other: &Self) -> Ordering {
        self.weight
            .cmp(&other.weight)
            .then_with(|| self.digits.cmp(&other.digits))
    }
}

/// `set_var_from_str` from the first digit or point, returning the value and the unread rest.
fn parse_decimal(bytes: &[u8]) -> Result<(Finite, &[u8]), CastError> {
    let syntax = CastError::InvalidInputSyntax(PgType::Numeric);
    let mut digits = Vec::new();
    let mut integer_digits: i64 = 0;
    let mut dscale: i64 = 0;
    let mut have_point = false;
    let mut at = 0;
    if bytes.first() == Some(&b'.') {
        have_point = true;
        at = 1;
    }
    if !bytes.get(at).is_some_and(u8::is_ascii_digit) {
        return Err(syntax);
    }
    while let Some(&byte) = bytes.get(at) {
        match byte {
            b'0'..=b'9' => {
                digits.push(byte - b'0');
                if have_point {
                    dscale += 1;
                } else {
                    integer_digits += 1;
                }
                at += 1;
            }
            b'.' if have_point => return Err(syntax),
            b'.' => {
                have_point = true;
                at += 1;
                if bytes.get(at) == Some(&b'_') {
                    return Err(syntax);
                }
            }
            b'_' => {
                at += 1;
                if !bytes.get(at).is_some_and(u8::is_ascii_digit) {
                    return Err(syntax);
                }
            }
            _ => break,
        }
    }
    let mut weight = integer_digits - 1;
    if matches!(bytes.get(at), Some(b'e' | b'E')) {
        at += 1;
        let negative = match bytes.get(at) {
            Some(b'+') => {
                at += 1;
                false
            }
            Some(b'-') => {
                at += 1;
                true
            }
            _ => false,
        };
        if !bytes.get(at).is_some_and(u8::is_ascii_digit) {
            return Err(syntax);
        }
        let mut exponent: i64 = 0;
        while let Some(&byte) = bytes.get(at) {
            match byte {
                b'0'..=b'9' => {
                    exponent = exponent * 10 + i64::from(byte - b'0');
                    if exponent > MAX_EXPONENT {
                        return Err(CastError::NumericFormatOverflow);
                    }
                    at += 1;
                }
                b'_' => {
                    at += 1;
                    if !bytes.get(at).is_some_and(u8::is_ascii_digit) {
                        return Err(syntax);
                    }
                }
                _ => break,
            }
        }
        let exponent = if negative { -exponent } else { exponent };
        weight += exponent;
        dscale = (dscale - exponent).max(0);
    }
    let mut finite = Finite {
        negative: false,
        digits,
        weight,
        dscale,
    };
    finite.normalise();
    Ok((finite, &bytes[at..]))
}

/// `set_var_from_non_decimal_integer_str` after the base prefix, checking the weight after each
/// group of digits that fills an `int64` as PostgreSQL does.
fn parse_non_decimal(bytes: &[u8], base: u32) -> Result<(Finite, &[u8]), CastError> {
    let syntax = CastError::InvalidInputSyntax(PgType::Numeric);
    // `mul > PG_INT64_MAX / base` starts a new group after this many digits.
    let group_len = match base {
        16 => 15,
        8 => 20,
        _ => 62,
    };
    let mut limbs = Limbs::default();
    let mut group: u64 = 0;
    let mut group_digits: u32 = 0;
    let mut at = 0;
    while let Some(&byte) = bytes.get(at) {
        if let Some(digit) = char::from(byte).to_digit(base) {
            if group_digits == group_len {
                limbs.push_group(group, base, group_digits);
                if limbs.decimal_weight() > MAX_WEIGHT {
                    return Err(CastError::NumericFormatOverflow);
                }
                group = 0;
                group_digits = 0;
            }
            group = group * u64::from(base) + u64::from(digit);
            group_digits += 1;
            at += 1;
        } else if byte == b'_' {
            at += 1;
            let next_is_digit = bytes
                .get(at)
                .is_some_and(|&next| char::from(next).is_digit(base));
            if !next_is_digit {
                return Err(syntax);
            }
        } else {
            break;
        }
    }
    if at == 0 {
        return Err(syntax);
    }
    limbs.push_group(group, base, group_digits);
    if limbs.decimal_weight() > MAX_WEIGHT {
        return Err(CastError::NumericFormatOverflow);
    }
    Ok((limbs.into_finite(), &bytes[at..]))
}

/// A non-negative integer in base 10^9 limbs, least significant first.
#[derive(Default)]
struct Limbs(Vec<u32>);

const LIMB: u128 = 1_000_000_000;

impl Limbs {
    /// Multiply by `base^digits` and add `group`.
    fn push_group(&mut self, group: u64, base: u32, digits: u32) {
        let factor = u128::from(base).pow(digits);
        let mut carry = u128::from(group);
        for limb in &mut self.0 {
            let value = u128::from(*limb) * factor + carry;
            *limb = u32::try_from(value % LIMB).expect("a limb is below 10^9");
            carry = value / LIMB;
        }
        while carry > 0 {
            self.0
                .push(u32::try_from(carry % LIMB).expect("a limb is below 10^9"));
            carry /= LIMB;
        }
    }

    /// The decimal digits, most significant first, with leading zeros.
    fn decimal_digits(&self) -> Vec<u8> {
        let mut digits = Vec::with_capacity(self.0.len() * 9);
        for &limb in self.0.iter().rev() {
            let mut rest = limb;
            let mut chunk = [0u8; 9];
            for slot in chunk.iter_mut().rev() {
                *slot = u8::try_from(rest % 10).expect("a decimal digit fits u8");
                rest /= 10;
            }
            digits.extend_from_slice(&chunk);
        }
        digits
    }

    /// The power of ten of the leading digit, `-1` for zero.
    fn decimal_weight(&self) -> i64 {
        let Some(&top) = self.0.last() else {
            return -1;
        };
        let top_digits = top.checked_ilog10().map_or(0, |log| i64::from(log) + 1);
        let lower = i64::try_from(self.0.len() - 1).expect("a limb count fits i64") * 9;
        lower + top_digits - 1
    }

    fn into_finite(self) -> Finite {
        let digits = self.decimal_digits();
        let weight = i64::try_from(digits.len()).expect("a digit count fits i64") - 1;
        let mut finite = Finite {
            negative: false,
            digits,
            weight,
            dscale: 0,
        };
        finite.normalise();
        finite
    }
}

/// `pg_strncasecmp(bytes, word, word.len()) == 0`.
fn starts_with_ignore_case(bytes: &[u8], word: &[u8]) -> bool {
    bytes
        .get(..word.len())
        .is_some_and(|prefix| prefix.eq_ignore_ascii_case(word))
}

/// `numeric_out`.
impl fmt::Display for PgNumeric {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let finite = match &self.0 {
            Repr::NaN => return f.write_str("NaN"),
            Repr::Infinity { negative: false } => return f.write_str("Infinity"),
            Repr::Infinity { negative: true } => return f.write_str("-Infinity"),
            Repr::Finite(finite) => finite,
        };
        if finite.negative {
            f.write_str("-")?;
        }
        let digit = |power| char::from(b'0' + finite.digit_at(power));
        if finite.weight < 0 || finite.digits.is_empty() {
            f.write_str("0")?;
        } else {
            for power in (0..=finite.weight).rev() {
                fmt::Write::write_char(f, digit(power))?;
            }
        }
        if finite.dscale > 0 {
            f.write_str(".")?;
            for power in 1..=finite.dscale {
                fmt::Write::write_char(f, digit(-power))?;
            }
        }
        Ok(())
    }
}

impl PartialEq for PgNumeric {
    fn eq(&self, other: &Self) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}

impl Eq for PgNumeric {}

impl PartialOrd for PgNumeric {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

/// `cmp_numerics`, ordering `-Infinity` below finite values by value, then `Infinity`, then `NaN`.
impl Ord for PgNumeric {
    fn cmp(&self, other: &Self) -> Ordering {
        match (&self.0, &other.0) {
            (Repr::Finite(left), Repr::Finite(right))
                if left.negative == right.negative && !left.digits.is_empty() =>
            {
                let magnitude = left.cmp_magnitude(right);
                if left.negative {
                    magnitude.reverse()
                } else {
                    magnitude
                }
            }
            _ => self.class().cmp(&other.class()),
        }
    }
}

impl Hash for PgNumeric {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.class().hash(state);
        if let Repr::Finite(finite) = &self.0 {
            finite.weight.hash(state);
            finite.digits.hash(state);
        }
    }
}