1use alloc::string::{String, ToString};
6use core::fmt;
7
8use super::{
9 BuiltinType,
10 bpchar::PgBpchar,
11 datetime::{
12 DateTimeError, InputContext, PgDate, PgTime, PgTimeTz, PgTimestamp, PgTimestampTz,
13 USECS_PER_DAY,
14 },
15 integer::IntegerType,
16 interval::{IntervalError, PgInterval, parse_interval, parse_interval_typmod},
17 jsonb::{JsonbError, JsonbKind, PgJsonb},
18 numeric::{NumericError, NumericTypmod, PgNumeric},
19 uuid::{PgUuid, UuidError},
20};
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
24pub enum Literal<'a> {
25 Quoted(&'a str),
28 Number(&'a str),
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
36pub struct CharLength(usize);
37
38const MAX_CHAR_LENGTH: usize = 10_485_760;
40
41impl CharLength {
42 #[must_use]
44 pub const fn get(self) -> usize {
45 self.0
46 }
47 #[must_use]
57 pub fn new(length: usize) -> Option<Self> {
58 (1..=MAX_CHAR_LENGTH)
59 .contains(&length)
60 .then_some(Self(length))
61 }
62}
63
64#[derive(Debug, Clone, PartialEq, Eq, Hash)]
67pub enum CastValue {
68 Boolean(bool),
70 Smallint(i16),
72 Integer(i32),
74 Bigint(i64),
76 Numeric(PgNumeric),
78 Text(String),
80 Bpchar(PgBpchar<'static>),
83 Date(PgDate),
85 Timestamp(PgTimestamp),
87 TimestampTz(PgTimestampTz),
89 Time(PgTime),
91 TimeTz(PgTimeTz),
93 Jsonb(PgJsonb),
95 Uuid(PgUuid),
97 Interval(PgInterval),
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
105#[non_exhaustive]
106pub enum CastError {
107 #[error("invalid input syntax for type {}", .0.input_name())]
109 InvalidInputSyntax(BuiltinType),
110 #[error("value is out of range for type {}", .0.diagnostic_name())]
112 ValueOutOfRange(BuiltinType),
113 #[error("{} out of range", .0.diagnostic_name())]
115 OutOfRange(BuiltinType),
116 #[error("cannot convert NaN to {}", .0.diagnostic_name())]
118 CannotConvertNaN(BuiltinType),
119 #[error("cannot convert infinity to {}", .0.diagnostic_name())]
121 CannotConvertInfinity(BuiltinType),
122 #[error("numeric field overflow")]
125 NumericFieldOverflow,
126 #[error("value overflows numeric format")]
128 NumericFormatOverflow,
129 #[error("date/time field value out of range")]
131 DateTimeFieldOutOfRange,
132 #[error("date out of range")]
134 DateOutOfRange,
135 #[error("timestamp out of range")]
137 TimestampOutOfRange,
138 #[error("date out of range for timestamp")]
140 DateOutOfRangeForTimestamp,
141 #[error("time zone displacement out of range")]
143 TimeZoneDisplacementOutOfRange,
144 #[error("interval field value out of range")]
146 IntervalFieldValueOutOfRange,
147 #[error("interval out of range")]
149 IntervalOutOfRange,
150 #[error("cannot convert infinite interval to time")]
152 CannotConvertInfiniteIntervalToTime,
153 #[error("cannot cast type {} to {}", .from.diagnostic_name(), .to.diagnostic_name())]
155 CannotCast {
156 from: BuiltinType,
158 to: BuiltinType,
160 },
161 #[error("cannot cast jsonb {from} to type {}", .to.diagnostic_name())]
164 CannotCastJsonb {
165 from: JsonbKind,
167 to: BuiltinType,
169 },
170 #[error(transparent)]
172 Jsonb(JsonbError),
173 #[error("malformed array literal")]
175 MalformedArrayLiteral,
176 #[error("number of array dimensions exceeds the maximum allowed (6)")]
178 ArrayDimensionsExceeded,
179 #[error("upper bound cannot be less than lower bound")]
181 UpperBoundLessThanLower,
182 #[error("array upper bound is too large: {0}")]
184 ArrayUpperBoundTooLarge(i32),
185 #[error("array size exceeds the maximum allowed (134217727)")]
187 ArraySizeExceeded,
188 #[error("array bound is out of integer range")]
190 ArrayBoundOutOfRange,
191 #[error("cast not modelled")]
198 Unsupported,
199}
200
201pub fn cast_literal(literal: Literal<'_>, target: BuiltinType) -> Result<CastValue, CastError> {
289 match literal {
290 Literal::Quoted(text) => cast_quoted(text, target),
291 Literal::Number(_) if !target.supports_cast() => Err(CastError::Unsupported),
292 Literal::Number(text) => cast_non_null(number_constant(text)?, target),
293 }
294}
295
296pub fn number_constant(text: &str) -> Result<CastValue, CastError> {
317 let unsigned = text.strip_prefix('-').unwrap_or(text);
318 match scan_number(unsigned.as_bytes()) {
319 None => Err(CastError::Unsupported),
320 Some(NumberToken::Integer) => [IntegerType::Integer, IntegerType::Bigint]
321 .into_iter()
322 .find_map(|integer| int_input(text, integer).ok())
323 .map_or_else(|| numeric_input(text).map(CastValue::Numeric), Ok),
324 Some(NumberToken::Decimal) => numeric_input(text).map(CastValue::Numeric),
325 }
326}
327
328pub fn cast_value(value: CastValue, target: BuiltinType) -> Result<Option<CastValue>, CastError> {
406 match (value, target) {
407 (CastValue::Jsonb(value), _) => cast_jsonb(value, target),
408 (CastValue::Timestamp(at), BuiltinType::Time(precision)) => Ok(at.time().map(|time| {
410 CastValue::Time(time.adjust_for_typmod(precision.map(super::TimePrecision::get)))
411 })),
412 (value, _) => cast_non_null(value, target).map(Some),
413 }
414}
415
416fn cast_jsonb(value: PgJsonb, target: BuiltinType) -> Result<Option<CastValue>, CastError> {
418 let to = target.pg_type();
419 let cannot_cast = |from| CastError::CannotCastJsonb { from, to };
420 match target {
421 BuiltinType::Boolean => Ok(value
422 .to_bool()
423 .map_err(cannot_cast)?
424 .map(CastValue::Boolean)),
425 BuiltinType::Smallint
426 | BuiltinType::Integer
427 | BuiltinType::Bigint
428 | BuiltinType::Numeric(_) => value
429 .into_numeric()
430 .map_err(cannot_cast)?
431 .map(|number| cast_non_null(CastValue::Numeric(number), target))
432 .transpose(),
433 BuiltinType::Text | BuiltinType::Varchar(_) | BuiltinType::Bpchar(_) => {
434 Ok(Some(character(&value.to_string(), target)))
435 }
436 BuiltinType::Jsonb => Ok(Some(CastValue::Jsonb(value))),
437 _ => cast_non_null(CastValue::Jsonb(value), target).map(Some),
438 }
439}
440
441fn cast_non_null(value: CastValue, target: BuiltinType) -> Result<CastValue, CastError> {
444 if !target.supports_cast() {
445 return Err(CastError::Unsupported);
446 }
447 let cannot_cast = CastError::CannotCast {
448 from: value.pg_type(),
449 to: target.pg_type(),
450 };
451 match (value, target) {
452 (CastValue::Text(text), _) => cast_text(&text, target),
453 (CastValue::Bpchar(value), BuiltinType::Text | BuiltinType::Varchar(_)) => {
455 Ok(character(value.as_text(), target))
456 }
457 (CastValue::Bpchar(value), _) => cast_text(value.as_str(), target),
458 (
459 CastValue::TimestampTz(_),
460 BuiltinType::Date
461 | BuiltinType::Timestamp(_)
462 | BuiltinType::Time(_)
463 | BuiltinType::TimeTz(_)
464 | BuiltinType::Text
465 | BuiltinType::Varchar(_)
466 | BuiltinType::Bpchar(_),
467 )
468 | (CastValue::Date(_) | CastValue::Timestamp(_), BuiltinType::TimestampTz(_))
469 | (CastValue::Time(_), BuiltinType::TimeTz(_)) => Err(CastError::Unsupported),
470 (
472 CastValue::Boolean(value),
473 BuiltinType::Text | BuiltinType::Varchar(_) | BuiltinType::Bpchar(_),
474 ) => Ok(character(if value { "true" } else { "false" }, target)),
475 (value, BuiltinType::Text | BuiltinType::Varchar(_) | BuiltinType::Bpchar(_)) => {
476 Ok(character(&value.to_string(), target))
477 }
478 (CastValue::Boolean(value), BuiltinType::Boolean) => Ok(CastValue::Boolean(value)),
479 (CastValue::Boolean(value), BuiltinType::Integer) => Ok(CastValue::Integer(value.into())),
480 (CastValue::Integer(value), BuiltinType::Boolean) => Ok(CastValue::Boolean(value != 0)),
481 (CastValue::Smallint(value), _) if target.takes_integer() => integer(value.into(), target),
482 (CastValue::Integer(value), _) if target.takes_integer() => integer(value.into(), target),
483 (CastValue::Bigint(value), _) if target.takes_integer() => integer(value, target),
484 (CastValue::Numeric(value), BuiltinType::Numeric(typmod)) => numeric_typmod(value, typmod),
485 (CastValue::Numeric(value), _) if target.takes_integer() => {
486 let to = target.pg_type();
487 if value.is_nan() {
488 Err(CastError::CannotConvertNaN(to))
489 } else if value.is_infinite() {
490 Err(CastError::CannotConvertInfinity(to))
491 } else {
492 let value = value.to_i64_rounded().ok_or(CastError::OutOfRange(to))?;
493 integer(value, target)
494 }
495 }
496 (CastValue::Date(date), BuiltinType::Date) => Ok(CastValue::Date(date)),
497 (CastValue::Date(date), BuiltinType::Timestamp(precision)) => {
498 let at = date
500 .to_timestamp()
501 .map_err(|_| CastError::DateOutOfRangeForTimestamp)?;
502 Ok(CastValue::Timestamp(at.adjust_for_typmod(
503 precision.map(super::TimePrecision::get),
504 )))
505 }
506 (CastValue::Timestamp(at), BuiltinType::Date) => Ok(CastValue::Date(at.date())),
507 (CastValue::Timestamp(at), BuiltinType::Timestamp(precision)) => Ok(CastValue::Timestamp(
508 at.adjust_for_typmod(precision.map(super::TimePrecision::get)),
509 )),
510 (CastValue::TimestampTz(at), BuiltinType::TimestampTz(precision)) => Ok(
511 CastValue::TimestampTz(at.adjust_for_typmod(precision.map(super::TimePrecision::get))),
512 ),
513 (CastValue::Time(time), BuiltinType::Time(precision)) => Ok(CastValue::Time(
514 time.adjust_for_typmod(precision.map(super::TimePrecision::get)),
515 )),
516 (CastValue::TimeTz(time), BuiltinType::Time(precision)) => Ok(CastValue::Time(
518 time.time()
519 .adjust_for_typmod(precision.map(super::TimePrecision::get)),
520 )),
521 (CastValue::TimeTz(time), BuiltinType::TimeTz(precision)) => Ok(CastValue::TimeTz(
522 time.adjust_for_typmod(precision.map(super::TimePrecision::get)),
523 )),
524 (CastValue::Uuid(value), BuiltinType::Uuid) => Ok(CastValue::Uuid(value)),
525 (CastValue::Interval(span), BuiltinType::Time(precision)) => {
527 if !span.is_finite() {
528 return Err(CastError::CannotConvertInfiniteIntervalToTime);
529 }
530 let time = PgTime::from_micros(span.microseconds.rem_euclid(USECS_PER_DAY))
531 .expect("a remainder of a day is a time");
532 Ok(CastValue::Time(time.adjust_for_typmod(
533 precision.map(super::TimePrecision::get),
534 )))
535 }
536 (CastValue::Interval(span), BuiltinType::Interval(typmod)) => {
537 interval_value(span.adjust_for_typmod(typmod))
538 }
539 (CastValue::Time(time), BuiltinType::Interval(typmod)) => {
541 let span = PgInterval {
542 months: 0,
543 days: 0,
544 microseconds: time.micros(),
545 };
546 interval_value(span.adjust_for_typmod(typmod))
547 }
548 _ => Err(cannot_cast),
549 }
550}
551
552impl BuiltinType {
553 const fn takes_integer(self) -> bool {
555 matches!(
556 self,
557 Self::Smallint | Self::Integer | Self::Bigint | Self::Numeric(_)
558 )
559 }
560}
561
562impl CastValue {
563 const fn pg_type(&self) -> BuiltinType {
565 match self {
566 Self::Boolean(_) => BuiltinType::Boolean,
567 Self::Smallint(_) => BuiltinType::Smallint,
568 Self::Integer(_) => BuiltinType::Integer,
569 Self::Bigint(_) => BuiltinType::Bigint,
570 Self::Numeric(_) => BuiltinType::Numeric(None),
571 Self::Text(_) => BuiltinType::Text,
572 Self::Bpchar(_) => BuiltinType::Bpchar(None),
573 Self::Date(_) => BuiltinType::Date,
574 Self::Timestamp(_) => BuiltinType::Timestamp(None),
575 Self::TimestampTz(_) => BuiltinType::TimestampTz(None),
576 Self::Time(_) => BuiltinType::Time(None),
577 Self::TimeTz(_) => BuiltinType::TimeTz(None),
578 Self::Jsonb(_) => BuiltinType::Jsonb,
579 Self::Uuid(_) => BuiltinType::Uuid,
580 Self::Interval(_) => BuiltinType::Interval(super::IntervalTypmod::UNMODIFIED),
581 }
582 }
583}
584
585fn integer(value: i64, target: BuiltinType) -> Result<CastValue, CastError> {
588 if let BuiltinType::Numeric(typmod) = target {
589 return numeric_typmod(PgNumeric::from(value), typmod);
590 }
591 IntegerType::try_from(target)
592 .expect("a target taking an integer is numeric or an integer type")
593 .value(value)
594}
595
596fn numeric_input(text: &str) -> Result<PgNumeric, CastError> {
598 PgNumeric::parse(text).map_err(numeric_input_error)
599}
600
601fn numeric_input_error(error: NumericError) -> CastError {
603 if error == NumericError::InvalidInputSyntax {
604 CastError::InvalidInputSyntax(BuiltinType::Numeric(None))
605 } else {
606 CastError::NumericFormatOverflow
607 }
608}
609
610fn jsonb_input_error(error: JsonbError) -> CastError {
612 match error {
613 JsonbError::Numeric(error) => numeric_input_error(error),
614 error => CastError::Jsonb(error),
615 }
616}
617
618fn interval_value(span: Result<PgInterval, IntervalError>) -> Result<CastValue, CastError> {
620 span.map(CastValue::Interval).map_err(|error| match error {
621 IntervalError::InvalidSyntax => {
622 CastError::InvalidInputSyntax(BuiltinType::Interval(super::IntervalTypmod::UNMODIFIED))
623 }
624 IntervalError::FieldValueOutOfRange => CastError::IntervalFieldValueOutOfRange,
625 IntervalError::OutOfRange => CastError::IntervalOutOfRange,
626 IntervalError::DivisionByZero => unreachable!("no cast divides an interval"),
627 })
628}
629
630enum NumberToken {
632 Integer,
634 Decimal,
636}
637
638fn scan_number(bytes: &[u8]) -> Option<NumberToken> {
641 let (radix, digits) = match bytes {
642 [b'0', b'x' | b'X', digits @ ..] => (16, digits),
643 [b'0', b'o' | b'O', digits @ ..] => (8, digits),
644 [b'0', b'b' | b'B', digits @ ..] => (2, digits),
645 _ => return scan_decimal(bytes),
646 };
647 let mut at = 0;
649 while at < digits.len() {
650 at += usize::from(digits[at] == b'_');
651 if !digits
652 .get(at)
653 .is_some_and(|&b| char::from(b).is_digit(radix))
654 {
655 return None;
656 }
657 at += 1;
658 }
659 (at > 0).then_some(NumberToken::Integer)
660}
661
662fn scan_decimal(bytes: &[u8]) -> Option<NumberToken> {
664 let integer = scan_decinteger(bytes);
665 let mut at = integer;
666 let mut token = NumberToken::Integer;
667 if bytes.get(at) == Some(&b'.') {
668 token = NumberToken::Decimal;
669 at += 1;
670 let fraction = scan_decinteger(&bytes[at..]);
671 if integer == 0 && fraction == 0 {
672 return None;
673 }
674 at += fraction;
675 } else if integer == 0 {
676 return None;
677 }
678 if matches!(bytes.get(at), Some(b'e' | b'E')) {
679 token = NumberToken::Decimal;
680 at += 1;
681 at += usize::from(matches!(bytes.get(at), Some(b'+' | b'-')));
682 let exponent = scan_decinteger(&bytes[at..]);
683 if exponent == 0 {
684 return None;
685 }
686 at += exponent;
687 }
688 (at == bytes.len()).then_some(token)
689}
690
691fn scan_decinteger(bytes: &[u8]) -> usize {
693 if !bytes.first().is_some_and(u8::is_ascii_digit) {
694 return 0;
695 }
696 let mut at = 1;
697 loop {
698 let next = at + usize::from(bytes.get(at) == Some(&b'_'));
699 if !bytes.get(next).is_some_and(u8::is_ascii_digit) {
700 return at;
701 }
702 at = next + 1;
703 }
704}
705
706fn cast_quoted(text: &str, target: BuiltinType) -> Result<CastValue, CastError> {
710 match target {
711 BuiltinType::Interval(typmod) if !text.contains('\0') => {
712 interval_value(parse_interval_typmod(text, typmod))
713 }
714 _ => cast_text(text, target),
715 }
716}
717
718fn cast_text(text: &str, target: BuiltinType) -> Result<CastValue, CastError> {
721 if text.contains('\0') {
723 return Err(CastError::Unsupported);
724 }
725 match target {
726 BuiltinType::Boolean => bool_in(text).map(CastValue::Boolean),
727 BuiltinType::Smallint => int_input(text, IntegerType::Smallint),
728 BuiltinType::Integer => int_input(text, IntegerType::Integer),
729 BuiltinType::Bigint => int_input(text, IntegerType::Bigint),
730 BuiltinType::Numeric(typmod) => numeric_typmod(numeric_input(text)?, typmod),
731 BuiltinType::Text | BuiltinType::Varchar(_) | BuiltinType::Bpchar(_) => {
732 Ok(character(text, target))
733 }
734 BuiltinType::Date => PgDate::parse(text, InputContext::new())
735 .map(CastValue::Date)
736 .map_err(datetime_error),
737 BuiltinType::Timestamp(precision) => PgTimestamp::parse(text, InputContext::new())
738 .map(|at| {
739 CastValue::Timestamp(at.adjust_for_typmod(precision.map(super::TimePrecision::get)))
740 })
741 .map_err(datetime_error),
742 BuiltinType::TimestampTz(precision) => PgTimestampTz::parse(text, InputContext::new())
743 .map(|at| {
744 CastValue::TimestampTz(
745 at.adjust_for_typmod(precision.map(super::TimePrecision::get)),
746 )
747 })
748 .map_err(datetime_error),
749 BuiltinType::Time(precision) => PgTime::parse(text, InputContext::new())
750 .map(|time| {
751 CastValue::Time(time.adjust_for_typmod(precision.map(super::TimePrecision::get)))
752 })
753 .map_err(datetime_error),
754 BuiltinType::TimeTz(precision) => PgTimeTz::parse(text, InputContext::new())
755 .map(|time| {
756 CastValue::TimeTz(time.adjust_for_typmod(precision.map(super::TimePrecision::get)))
757 })
758 .map_err(datetime_error),
759 BuiltinType::Jsonb => PgJsonb::parse(text)
760 .map(CastValue::Jsonb)
761 .map_err(jsonb_input_error),
762 BuiltinType::Uuid => {
763 PgUuid::parse(text)
764 .map(CastValue::Uuid)
765 .map_err(|UuidError::InvalidInputSyntax| {
766 CastError::InvalidInputSyntax(BuiltinType::Uuid)
767 })
768 }
769 BuiltinType::Interval(typmod) => {
770 interval_value(parse_interval(text).and_then(|span| span.adjust_for_typmod(typmod)))
771 }
772 _ => Err(CastError::Unsupported),
773 }
774}
775
776fn numeric_typmod(value: PgNumeric, typmod: Option<NumericTypmod>) -> Result<CastValue, CastError> {
777 match typmod {
778 Some(typmod) => value.apply_typmod(typmod),
779 None => Ok(value),
780 }
781 .map(CastValue::Numeric)
782}
783
784fn character(text: &str, target: BuiltinType) -> CastValue {
787 match target {
788 BuiltinType::Varchar(Some(length)) => CastValue::Text(clip(text, length).into()),
789 BuiltinType::Bpchar(Some(length)) => {
790 let clipped = clip(text, length);
791 let mut padded = String::from(clipped);
792 let blanks = length.0 - clipped.chars().count();
793 padded.extend(core::iter::repeat_n(' ', blanks));
794 CastValue::Bpchar(PgBpchar::new(padded))
795 }
796 BuiltinType::Bpchar(None) => CastValue::Bpchar(PgBpchar::new(String::from(text))),
797 _ => CastValue::Text(text.into()),
798 }
799}
800
801fn clip(text: &str, length: CharLength) -> &str {
803 text.char_indices()
804 .nth(length.0)
805 .map_or(text, |(end, _)| &text[..end])
806}
807
808pub(crate) const fn is_pg_space(byte: u8) -> bool {
810 matches!(byte, b' ' | b'\t' | b'\n' | 0x0B | 0x0C | b'\r')
811}
812
813pub(crate) fn trim_pg_space(bytes: &[u8]) -> &[u8] {
814 let start = bytes.iter().take_while(|&&b| is_pg_space(b)).count();
815 let end = bytes
816 .iter()
817 .rposition(|&b| !is_pg_space(b))
818 .map_or(start, |last| last + 1);
819 &bytes[start..end.max(start)]
820}
821
822fn bool_in(text: &str) -> Result<bool, CastError> {
825 let word = trim_pg_space(text.as_bytes());
826 let abbreviates = |full: &[u8]| {
827 full.get(..word.len())
828 .is_some_and(|prefix| prefix.eq_ignore_ascii_case(word))
829 };
830 let value = match word {
831 [b't' | b'T', ..] if abbreviates(b"true") => true,
832 [b'f' | b'F', ..] if abbreviates(b"false") => false,
833 [b'y' | b'Y', ..] if abbreviates(b"yes") => true,
834 [b'n' | b'N', ..] if abbreviates(b"no") => false,
835 [b'o' | b'O', _, ..] if abbreviates(b"on") => true,
836 [b'o' | b'O', _, ..] if abbreviates(b"off") => false,
837 b"1" => true,
838 b"0" => false,
839 _ => return Err(CastError::InvalidInputSyntax(BuiltinType::Boolean)),
840 };
841 Ok(value)
842}
843
844enum IntInputError {
846 Syntax,
847 Range,
848}
849
850fn int_input(text: &str, integer: IntegerType) -> Result<CastValue, CastError> {
852 let value = int_in(text, integer).map_err(|error| match error {
853 IntInputError::Syntax => CastError::InvalidInputSyntax(integer.into()),
854 IntInputError::Range => CastError::ValueOutOfRange(integer.into()),
855 })?;
856 Ok(integer
857 .value(value)
858 .expect("int_in kept the value in the type's range"))
859}
860
861fn int_in(text: &str, integer: IntegerType) -> Result<i64, IntInputError> {
865 let bytes = text.as_bytes();
866 let mut at = bytes.iter().take_while(|&&b| is_pg_space(b)).count();
867 let negative = bytes.get(at) == Some(&b'-');
868 at += usize::from(matches!(bytes.get(at), Some(b'+' | b'-')));
869 let radix = match (bytes.get(at), bytes.get(at + 1)) {
870 (Some(b'0'), Some(b'x' | b'X')) => 16,
871 (Some(b'0'), Some(b'o' | b'O')) => 8,
872 (Some(b'0'), Some(b'b' | b'B')) => 2,
873 _ => 10,
874 };
875 if radix != 10 {
876 at += 2;
877 }
878 let first_digit = at;
879 let is_digit = |byte: Option<&u8>| byte.is_some_and(|&b| char::from(b).is_digit(radix));
880 let limit = integer.range().start().unsigned_abs();
882 let mut magnitude: u64 = 0;
883 loop {
884 match bytes.get(at) {
885 Some(&byte) if is_digit(Some(&byte)) => {
886 if magnitude > limit / u64::from(radix) {
887 return Err(IntInputError::Range);
888 }
889 let digit = char::from(byte).to_digit(radix).expect("checked a digit");
890 magnitude = magnitude * u64::from(radix) + u64::from(digit);
891 at += 1;
892 }
893 Some(b'_') => {
894 if radix == 10 && at == first_digit {
895 return Err(IntInputError::Syntax);
896 }
897 at += 1;
898 if !is_digit(bytes.get(at)) {
899 return Err(IntInputError::Syntax);
900 }
901 }
902 _ => break,
903 }
904 }
905 if at == first_digit || !bytes[at..].iter().all(|&b| is_pg_space(b)) {
906 return Err(IntInputError::Syntax);
907 }
908 let value = if negative {
909 -i128::from(magnitude)
910 } else {
911 i128::from(magnitude)
912 };
913 i64::try_from(value)
914 .ok()
915 .filter(|value| integer.range().contains(value))
916 .ok_or(IntInputError::Range)
917}
918
919fn datetime_error(error: DateTimeError) -> CastError {
921 match error {
922 DateTimeError::FieldValueOutOfRange => CastError::DateTimeFieldOutOfRange,
923 DateTimeError::TimeZoneDisplacementOutOfRange => CastError::TimeZoneDisplacementOutOfRange,
924 DateTimeError::DateOutOfRange => CastError::DateOutOfRange,
925 DateTimeError::TimestampOutOfRange => CastError::TimestampOutOfRange,
926
927 DateTimeError::InvalidInputSyntax(pg_type) => CastError::InvalidInputSyntax(pg_type),
928 DateTimeError::TimestampCannotBeNaN
929 | DateTimeError::OutsideJiffRange
930 | DateTimeError::NeedsTimeZone
931 | DateTimeError::NeedsDateOrder
932 | DateTimeError::NeedsCurrentTime
933 | DateTimeError::TimeZoneNotRecognized => CastError::Unsupported,
934 }
935}
936
937impl fmt::Display for CastValue {
940 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
941 match self {
942 Self::Boolean(value) => f.write_str(if *value { "t" } else { "f" }),
943 Self::Smallint(value) => write!(f, "{value}"),
944 Self::Integer(value) => write!(f, "{value}"),
945 Self::Bigint(value) => write!(f, "{value}"),
946 Self::Numeric(value) => write!(f, "{value}"),
947 Self::Text(text) => f.write_str(text),
948 Self::Bpchar(value) => write!(f, "{value}"),
949 Self::Date(date) => write!(f, "{date}"),
950 Self::Timestamp(at) => write!(f, "{at}"),
951 Self::TimestampTz(at) => write!(f, "{at}"),
952 Self::Time(time) => write!(f, "{time}"),
953 Self::TimeTz(time) => write!(f, "{time}"),
954 Self::Jsonb(value) => write!(f, "{value}"),
955 Self::Uuid(value) => write!(f, "{value}"),
956 Self::Interval(span) => write!(f, "{span}"),
957 }
958 }
959}