1use alloc::string::{String, ToString};
6use core::fmt;
7
8use super::{
9 bpchar::PgBpchar,
10 datetime::{
11 DateTimeError, InputContext, PgDate, PgTime, PgTimeTz, PgTimestamp, PgTimestampTz,
12 USECS_PER_DAY,
13 },
14 integer::IntegerType,
15 interval::{IntervalError, IntervalTypmod, PgInterval, parse_interval, parse_interval_typmod},
16 jsonb::{JsonbError, JsonbKind, PgJsonb},
17 numeric::{NumericError, NumericTypmod, PgNumeric},
18 uuid::{PgUuid, UuidError},
19};
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
23pub enum Literal<'a> {
24 Quoted(&'a str),
27 Number(&'a str),
31}
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
35pub enum CastTarget {
36 Boolean,
38 Smallint,
40 Integer,
42 Bigint,
44 Numeric(Option<NumericTypmod>),
46 Text,
48 Varchar(Option<CharLength>),
50 Bpchar(Option<CharLength>),
52 Date,
54 Timestamp(Option<u8>),
56 TimestampTz(Option<u8>),
58 Time(Option<u8>),
60 TimeTz(Option<u8>),
62 Jsonb,
64 Uuid,
66 Interval(IntervalTypmod),
69}
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73pub struct CharLength(usize);
74
75const MAX_CHAR_LENGTH: usize = 10_485_760;
77
78impl CharLength {
79 #[must_use]
89 pub fn new(length: usize) -> Option<Self> {
90 (1..=MAX_CHAR_LENGTH)
91 .contains(&length)
92 .then_some(Self(length))
93 }
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
107#[non_exhaustive]
108pub enum PgType {
109 Boolean,
111 Smallint,
113 Integer,
115 Bigint,
117 Numeric,
119 Text,
121 Varchar,
123 Bpchar,
125 Date,
127 Timestamp,
129 TimestampTz,
131 Time,
133 TimeTz,
135 Jsonb,
137 Interval,
139 Uuid,
141}
142
143impl fmt::Display for PgType {
144 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145 f.write_str(self.name())
146 }
147}
148
149impl PgType {
150 const fn name(self) -> &'static str {
152 match self {
153 Self::Boolean => "boolean",
154 Self::Smallint => "smallint",
155 Self::Integer => "integer",
156 Self::Bigint => "bigint",
157 Self::Numeric => "numeric",
158 Self::Text => "text",
159 Self::Varchar => "character varying",
160 Self::Bpchar => "character",
161 Self::Date => "date",
162 Self::Timestamp => "timestamp without time zone",
163 Self::TimestampTz => "timestamp with time zone",
164 Self::Time => "time without time zone",
165 Self::TimeTz => "time with time zone",
166 Self::Jsonb => "jsonb",
167 Self::Interval => "interval",
168 Self::Uuid => "uuid",
169 }
170 }
171
172 pub(crate) const fn input_name(self) -> &'static str {
175 match self {
176 Self::Timestamp => "timestamp",
177 Self::Time => "time",
178 other => other.name(),
179 }
180 }
181}
182
183impl CastTarget {
184 #[must_use]
186 pub const fn pg_type(self) -> PgType {
187 match self {
188 Self::Boolean => PgType::Boolean,
189 Self::Smallint => PgType::Smallint,
190 Self::Integer => PgType::Integer,
191 Self::Bigint => PgType::Bigint,
192 Self::Numeric(_) => PgType::Numeric,
193 Self::Text => PgType::Text,
194 Self::Varchar(_) => PgType::Varchar,
195 Self::Bpchar(_) => PgType::Bpchar,
196 Self::Date => PgType::Date,
197 Self::Timestamp(_) => PgType::Timestamp,
198 Self::TimestampTz(_) => PgType::TimestampTz,
199 Self::Time(_) => PgType::Time,
200 Self::TimeTz(_) => PgType::TimeTz,
201 Self::Jsonb => PgType::Jsonb,
202 Self::Uuid => PgType::Uuid,
203 Self::Interval(_) => PgType::Interval,
204 }
205 }
206}
207
208#[derive(Debug, Clone, PartialEq, Eq, Hash)]
211pub enum CastValue {
212 Boolean(bool),
214 Smallint(i16),
216 Integer(i32),
218 Bigint(i64),
220 Numeric(PgNumeric),
222 Text(String),
224 Bpchar(PgBpchar<'static>),
227 Date(PgDate),
229 Timestamp(PgTimestamp),
231 TimestampTz(PgTimestampTz),
233 Time(PgTime),
235 TimeTz(PgTimeTz),
237 Jsonb(PgJsonb),
239 Uuid(PgUuid),
241 Interval(PgInterval),
244}
245
246#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
249#[non_exhaustive]
250pub enum CastError {
251 #[error("invalid input syntax for type {}", .0.input_name())]
253 InvalidInputSyntax(PgType),
254 #[error("value is out of range for type {0}")]
256 ValueOutOfRange(PgType),
257 #[error("{0} out of range")]
259 OutOfRange(PgType),
260 #[error("cannot convert NaN to {0}")]
262 CannotConvertNaN(PgType),
263 #[error("cannot convert infinity to {0}")]
265 CannotConvertInfinity(PgType),
266 #[error("numeric field overflow")]
269 NumericFieldOverflow,
270 #[error("value overflows numeric format")]
272 NumericFormatOverflow,
273 #[error("date/time field value out of range")]
275 DateTimeFieldOutOfRange,
276 #[error("date out of range")]
278 DateOutOfRange,
279 #[error("timestamp out of range")]
281 TimestampOutOfRange,
282 #[error("date out of range for timestamp")]
284 DateOutOfRangeForTimestamp,
285 #[error("time zone displacement out of range")]
287 TimeZoneDisplacementOutOfRange,
288 #[error("interval field value out of range")]
290 IntervalFieldValueOutOfRange,
291 #[error("interval out of range")]
293 IntervalOutOfRange,
294 #[error("cannot convert infinite interval to time")]
296 CannotConvertInfiniteIntervalToTime,
297 #[error("cannot cast type {from} to {to}")]
299 CannotCast {
300 from: PgType,
302 to: PgType,
304 },
305 #[error("cannot cast jsonb {from} to type {to}")]
308 CannotCastJsonb {
309 from: JsonbKind,
311 to: PgType,
313 },
314 #[error(transparent)]
316 Jsonb(JsonbError),
317 #[error("malformed array literal")]
319 MalformedArrayLiteral,
320 #[error("number of array dimensions exceeds the maximum allowed (6)")]
322 ArrayDimensionsExceeded,
323 #[error("upper bound cannot be less than lower bound")]
325 UpperBoundLessThanLower,
326 #[error("array upper bound is too large: {0}")]
328 ArrayUpperBoundTooLarge(i32),
329 #[error("array size exceeds the maximum allowed (134217727)")]
331 ArraySizeExceeded,
332 #[error("array bound is out of integer range")]
334 ArrayBoundOutOfRange,
335 #[error("cast not modelled")]
342 Unsupported,
343}
344
345pub fn cast_literal(literal: Literal<'_>, target: CastTarget) -> Result<CastValue, CastError> {
433 match literal {
434 Literal::Quoted(text) => cast_quoted(text, target),
435 Literal::Number(text) => cast_non_null(number_constant(text)?, target),
436 }
437}
438
439pub fn number_constant(text: &str) -> Result<CastValue, CastError> {
460 let unsigned = text.strip_prefix('-').unwrap_or(text);
461 match scan_number(unsigned.as_bytes()) {
462 None => Err(CastError::Unsupported),
463 Some(NumberToken::Integer) => [IntegerType::Integer, IntegerType::Bigint]
464 .into_iter()
465 .find_map(|integer| int_input(text, integer).ok())
466 .map_or_else(|| numeric_input(text).map(CastValue::Numeric), Ok),
467 Some(NumberToken::Decimal) => numeric_input(text).map(CastValue::Numeric),
468 }
469}
470
471pub fn cast_value(value: CastValue, target: CastTarget) -> Result<Option<CastValue>, CastError> {
549 match (value, target) {
550 (CastValue::Jsonb(value), _) => cast_jsonb(value, target),
551 (CastValue::Timestamp(at), CastTarget::Time(precision)) => Ok(at
553 .time()
554 .map(|time| CastValue::Time(time.adjust_for_typmod(precision)))),
555 (value, _) => cast_non_null(value, target).map(Some),
556 }
557}
558
559fn cast_jsonb(value: PgJsonb, target: CastTarget) -> Result<Option<CastValue>, CastError> {
561 let to = target.pg_type();
562 let cannot_cast = |from| CastError::CannotCastJsonb { from, to };
563 match target {
564 CastTarget::Boolean => Ok(value
565 .to_bool()
566 .map_err(cannot_cast)?
567 .map(CastValue::Boolean)),
568 CastTarget::Smallint
569 | CastTarget::Integer
570 | CastTarget::Bigint
571 | CastTarget::Numeric(_) => value
572 .into_numeric()
573 .map_err(cannot_cast)?
574 .map(|number| cast_non_null(CastValue::Numeric(number), target))
575 .transpose(),
576 CastTarget::Text | CastTarget::Varchar(_) | CastTarget::Bpchar(_) => {
577 Ok(Some(character(&value.to_string(), target)))
578 }
579 CastTarget::Jsonb => Ok(Some(CastValue::Jsonb(value))),
580 CastTarget::Date
581 | CastTarget::Timestamp(_)
582 | CastTarget::TimestampTz(_)
583 | CastTarget::Time(_)
584 | CastTarget::TimeTz(_)
585 | CastTarget::Uuid
586 | CastTarget::Interval(_) => Err(CastError::CannotCast {
587 from: PgType::Jsonb,
588 to,
589 }),
590 }
591}
592
593fn cast_non_null(value: CastValue, target: CastTarget) -> Result<CastValue, CastError> {
596 let cannot_cast = CastError::CannotCast {
597 from: value.pg_type(),
598 to: target.pg_type(),
599 };
600 match (value, target) {
601 (CastValue::Text(text), _) => cast_text(&text, target),
602 (CastValue::Bpchar(value), CastTarget::Text | CastTarget::Varchar(_)) => {
604 Ok(character(value.as_text(), target))
605 }
606 (CastValue::Bpchar(value), _) => cast_text(value.as_str(), target),
607 (
608 CastValue::TimestampTz(_),
609 CastTarget::Date
610 | CastTarget::Timestamp(_)
611 | CastTarget::Time(_)
612 | CastTarget::TimeTz(_)
613 | CastTarget::Text
614 | CastTarget::Varchar(_)
615 | CastTarget::Bpchar(_),
616 )
617 | (CastValue::Date(_) | CastValue::Timestamp(_), CastTarget::TimestampTz(_))
618 | (CastValue::Time(_), CastTarget::TimeTz(_)) => Err(CastError::Unsupported),
619 (
621 CastValue::Boolean(value),
622 CastTarget::Text | CastTarget::Varchar(_) | CastTarget::Bpchar(_),
623 ) => Ok(character(if value { "true" } else { "false" }, target)),
624 (value, CastTarget::Text | CastTarget::Varchar(_) | CastTarget::Bpchar(_)) => {
625 Ok(character(&value.to_string(), target))
626 }
627 (CastValue::Boolean(value), CastTarget::Boolean) => Ok(CastValue::Boolean(value)),
628 (CastValue::Boolean(value), CastTarget::Integer) => Ok(CastValue::Integer(value.into())),
629 (CastValue::Integer(value), CastTarget::Boolean) => Ok(CastValue::Boolean(value != 0)),
630 (CastValue::Smallint(value), _) if target.takes_integer() => integer(value.into(), target),
631 (CastValue::Integer(value), _) if target.takes_integer() => integer(value.into(), target),
632 (CastValue::Bigint(value), _) if target.takes_integer() => integer(value, target),
633 (CastValue::Numeric(value), CastTarget::Numeric(typmod)) => numeric_typmod(value, typmod),
634 (CastValue::Numeric(value), _) if target.takes_integer() => {
635 let to = target.pg_type();
636 if value.is_nan() {
637 Err(CastError::CannotConvertNaN(to))
638 } else if value.is_infinite() {
639 Err(CastError::CannotConvertInfinity(to))
640 } else {
641 let value = value.into_i64_rounded().ok_or(CastError::OutOfRange(to))?;
642 integer(value, target)
643 }
644 }
645 (CastValue::Date(date), CastTarget::Date) => Ok(CastValue::Date(date)),
646 (CastValue::Date(date), CastTarget::Timestamp(precision)) => {
647 let at = date
649 .to_timestamp()
650 .map_err(|_| CastError::DateOutOfRangeForTimestamp)?;
651 Ok(CastValue::Timestamp(at.adjust_for_typmod(precision)))
652 }
653 (CastValue::Timestamp(at), CastTarget::Date) => Ok(CastValue::Date(at.date())),
654 (CastValue::Timestamp(at), CastTarget::Timestamp(precision)) => {
655 Ok(CastValue::Timestamp(at.adjust_for_typmod(precision)))
656 }
657 (CastValue::TimestampTz(at), CastTarget::TimestampTz(precision)) => {
658 Ok(CastValue::TimestampTz(at.adjust_for_typmod(precision)))
659 }
660 (CastValue::Time(time), CastTarget::Time(precision)) => {
661 Ok(CastValue::Time(time.adjust_for_typmod(precision)))
662 }
663 (CastValue::TimeTz(time), CastTarget::Time(precision)) => {
665 Ok(CastValue::Time(time.time().adjust_for_typmod(precision)))
666 }
667 (CastValue::TimeTz(time), CastTarget::TimeTz(precision)) => {
668 Ok(CastValue::TimeTz(time.adjust_for_typmod(precision)))
669 }
670 (CastValue::Uuid(value), CastTarget::Uuid) => Ok(CastValue::Uuid(value)),
671 (CastValue::Interval(span), CastTarget::Time(precision)) => {
673 if !span.is_finite() {
674 return Err(CastError::CannotConvertInfiniteIntervalToTime);
675 }
676 let time = PgTime::from_micros(span.microseconds.rem_euclid(USECS_PER_DAY))
677 .expect("a remainder of a day is a time");
678 Ok(CastValue::Time(time.adjust_for_typmod(precision)))
679 }
680 (CastValue::Interval(span), CastTarget::Interval(typmod)) => {
681 interval_value(span.adjust_for_typmod(typmod))
682 }
683 (CastValue::Time(time), CastTarget::Interval(typmod)) => {
685 let span = PgInterval {
686 months: 0,
687 days: 0,
688 microseconds: time.micros(),
689 };
690 interval_value(span.adjust_for_typmod(typmod))
691 }
692 _ => Err(cannot_cast),
693 }
694}
695
696impl CastTarget {
697 const fn takes_integer(self) -> bool {
699 matches!(
700 self,
701 Self::Smallint | Self::Integer | Self::Bigint | Self::Numeric(_)
702 )
703 }
704}
705
706impl CastValue {
707 const fn pg_type(&self) -> PgType {
709 match self {
710 Self::Boolean(_) => PgType::Boolean,
711 Self::Smallint(_) => PgType::Smallint,
712 Self::Integer(_) => PgType::Integer,
713 Self::Bigint(_) => PgType::Bigint,
714 Self::Numeric(_) => PgType::Numeric,
715 Self::Text(_) => PgType::Text,
716 Self::Bpchar(_) => PgType::Bpchar,
717 Self::Date(_) => PgType::Date,
718 Self::Timestamp(_) => PgType::Timestamp,
719 Self::TimestampTz(_) => PgType::TimestampTz,
720 Self::Time(_) => PgType::Time,
721 Self::TimeTz(_) => PgType::TimeTz,
722 Self::Jsonb(_) => PgType::Jsonb,
723 Self::Uuid(_) => PgType::Uuid,
724 Self::Interval(_) => PgType::Interval,
725 }
726 }
727}
728
729fn integer(value: i64, target: CastTarget) -> Result<CastValue, CastError> {
732 if let CastTarget::Numeric(typmod) = target {
733 return numeric_typmod(PgNumeric::from(value), typmod);
734 }
735 IntegerType::try_from(target)
736 .expect("a target taking an integer is numeric or an integer type")
737 .value(value)
738}
739
740fn numeric_input(text: &str) -> Result<PgNumeric, CastError> {
742 PgNumeric::parse(text).map_err(numeric_input_error)
743}
744
745fn numeric_input_error(error: NumericError) -> CastError {
747 if error == NumericError::InvalidInputSyntax {
748 CastError::InvalidInputSyntax(PgType::Numeric)
749 } else {
750 CastError::NumericFormatOverflow
751 }
752}
753
754fn jsonb_input_error(error: JsonbError) -> CastError {
756 match error {
757 JsonbError::Numeric(error) => numeric_input_error(error),
758 error => CastError::Jsonb(error),
759 }
760}
761
762fn interval_value(span: Result<PgInterval, IntervalError>) -> Result<CastValue, CastError> {
764 span.map(CastValue::Interval).map_err(|error| match error {
765 IntervalError::InvalidSyntax => CastError::InvalidInputSyntax(PgType::Interval),
766 IntervalError::FieldValueOutOfRange => CastError::IntervalFieldValueOutOfRange,
767 IntervalError::OutOfRange => CastError::IntervalOutOfRange,
768 IntervalError::DivisionByZero => unreachable!("no cast divides an interval"),
769 })
770}
771
772enum NumberToken {
774 Integer,
776 Decimal,
778}
779
780fn scan_number(bytes: &[u8]) -> Option<NumberToken> {
783 let (radix, digits) = match bytes {
784 [b'0', b'x' | b'X', digits @ ..] => (16, digits),
785 [b'0', b'o' | b'O', digits @ ..] => (8, digits),
786 [b'0', b'b' | b'B', digits @ ..] => (2, digits),
787 _ => return scan_decimal(bytes),
788 };
789 let mut at = 0;
791 while at < digits.len() {
792 at += usize::from(digits[at] == b'_');
793 if !digits
794 .get(at)
795 .is_some_and(|&b| char::from(b).is_digit(radix))
796 {
797 return None;
798 }
799 at += 1;
800 }
801 (at > 0).then_some(NumberToken::Integer)
802}
803
804fn scan_decimal(bytes: &[u8]) -> Option<NumberToken> {
806 let integer = scan_decinteger(bytes);
807 let mut at = integer;
808 let mut token = NumberToken::Integer;
809 if bytes.get(at) == Some(&b'.') {
810 token = NumberToken::Decimal;
811 at += 1;
812 let fraction = scan_decinteger(&bytes[at..]);
813 if integer == 0 && fraction == 0 {
814 return None;
815 }
816 at += fraction;
817 } else if integer == 0 {
818 return None;
819 }
820 if matches!(bytes.get(at), Some(b'e' | b'E')) {
821 token = NumberToken::Decimal;
822 at += 1;
823 at += usize::from(matches!(bytes.get(at), Some(b'+' | b'-')));
824 let exponent = scan_decinteger(&bytes[at..]);
825 if exponent == 0 {
826 return None;
827 }
828 at += exponent;
829 }
830 (at == bytes.len()).then_some(token)
831}
832
833fn scan_decinteger(bytes: &[u8]) -> usize {
835 if !bytes.first().is_some_and(u8::is_ascii_digit) {
836 return 0;
837 }
838 let mut at = 1;
839 loop {
840 let next = at + usize::from(bytes.get(at) == Some(&b'_'));
841 if !bytes.get(next).is_some_and(u8::is_ascii_digit) {
842 return at;
843 }
844 at = next + 1;
845 }
846}
847
848fn cast_quoted(text: &str, target: CastTarget) -> Result<CastValue, CastError> {
852 match target {
853 CastTarget::Interval(typmod) if !text.contains('\0') => {
854 interval_value(parse_interval_typmod(text, typmod))
855 }
856 _ => cast_text(text, target),
857 }
858}
859
860fn cast_text(text: &str, target: CastTarget) -> Result<CastValue, CastError> {
863 if text.contains('\0') {
865 return Err(CastError::Unsupported);
866 }
867 match target {
868 CastTarget::Boolean => bool_in(text).map(CastValue::Boolean),
869 CastTarget::Smallint => int_input(text, IntegerType::Smallint),
870 CastTarget::Integer => int_input(text, IntegerType::Integer),
871 CastTarget::Bigint => int_input(text, IntegerType::Bigint),
872 CastTarget::Numeric(typmod) => numeric_typmod(numeric_input(text)?, typmod),
873 CastTarget::Text | CastTarget::Varchar(_) | CastTarget::Bpchar(_) => {
874 Ok(character(text, target))
875 }
876 CastTarget::Date => PgDate::parse(text, InputContext::new())
877 .map(CastValue::Date)
878 .map_err(datetime_error),
879 CastTarget::Timestamp(precision) => PgTimestamp::parse(text, InputContext::new())
880 .map(|at| CastValue::Timestamp(at.adjust_for_typmod(precision)))
881 .map_err(datetime_error),
882 CastTarget::TimestampTz(precision) => PgTimestampTz::parse(text, InputContext::new())
883 .map(|at| CastValue::TimestampTz(at.adjust_for_typmod(precision)))
884 .map_err(datetime_error),
885 CastTarget::Time(precision) => PgTime::parse(text, InputContext::new())
886 .map(|time| CastValue::Time(time.adjust_for_typmod(precision)))
887 .map_err(datetime_error),
888 CastTarget::TimeTz(precision) => PgTimeTz::parse(text, InputContext::new())
889 .map(|time| CastValue::TimeTz(time.adjust_for_typmod(precision)))
890 .map_err(datetime_error),
891 CastTarget::Jsonb => PgJsonb::parse(text)
892 .map(CastValue::Jsonb)
893 .map_err(jsonb_input_error),
894 CastTarget::Uuid => PgUuid::parse(text)
895 .map(CastValue::Uuid)
896 .map_err(|UuidError::InvalidInputSyntax| CastError::InvalidInputSyntax(PgType::Uuid)),
897 CastTarget::Interval(typmod) => {
898 interval_value(parse_interval(text).and_then(|span| span.adjust_for_typmod(typmod)))
899 }
900 }
901}
902
903fn numeric_typmod(value: PgNumeric, typmod: Option<NumericTypmod>) -> Result<CastValue, CastError> {
904 match typmod {
905 Some(typmod) => value.apply_typmod(typmod),
906 None => Ok(value),
907 }
908 .map(CastValue::Numeric)
909}
910
911fn character(text: &str, target: CastTarget) -> CastValue {
914 match target {
915 CastTarget::Varchar(Some(length)) => CastValue::Text(clip(text, length).into()),
916 CastTarget::Bpchar(Some(length)) => {
917 let clipped = clip(text, length);
918 let mut padded = String::from(clipped);
919 let blanks = length.0 - clipped.chars().count();
920 padded.extend(core::iter::repeat_n(' ', blanks));
921 CastValue::Bpchar(PgBpchar::new(padded))
922 }
923 CastTarget::Bpchar(None) => CastValue::Bpchar(PgBpchar::new(String::from(text))),
924 _ => CastValue::Text(text.into()),
925 }
926}
927
928fn clip(text: &str, length: CharLength) -> &str {
930 text.char_indices()
931 .nth(length.0)
932 .map_or(text, |(end, _)| &text[..end])
933}
934
935pub(crate) const fn is_pg_space(byte: u8) -> bool {
937 matches!(byte, b' ' | b'\t' | b'\n' | 0x0B | 0x0C | b'\r')
938}
939
940pub(crate) fn trim_pg_space(bytes: &[u8]) -> &[u8] {
941 let start = bytes.iter().take_while(|&&b| is_pg_space(b)).count();
942 let end = bytes
943 .iter()
944 .rposition(|&b| !is_pg_space(b))
945 .map_or(start, |last| last + 1);
946 &bytes[start..end.max(start)]
947}
948
949fn bool_in(text: &str) -> Result<bool, CastError> {
952 let word = trim_pg_space(text.as_bytes());
953 let abbreviates = |full: &[u8]| {
954 full.get(..word.len())
955 .is_some_and(|prefix| prefix.eq_ignore_ascii_case(word))
956 };
957 let value = match word {
958 [b't' | b'T', ..] if abbreviates(b"true") => true,
959 [b'f' | b'F', ..] if abbreviates(b"false") => false,
960 [b'y' | b'Y', ..] if abbreviates(b"yes") => true,
961 [b'n' | b'N', ..] if abbreviates(b"no") => false,
962 [b'o' | b'O', _, ..] if abbreviates(b"on") => true,
963 [b'o' | b'O', _, ..] if abbreviates(b"off") => false,
964 b"1" => true,
965 b"0" => false,
966 _ => return Err(CastError::InvalidInputSyntax(PgType::Boolean)),
967 };
968 Ok(value)
969}
970
971enum IntInputError {
973 Syntax,
974 Range,
975}
976
977fn int_input(text: &str, integer: IntegerType) -> Result<CastValue, CastError> {
979 let value = int_in(text, integer).map_err(|error| match error {
980 IntInputError::Syntax => CastError::InvalidInputSyntax(integer.into()),
981 IntInputError::Range => CastError::ValueOutOfRange(integer.into()),
982 })?;
983 Ok(integer
984 .value(value)
985 .expect("int_in kept the value in the type's range"))
986}
987
988fn int_in(text: &str, integer: IntegerType) -> Result<i64, IntInputError> {
992 let bytes = text.as_bytes();
993 let mut at = bytes.iter().take_while(|&&b| is_pg_space(b)).count();
994 let negative = bytes.get(at) == Some(&b'-');
995 at += usize::from(matches!(bytes.get(at), Some(b'+' | b'-')));
996 let radix = match (bytes.get(at), bytes.get(at + 1)) {
997 (Some(b'0'), Some(b'x' | b'X')) => 16,
998 (Some(b'0'), Some(b'o' | b'O')) => 8,
999 (Some(b'0'), Some(b'b' | b'B')) => 2,
1000 _ => 10,
1001 };
1002 if radix != 10 {
1003 at += 2;
1004 }
1005 let first_digit = at;
1006 let is_digit = |byte: Option<&u8>| byte.is_some_and(|&b| char::from(b).is_digit(radix));
1007 let limit = integer.range().start().unsigned_abs();
1009 let mut magnitude: u64 = 0;
1010 loop {
1011 match bytes.get(at) {
1012 Some(&byte) if is_digit(Some(&byte)) => {
1013 if magnitude > limit / u64::from(radix) {
1014 return Err(IntInputError::Range);
1015 }
1016 let digit = char::from(byte).to_digit(radix).expect("checked a digit");
1017 magnitude = magnitude * u64::from(radix) + u64::from(digit);
1018 at += 1;
1019 }
1020 Some(b'_') => {
1021 if radix == 10 && at == first_digit {
1022 return Err(IntInputError::Syntax);
1023 }
1024 at += 1;
1025 if !is_digit(bytes.get(at)) {
1026 return Err(IntInputError::Syntax);
1027 }
1028 }
1029 _ => break,
1030 }
1031 }
1032 if at == first_digit || !bytes[at..].iter().all(|&b| is_pg_space(b)) {
1033 return Err(IntInputError::Syntax);
1034 }
1035 let value = if negative {
1036 -i128::from(magnitude)
1037 } else {
1038 i128::from(magnitude)
1039 };
1040 i64::try_from(value)
1041 .ok()
1042 .filter(|value| integer.range().contains(value))
1043 .ok_or(IntInputError::Range)
1044}
1045
1046fn datetime_error(error: DateTimeError) -> CastError {
1048 match error {
1049 DateTimeError::FieldValueOutOfRange => CastError::DateTimeFieldOutOfRange,
1050 DateTimeError::TimeZoneDisplacementOutOfRange => CastError::TimeZoneDisplacementOutOfRange,
1051 DateTimeError::DateOutOfRange => CastError::DateOutOfRange,
1052 DateTimeError::TimestampOutOfRange => CastError::TimestampOutOfRange,
1053
1054 DateTimeError::InvalidInputSyntax(pg_type) => CastError::InvalidInputSyntax(pg_type),
1055 DateTimeError::TimestampCannotBeNaN
1056 | DateTimeError::OutsideJiffRange
1057 | DateTimeError::NeedsTimeZone
1058 | DateTimeError::NeedsDateOrder
1059 | DateTimeError::NeedsCurrentTime
1060 | DateTimeError::TimeZoneNotRecognized => CastError::Unsupported,
1061 }
1062}
1063
1064impl fmt::Display for CastValue {
1067 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1068 match self {
1069 Self::Boolean(value) => f.write_str(if *value { "t" } else { "f" }),
1070 Self::Smallint(value) => write!(f, "{value}"),
1071 Self::Integer(value) => write!(f, "{value}"),
1072 Self::Bigint(value) => write!(f, "{value}"),
1073 Self::Numeric(value) => write!(f, "{value}"),
1074 Self::Text(text) => f.write_str(text),
1075 Self::Bpchar(value) => write!(f, "{value}"),
1076 Self::Date(date) => write!(f, "{date}"),
1077 Self::Timestamp(at) => write!(f, "{at}"),
1078 Self::TimestampTz(at) => write!(f, "{at}"),
1079 Self::Time(time) => write!(f, "{time}"),
1080 Self::TimeTz(time) => write!(f, "{time}"),
1081 Self::Jsonb(value) => write!(f, "{value}"),
1082 Self::Uuid(value) => write!(f, "{value}"),
1083 Self::Interval(span) => write!(f, "{span}"),
1084 }
1085 }
1086}