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