Skip to main content

sql_values/
cast.rs

1//! PostgreSQL 18's explicit cast of a literal, `'…'::type` or `1.5::type`, as the input function
2//! or the cast from the constant's type followed by the length coercion of the target's modifier.
3
4use alloc::string::{String, ToString};
5use core::fmt;
6
7use crate::{
8    datetime::{DateTimeError, InputContext, PgDate, PgTimestamp, PgTimestampTz},
9    numeric::{NumericTypmod, PgNumeric},
10};
11
12/// A literal as written before `::`, its quotes and escapes already decoded.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14pub enum Literal<'a> {
15    /// A string constant, `'…'`, `E'…'` or `$$…$$`, whose type PostgreSQL leaves unknown until
16    /// the cast reads it with the target's input function.
17    Quoted(&'a str),
18    /// A numeric constant as PostgreSQL 18's lexer reads it, `42`, `0x2A`, `1_000`, `2.5`, `.5`
19    /// or `1e2`, with a leading `-` for a negation the parser folds into the constant, as in
20    /// `(-2.5)::int`.
21    Number(&'a str),
22}
23
24/// The type a literal is cast to, with its modifier.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
26pub enum CastTarget {
27    /// `boolean`.
28    Boolean,
29    /// `smallint`.
30    Smallint,
31    /// `integer`.
32    Integer,
33    /// `bigint`.
34    Bigint,
35    /// `numeric`, or `numeric(p, s)` with a modifier.
36    Numeric(Option<NumericTypmod>),
37    /// `text`.
38    Text,
39    /// `varchar`, or `varchar(n)` with a length.
40    Varchar(Option<CharLength>),
41    /// `bpchar`, or `char(n)` with a length, where a bare `char` is `char(1)`.
42    Bpchar(Option<CharLength>),
43    /// `date`.
44    Date,
45    /// `timestamp`, or `timestamp(p)` with a precision, where one above 6 is 6.
46    Timestamp(Option<u8>),
47    /// `timestamptz`, or `timestamptz(p)` with a precision, where one above 6 is 6.
48    TimestampTz(Option<u8>),
49}
50
51/// The length of a `varchar(n)` or `char(n)` type, in characters.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
53pub struct CharLength(usize);
54
55/// `MaxAttrSize`, the longest length a character type takes.
56const MAX_CHAR_LENGTH: usize = 10_485_760;
57
58impl CharLength {
59    /// The length PostgreSQL accepts in `varchar(n)` and `char(n)`, from 1 to 10485760.
60    ///
61    /// ```
62    /// use sql_values::CharLength;
63    ///
64    /// assert!(CharLength::new(1).is_some());
65    /// assert!(CharLength::new(0).is_none());
66    /// assert!(CharLength::new(10_485_761).is_none());
67    /// ```
68    #[must_use]
69    pub fn new(length: usize) -> Option<Self> {
70        (1..=MAX_CHAR_LENGTH)
71            .contains(&length)
72            .then_some(Self(length))
73    }
74}
75
76/// A type PostgreSQL names in a cast's error.
77#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
78pub enum PgType {
79    /// `boolean`.
80    Boolean,
81    /// `smallint`.
82    Smallint,
83    /// `integer`.
84    Integer,
85    /// `bigint`.
86    Bigint,
87    /// `numeric`.
88    Numeric,
89    /// `text`.
90    Text,
91    /// `character varying`.
92    Varchar,
93    /// `character`.
94    Bpchar,
95    /// `date`.
96    Date,
97    /// `timestamp without time zone`.
98    Timestamp,
99    /// `timestamp with time zone`.
100    TimestampTz,
101}
102
103impl fmt::Display for PgType {
104    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105        f.write_str(match self {
106            Self::Boolean => "boolean",
107            Self::Smallint => "smallint",
108            Self::Integer => "integer",
109            Self::Bigint => "bigint",
110            Self::Numeric => "numeric",
111            Self::Text => "text",
112            Self::Varchar => "character varying",
113            Self::Bpchar => "character",
114            Self::Date => "date",
115            Self::Timestamp => "timestamp without time zone",
116            Self::TimestampTz => "timestamp with time zone",
117        })
118    }
119}
120
121impl CastTarget {
122    /// The type without its modifier.
123    #[must_use]
124    pub const fn pg_type(self) -> PgType {
125        match self {
126            Self::Boolean => PgType::Boolean,
127            Self::Smallint => PgType::Smallint,
128            Self::Integer => PgType::Integer,
129            Self::Bigint => PgType::Bigint,
130            Self::Numeric(_) => PgType::Numeric,
131            Self::Text => PgType::Text,
132            Self::Varchar(_) => PgType::Varchar,
133            Self::Bpchar(_) => PgType::Bpchar,
134            Self::Date => PgType::Date,
135            Self::Timestamp(_) => PgType::Timestamp,
136            Self::TimestampTz(_) => PgType::TimestampTz,
137        }
138    }
139}
140
141/// The value a cast produces, printed by [`Display`](fmt::Display) as the type's output function
142/// prints it under the default `DateStyle` of `ISO`.
143#[derive(Debug, Clone, PartialEq, Eq, Hash)]
144pub enum CastValue {
145    /// A `boolean`, printed `t` or `f`.
146    Boolean(bool),
147    /// A `smallint`.
148    Smallint(i16),
149    /// An `integer`.
150    Integer(i32),
151    /// A `bigint`.
152    Bigint(i64),
153    /// A `numeric`.
154    Numeric(PgNumeric),
155    /// A `text` or `varchar`.
156    Text(String),
157    /// A `char(n)`, blank-padded to its length as PostgreSQL holds it. PostgreSQL drops the
158    /// trailing blanks when it compares it with `text` or casts it to `text`.
159    Bpchar(String),
160    /// A `date`.
161    Date(PgDate),
162    /// A `timestamp`.
163    Timestamp(PgTimestamp),
164    /// A `timestamptz`, printed as under `TimeZone` `UTC`.
165    TimestampTz(PgTimestampTz),
166}
167
168/// Why PostgreSQL refuses a cast, one variant per message it raises, or why this crate declines
169/// to answer for it.
170#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
171pub enum CastError {
172    /// Text the target's input function cannot read.
173    #[error("invalid input syntax for type {0}")]
174    InvalidInputSyntax(PgType),
175    /// Text the integer input function reads as a number beyond the type.
176    #[error("value is out of range for type {0}")]
177    ValueOutOfRange(PgType),
178    /// A constant the cast to an integer type finds beyond the type.
179    #[error("{0} out of range")]
180    OutOfRange(PgType),
181    /// A value beyond the precision of `numeric(p, s)` after rounding to its scale, or an
182    /// infinity cast to it.
183    #[error("numeric field overflow")]
184    NumericFieldOverflow,
185    /// A `numeric` beyond the weight or display scale PostgreSQL stores.
186    #[error("value overflows numeric format")]
187    NumericFormatOverflow,
188    /// A year, month or day no calendar has.
189    #[error("date/time field value out of range")]
190    DateTimeFieldOutOfRange,
191    /// A date before 4714-11-24 BC.
192    #[error("date out of range")]
193    DateOutOfRange,
194    /// A timestamp before 4714-11-24 BC.
195    #[error("timestamp out of range")]
196    TimestampOutOfRange,
197    /// An offset of 16 hours or more, or with minutes or seconds of 60 or more.
198    #[error("time zone displacement out of range")]
199    TimeZoneDisplacementOutOfRange,
200    /// A numeric constant of a type with no cast to the target.
201    #[error("cannot cast type {from} to {to}")]
202    CannotCast {
203        /// The constant's type.
204        from: PgType,
205        /// The target's type.
206        to: PgType,
207    },
208    /// A literal or cast this crate does not model. A date or timestamp is read only in the
209    /// spellings [`PgDate::parse`] and [`PgTimestamp::parse`] read, and a `timestamptz` only
210    /// with its offset, since without one the session's `TimeZone` decides the instant.
211    #[error("cast not modelled")]
212    Unsupported,
213}
214
215/// The value PostgreSQL 18's explicit cast `literal::target` produces, or the error it raises,
216/// with a database encoding of UTF-8.
217///
218/// # Errors
219///
220/// The [`CastError`] PostgreSQL raises, or [`CastError::Unsupported`] for a literal or cast this
221/// crate does not model.
222///
223/// ```
224/// use sql_values::{CastError, CastTarget, CharLength, Literal, NumericTypmod, PgType, cast_literal};
225///
226/// let cast = |literal, target| cast_literal(literal, target).map(|value| value.to_string());
227/// let length = |n| CharLength::new(n);
228///
229/// assert_eq!(cast(Literal::Number("2.5"), CastTarget::Integer).unwrap(), "3");
230/// assert_eq!(cast(Literal::Number("-2.5"), CastTarget::Integer).unwrap(), "-3");
231/// assert_eq!(cast(Literal::Number("1e2"), CastTarget::Integer).unwrap(), "100");
232/// assert_eq!(cast(Literal::Number("2.5"), CastTarget::Smallint).unwrap(), "3");
233/// assert_eq!(
234///     cast(Literal::Number("32768"), CastTarget::Smallint),
235///     Err(CastError::OutOfRange(PgType::Smallint)),
236/// );
237/// assert_eq!(
238///     cast(Literal::Quoted("2.5"), CastTarget::Integer),
239///     Err(CastError::InvalidInputSyntax(PgType::Integer)),
240/// );
241///
242/// assert_eq!(cast(Literal::Quoted("abc"), CastTarget::Bpchar(length(2))).unwrap(), "ab");
243/// assert_eq!(cast(Literal::Quoted("ab"), CastTarget::Bpchar(length(4))).unwrap(), "ab  ");
244/// assert_eq!(cast(Literal::Quoted("ab"), CastTarget::Varchar(length(1))).unwrap(), "a");
245/// assert_eq!(cast(Literal::Quoted("abc  "), CastTarget::Varchar(length(3))).unwrap(), "abc");
246///
247/// let numeric_4_1 = CastTarget::Numeric(NumericTypmod::new(4, 1));
248/// assert_eq!(cast(Literal::Quoted("12.345"), numeric_4_1).unwrap(), "12.3");
249/// assert_eq!(cast(Literal::Number("12.345"), numeric_4_1).unwrap(), "12.3");
250///
251/// assert_eq!(cast(Literal::Quoted("yes"), CastTarget::Boolean).unwrap(), "t");
252///
253/// assert_eq!(cast(Literal::Quoted("2026-01-01 23:00"), CastTarget::Date).unwrap(), "2026-01-01");
254/// assert_eq!(
255///     cast(Literal::Quoted("2026-01-01T23:00:00+05"), CastTarget::Date).unwrap(),
256///     "2026-01-01",
257/// );
258/// assert_eq!(
259///     cast(Literal::Quoted("2026-01-01 23:00:00.6"), CastTarget::Timestamp(Some(0))).unwrap(),
260///     "2026-01-01 23:00:01",
261/// );
262/// assert_eq!(cast(Literal::Quoted("today"), CastTarget::Date), Err(CastError::Unsupported));
263///
264/// let instant = CastTarget::TimestampTz(None);
265/// assert_eq!(
266///     cast(Literal::Quoted("2030-01-01 00:00:00+02"), instant).unwrap(),
267///     "2029-12-31 22:00:00+00",
268/// );
269/// assert_eq!(
270///     cast(Literal::Quoted("2030-01-01 00:00:00"), instant),
271///     Err(CastError::Unsupported),
272/// );
273/// ```
274pub fn cast_literal(literal: Literal<'_>, target: CastTarget) -> Result<CastValue, CastError> {
275    match literal {
276        Literal::Quoted(text) => cast_quoted(text, target),
277        Literal::Number(text) => cast_constant(Constant::read(text)?, target),
278    }
279}
280
281/// A numeric constant as `make_const` types it.
282enum Constant {
283    Integer(i32),
284    Bigint(i64),
285    Numeric(PgNumeric),
286}
287
288impl Constant {
289    /// The constant PostgreSQL's lexer and `make_const` make of `text`.
290    fn read(text: &str) -> Result<Self, CastError> {
291        let unsigned = text.strip_prefix('-').unwrap_or(text);
292        match scan_number(unsigned.as_bytes()) {
293            None => Err(CastError::Unsupported),
294            Some(NumberToken::Integer) => {
295                if let Ok(value) = int_in(text, 32) {
296                    Ok(Self::Integer(narrow(value)))
297                } else if let Ok(value) = int_in(text, 64) {
298                    Ok(Self::Bigint(value))
299                } else {
300                    PgNumeric::parse(text).map(Self::Numeric)
301                }
302            }
303            Some(NumberToken::Decimal) => PgNumeric::parse(text).map(Self::Numeric),
304        }
305    }
306
307    const fn pg_type(&self) -> PgType {
308        match self {
309            Self::Integer(_) => PgType::Integer,
310            Self::Bigint(_) => PgType::Bigint,
311            Self::Numeric(_) => PgType::Numeric,
312        }
313    }
314
315    /// The constant as an `i64`, `numeric` rounded half away from zero, or `None` beyond it.
316    fn into_i64(self) -> Option<i64> {
317        match self {
318            Self::Integer(value) => Some(i64::from(value)),
319            Self::Bigint(value) => Some(value),
320            Self::Numeric(value) => value.into_i64_rounded(),
321        }
322    }
323}
324
325/// The lexer's token for a numeric constant.
326enum NumberToken {
327    /// `decinteger`, `hexinteger`, `octinteger` or `bininteger`.
328    Integer,
329    /// `numeric` or `real`.
330    Decimal,
331}
332
333/// The token PostgreSQL 18's `scan.l` reads `bytes` as, or `None` when it is not one numeric
334/// constant.
335fn scan_number(bytes: &[u8]) -> Option<NumberToken> {
336    let (radix, digits) = match bytes {
337        [b'0', b'x' | b'X', digits @ ..] => (16, digits),
338        [b'0', b'o' | b'O', digits @ ..] => (8, digits),
339        [b'0', b'b' | b'B', digits @ ..] => (2, digits),
340        _ => return scan_decimal(bytes),
341    };
342    // `0[xX](_?{hexdigit})+`, where an underscore may follow the prefix.
343    let mut at = 0;
344    while at < digits.len() {
345        at += usize::from(digits[at] == b'_');
346        if !digits
347            .get(at)
348            .is_some_and(|&b| char::from(b).is_digit(radix))
349        {
350            return None;
351        }
352        at += 1;
353    }
354    (at > 0).then_some(NumberToken::Integer)
355}
356
357/// `decinteger`, `numeric` or `real`.
358fn scan_decimal(bytes: &[u8]) -> Option<NumberToken> {
359    let integer = scan_decinteger(bytes);
360    let mut at = integer;
361    let mut token = NumberToken::Integer;
362    if bytes.get(at) == Some(&b'.') {
363        token = NumberToken::Decimal;
364        at += 1;
365        let fraction = scan_decinteger(&bytes[at..]);
366        if integer == 0 && fraction == 0 {
367            return None;
368        }
369        at += fraction;
370    } else if integer == 0 {
371        return None;
372    }
373    if matches!(bytes.get(at), Some(b'e' | b'E')) {
374        token = NumberToken::Decimal;
375        at += 1;
376        at += usize::from(matches!(bytes.get(at), Some(b'+' | b'-')));
377        let exponent = scan_decinteger(&bytes[at..]);
378        if exponent == 0 {
379            return None;
380        }
381        at += exponent;
382    }
383    (at == bytes.len()).then_some(token)
384}
385
386/// The length of the leading `{decdigit}(_?{decdigit})*`, `0` when there is none.
387fn scan_decinteger(bytes: &[u8]) -> usize {
388    if !bytes.first().is_some_and(u8::is_ascii_digit) {
389        return 0;
390    }
391    let mut at = 1;
392    loop {
393        let next = at + usize::from(bytes.get(at) == Some(&b'_'));
394        if !bytes.get(next).is_some_and(u8::is_ascii_digit) {
395            return at;
396        }
397        at = next + 1;
398    }
399}
400
401/// The cast of a numeric constant by `int4_bool`, the integer narrowings, `numeric_int*`, the
402/// `numeric()` length coercion, or the output function for a character type.
403fn cast_constant(constant: Constant, target: CastTarget) -> Result<CastValue, CastError> {
404    let from = constant.pg_type();
405    match target {
406        CastTarget::Boolean => match constant {
407            Constant::Integer(value) => Ok(CastValue::Boolean(value != 0)),
408            _ => Err(CastError::CannotCast {
409                from,
410                to: PgType::Boolean,
411            }),
412        },
413        CastTarget::Smallint => {
414            let value = constant.into_i64().and_then(|v| i16::try_from(v).ok());
415            value
416                .map(CastValue::Smallint)
417                .ok_or(CastError::OutOfRange(PgType::Smallint))
418        }
419        CastTarget::Integer => {
420            let value = constant.into_i64().and_then(|v| i32::try_from(v).ok());
421            value
422                .map(CastValue::Integer)
423                .ok_or(CastError::OutOfRange(PgType::Integer))
424        }
425        CastTarget::Bigint => constant
426            .into_i64()
427            .map(CastValue::Bigint)
428            .ok_or(CastError::OutOfRange(PgType::Bigint)),
429        CastTarget::Numeric(typmod) => {
430            let value = match constant {
431                Constant::Integer(value) => PgNumeric::from_i64(i64::from(value)),
432                Constant::Bigint(value) => PgNumeric::from_i64(value),
433                Constant::Numeric(value) => value,
434            };
435            numeric_typmod(value, typmod)
436        }
437        CastTarget::Text | CastTarget::Varchar(_) | CastTarget::Bpchar(_) => {
438            let text = match constant {
439                Constant::Integer(value) => value.to_string(),
440                Constant::Bigint(value) => value.to_string(),
441                Constant::Numeric(value) => value.to_string(),
442            };
443            Ok(character(&text, target))
444        }
445        CastTarget::Date | CastTarget::Timestamp(_) | CastTarget::TimestampTz(_) => {
446            Err(CastError::CannotCast {
447                from,
448                to: target.pg_type(),
449            })
450        }
451    }
452}
453
454/// The cast of an unknown literal, the target's input function without a modifier followed by
455/// the length coercion.
456fn cast_quoted(text: &str, target: CastTarget) -> Result<CastValue, CastError> {
457    // A string constant never holds NUL, which ends a C string.
458    if text.contains('\0') {
459        return Err(CastError::Unsupported);
460    }
461    match target {
462        CastTarget::Boolean => bool_in(text).map(CastValue::Boolean),
463        CastTarget::Smallint => int_input(text, 16, PgType::Smallint).map(|v| {
464            CastValue::Smallint(i16::try_from(v).expect("int_in kept the value in 16 bits"))
465        }),
466        CastTarget::Integer => {
467            int_input(text, 32, PgType::Integer).map(|v| CastValue::Integer(narrow(v)))
468        }
469        CastTarget::Bigint => int_input(text, 64, PgType::Bigint).map(CastValue::Bigint),
470        CastTarget::Numeric(typmod) => numeric_typmod(PgNumeric::parse(text)?, typmod),
471        CastTarget::Text | CastTarget::Varchar(_) | CastTarget::Bpchar(_) => {
472            Ok(character(text, target))
473        }
474        CastTarget::Date => PgDate::parse(text, InputContext::new())
475            .map(CastValue::Date)
476            .map_err(datetime_error),
477        CastTarget::Timestamp(precision) => {
478            let at = PgTimestamp::parse(text, InputContext::new()).map_err(datetime_error)?;
479            let micros = adjust_timestamp_for_typmod(at.pg_micros(), precision);
480            Ok(CastValue::Timestamp(PgTimestamp::from_stored(micros)))
481        }
482        CastTarget::TimestampTz(precision) => {
483            let at = PgTimestampTz::parse(text, InputContext::new()).map_err(datetime_error)?;
484            let micros = adjust_timestamp_for_typmod(at.pg_micros(), precision);
485            Ok(CastValue::TimestampTz(PgTimestampTz::from_stored(micros)))
486        }
487    }
488}
489
490/// An `i64` `int_in` read within 32 bits.
491fn narrow(value: i64) -> i32 {
492    i32::try_from(value).expect("int_in kept the value in 32 bits")
493}
494
495fn numeric_typmod(value: PgNumeric, typmod: Option<NumericTypmod>) -> Result<CastValue, CastError> {
496    match typmod {
497        Some(typmod) => value.apply_typmod(typmod),
498        None => Ok(value),
499    }
500    .map(CastValue::Numeric)
501}
502
503/// The `varchar()` or `bpchar()` length coercion of an explicit cast, which truncates to the
504/// length and, for `char(n)`, pads with blanks.
505fn character(text: &str, target: CastTarget) -> CastValue {
506    match target {
507        CastTarget::Varchar(Some(length)) => CastValue::Text(clip(text, length).into()),
508        CastTarget::Bpchar(Some(length)) => {
509            let clipped = clip(text, length);
510            let mut padded = String::from(clipped);
511            let blanks = length.0 - clipped.chars().count();
512            padded.extend(core::iter::repeat_n(' ', blanks));
513            CastValue::Bpchar(padded)
514        }
515        CastTarget::Bpchar(None) => CastValue::Bpchar(text.into()),
516        _ => CastValue::Text(text.into()),
517    }
518}
519
520/// The first `length` characters of `text`.
521fn clip(text: &str, length: CharLength) -> &str {
522    text.char_indices()
523        .nth(length.0)
524        .map_or(text, |(end, _)| &text[..end])
525}
526
527/// The C library's `isspace` in the C locale.
528pub(crate) const fn is_pg_space(byte: u8) -> bool {
529    matches!(byte, b' ' | b'\t' | b'\n' | 0x0B | 0x0C | b'\r')
530}
531
532pub(crate) fn trim_pg_space(bytes: &[u8]) -> &[u8] {
533    let start = bytes.iter().take_while(|&&b| is_pg_space(b)).count();
534    let end = bytes
535        .iter()
536        .rposition(|&b| !is_pg_space(b))
537        .map_or(start, |last| last + 1);
538    &bytes[start..end.max(start)]
539}
540
541/// `boolin`, reading a case-insensitive prefix of `true`, `false`, `yes` or `no`, `on`, `of` or
542/// `off`, or `1` or `0`, between blanks.
543fn bool_in(text: &str) -> Result<bool, CastError> {
544    let word = trim_pg_space(text.as_bytes());
545    let abbreviates = |full: &[u8]| {
546        full.get(..word.len())
547            .is_some_and(|prefix| prefix.eq_ignore_ascii_case(word))
548    };
549    let value = match word {
550        [b't' | b'T', ..] if abbreviates(b"true") => true,
551        [b'f' | b'F', ..] if abbreviates(b"false") => false,
552        [b'y' | b'Y', ..] if abbreviates(b"yes") => true,
553        [b'n' | b'N', ..] if abbreviates(b"no") => false,
554        [b'o' | b'O', _, ..] if abbreviates(b"on") => true,
555        [b'o' | b'O', _, ..] if abbreviates(b"off") => false,
556        b"1" => true,
557        b"0" => false,
558        _ => return Err(CastError::InvalidInputSyntax(PgType::Boolean)),
559    };
560    Ok(value)
561}
562
563/// Why `pg_strtoint*` refuses text.
564enum IntInputError {
565    Syntax,
566    Range,
567}
568
569/// `int_in` for a type of `bits`, mapping its refusal to the error naming `pg_type`.
570fn int_input(text: &str, bits: u32, pg_type: PgType) -> Result<i64, CastError> {
571    int_in(text, bits).map_err(|error| match error {
572        IntInputError::Syntax => CastError::InvalidInputSyntax(pg_type),
573        IntInputError::Range => CastError::ValueOutOfRange(pg_type),
574    })
575}
576
577/// `pg_strtoint16`, `pg_strtoint32` or `pg_strtoint64` by `bits`, reading blanks, a sign, a
578/// decimal, `0x`, `0o` or `0b` integer with single underscores between digits, then blanks. An
579/// overflow stops the read where it happens, before any trailing junk is seen.
580fn int_in(text: &str, bits: u32) -> Result<i64, IntInputError> {
581    let bytes = text.as_bytes();
582    let mut at = bytes.iter().take_while(|&&b| is_pg_space(b)).count();
583    let negative = bytes.get(at) == Some(&b'-');
584    at += usize::from(matches!(bytes.get(at), Some(b'+' | b'-')));
585    let radix = match (bytes.get(at), bytes.get(at + 1)) {
586        (Some(b'0'), Some(b'x' | b'X')) => 16,
587        (Some(b'0'), Some(b'o' | b'O')) => 8,
588        (Some(b'0'), Some(b'b' | b'B')) => 2,
589        _ => 10,
590    };
591    if radix != 10 {
592        at += 2;
593    }
594    let first_digit = at;
595    let is_digit = |byte: Option<&u8>| byte.is_some_and(|&b| char::from(b).is_digit(radix));
596    // The magnitude of the type's minimum, which a negative value reaches.
597    let limit: u64 = 1 << (bits - 1);
598    let mut magnitude: u64 = 0;
599    loop {
600        match bytes.get(at) {
601            Some(&byte) if is_digit(Some(&byte)) => {
602                if magnitude > limit / u64::from(radix) {
603                    return Err(IntInputError::Range);
604                }
605                let digit = char::from(byte).to_digit(radix).expect("checked a digit");
606                magnitude = magnitude * u64::from(radix) + u64::from(digit);
607                at += 1;
608            }
609            Some(b'_') => {
610                if radix == 10 && at == first_digit {
611                    return Err(IntInputError::Syntax);
612                }
613                at += 1;
614                if !is_digit(bytes.get(at)) {
615                    return Err(IntInputError::Syntax);
616                }
617            }
618            _ => break,
619        }
620    }
621    if at == first_digit || !bytes[at..].iter().all(|&b| is_pg_space(b)) {
622        return Err(IntInputError::Syntax);
623    }
624    let value = if negative {
625        -i128::from(magnitude)
626    } else {
627        i128::from(magnitude)
628    };
629    let range = -i128::from(limit)..i128::from(limit);
630    if range.contains(&value) {
631        Ok(i64::try_from(value).expect("a value within 64 bits fits i64"))
632    } else {
633        Err(IntInputError::Range)
634    }
635}
636
637/// `AdjustTimestampForTypmod`, rounding a finite timestamp half away from 2000-01-01 to
638/// `precision` digits, with no range check after, as PostgreSQL rounds the last second of
639/// 294276 up to 294277-01-01.
640fn adjust_timestamp_for_typmod(micros: i64, precision: Option<u8>) -> i64 {
641    let Some(precision @ 0..6) = precision else {
642        return micros;
643    };
644    if micros == i64::MAX || micros == i64::MIN {
645        return micros;
646    }
647    let scale = 10i64.pow(6 - u32::from(precision));
648    let offset = scale / 2;
649    if micros >= 0 {
650        (micros + offset) / scale * scale
651    } else {
652        -((-micros + offset) / scale * scale)
653    }
654}
655
656/// The cast error of a refusal by a date or time input function.
657fn datetime_error(error: DateTimeError) -> CastError {
658    match error {
659        DateTimeError::FieldValueOutOfRange => CastError::DateTimeFieldOutOfRange,
660        DateTimeError::TimeZoneDisplacementOutOfRange => CastError::TimeZoneDisplacementOutOfRange,
661        DateTimeError::DateOutOfRange => CastError::DateOutOfRange,
662        DateTimeError::TimestampOutOfRange => CastError::TimestampOutOfRange,
663        DateTimeError::OutsideJiffRange
664        | DateTimeError::NeedsTimeZone
665        | DateTimeError::TimeZoneNotRecognized
666        | DateTimeError::Unsupported => CastError::Unsupported,
667    }
668}
669
670/// Each type's output function under `DateStyle` `ISO` and `TimeZone` `UTC`.
671impl fmt::Display for CastValue {
672    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
673        match self {
674            Self::Boolean(value) => f.write_str(if *value { "t" } else { "f" }),
675            Self::Smallint(value) => write!(f, "{value}"),
676            Self::Integer(value) => write!(f, "{value}"),
677            Self::Bigint(value) => write!(f, "{value}"),
678            Self::Numeric(value) => write!(f, "{value}"),
679            Self::Text(text) | Self::Bpchar(text) => f.write_str(text),
680            Self::Date(date) => write!(f, "{date}"),
681            Self::Timestamp(at) => write!(f, "{at}"),
682            Self::TimestampTz(at) => write!(f, "{at}"),
683        }
684    }
685}