use alloc::string::{String, ToString};
use core::fmt;
use crate::{
datetime::{DateTimeError, InputContext, PgDate, PgTimestamp, PgTimestampTz},
numeric::{NumericTypmod, PgNumeric},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Literal<'a> {
Quoted(&'a str),
Number(&'a str),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CastTarget {
Boolean,
Smallint,
Integer,
Bigint,
Numeric(Option<NumericTypmod>),
Text,
Varchar(Option<CharLength>),
Bpchar(Option<CharLength>),
Date,
Timestamp(Option<u8>),
TimestampTz(Option<u8>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct CharLength(usize);
const MAX_CHAR_LENGTH: usize = 10_485_760;
impl CharLength {
#[must_use]
pub fn new(length: usize) -> Option<Self> {
(1..=MAX_CHAR_LENGTH)
.contains(&length)
.then_some(Self(length))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum PgType {
Boolean,
Smallint,
Integer,
Bigint,
Numeric,
Text,
Varchar,
Bpchar,
Date,
Timestamp,
TimestampTz,
Time,
TimeTz,
}
impl fmt::Display for PgType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
impl PgType {
const fn name(self) -> &'static str {
match self {
Self::Boolean => "boolean",
Self::Smallint => "smallint",
Self::Integer => "integer",
Self::Bigint => "bigint",
Self::Numeric => "numeric",
Self::Text => "text",
Self::Varchar => "character varying",
Self::Bpchar => "character",
Self::Date => "date",
Self::Timestamp => "timestamp without time zone",
Self::TimestampTz => "timestamp with time zone",
Self::Time => "time without time zone",
Self::TimeTz => "time with time zone",
}
}
pub(crate) const fn input_name(self) -> &'static str {
match self {
Self::Timestamp => "timestamp",
Self::Time => "time",
other => other.name(),
}
}
}
impl CastTarget {
#[must_use]
pub const fn pg_type(self) -> PgType {
match self {
Self::Boolean => PgType::Boolean,
Self::Smallint => PgType::Smallint,
Self::Integer => PgType::Integer,
Self::Bigint => PgType::Bigint,
Self::Numeric(_) => PgType::Numeric,
Self::Text => PgType::Text,
Self::Varchar(_) => PgType::Varchar,
Self::Bpchar(_) => PgType::Bpchar,
Self::Date => PgType::Date,
Self::Timestamp(_) => PgType::Timestamp,
Self::TimestampTz(_) => PgType::TimestampTz,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum CastValue {
Boolean(bool),
Smallint(i16),
Integer(i32),
Bigint(i64),
Numeric(PgNumeric),
Text(String),
Bpchar(String),
Date(PgDate),
Timestamp(PgTimestamp),
TimestampTz(PgTimestampTz),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, thiserror::Error)]
#[non_exhaustive]
pub enum CastError {
#[error("invalid input syntax for type {}", .0.input_name())]
InvalidInputSyntax(PgType),
#[error("value is out of range for type {0}")]
ValueOutOfRange(PgType),
#[error("{0} out of range")]
OutOfRange(PgType),
#[error("numeric field overflow")]
NumericFieldOverflow,
#[error("value overflows numeric format")]
NumericFormatOverflow,
#[error("date/time field value out of range")]
DateTimeFieldOutOfRange,
#[error("date out of range")]
DateOutOfRange,
#[error("timestamp out of range")]
TimestampOutOfRange,
#[error("time zone displacement out of range")]
TimeZoneDisplacementOutOfRange,
#[error("cannot cast type {from} to {to}")]
CannotCast {
from: PgType,
to: PgType,
},
#[error("cast not modelled")]
Unsupported,
}
pub fn cast_literal(literal: Literal<'_>, target: CastTarget) -> Result<CastValue, CastError> {
match literal {
Literal::Quoted(text) => cast_quoted(text, target),
Literal::Number(text) => cast_constant(Constant::read(text)?, target),
}
}
enum Constant {
Integer(i32),
Bigint(i64),
Numeric(PgNumeric),
}
impl Constant {
fn read(text: &str) -> Result<Self, CastError> {
let unsigned = text.strip_prefix('-').unwrap_or(text);
match scan_number(unsigned.as_bytes()) {
None => Err(CastError::Unsupported),
Some(NumberToken::Integer) => {
if let Ok(value) = int_in(text, 32) {
Ok(Self::Integer(narrow(value)))
} else if let Ok(value) = int_in(text, 64) {
Ok(Self::Bigint(value))
} else {
PgNumeric::parse(text).map(Self::Numeric)
}
}
Some(NumberToken::Decimal) => PgNumeric::parse(text).map(Self::Numeric),
}
}
const fn pg_type(&self) -> PgType {
match self {
Self::Integer(_) => PgType::Integer,
Self::Bigint(_) => PgType::Bigint,
Self::Numeric(_) => PgType::Numeric,
}
}
fn into_i64(self) -> Option<i64> {
match self {
Self::Integer(value) => Some(i64::from(value)),
Self::Bigint(value) => Some(value),
Self::Numeric(value) => value.into_i64_rounded(),
}
}
}
enum NumberToken {
Integer,
Decimal,
}
fn scan_number(bytes: &[u8]) -> Option<NumberToken> {
let (radix, digits) = match bytes {
[b'0', b'x' | b'X', digits @ ..] => (16, digits),
[b'0', b'o' | b'O', digits @ ..] => (8, digits),
[b'0', b'b' | b'B', digits @ ..] => (2, digits),
_ => return scan_decimal(bytes),
};
let mut at = 0;
while at < digits.len() {
at += usize::from(digits[at] == b'_');
if !digits
.get(at)
.is_some_and(|&b| char::from(b).is_digit(radix))
{
return None;
}
at += 1;
}
(at > 0).then_some(NumberToken::Integer)
}
fn scan_decimal(bytes: &[u8]) -> Option<NumberToken> {
let integer = scan_decinteger(bytes);
let mut at = integer;
let mut token = NumberToken::Integer;
if bytes.get(at) == Some(&b'.') {
token = NumberToken::Decimal;
at += 1;
let fraction = scan_decinteger(&bytes[at..]);
if integer == 0 && fraction == 0 {
return None;
}
at += fraction;
} else if integer == 0 {
return None;
}
if matches!(bytes.get(at), Some(b'e' | b'E')) {
token = NumberToken::Decimal;
at += 1;
at += usize::from(matches!(bytes.get(at), Some(b'+' | b'-')));
let exponent = scan_decinteger(&bytes[at..]);
if exponent == 0 {
return None;
}
at += exponent;
}
(at == bytes.len()).then_some(token)
}
fn scan_decinteger(bytes: &[u8]) -> usize {
if !bytes.first().is_some_and(u8::is_ascii_digit) {
return 0;
}
let mut at = 1;
loop {
let next = at + usize::from(bytes.get(at) == Some(&b'_'));
if !bytes.get(next).is_some_and(u8::is_ascii_digit) {
return at;
}
at = next + 1;
}
}
fn cast_constant(constant: Constant, target: CastTarget) -> Result<CastValue, CastError> {
let from = constant.pg_type();
match target {
CastTarget::Boolean => match constant {
Constant::Integer(value) => Ok(CastValue::Boolean(value != 0)),
_ => Err(CastError::CannotCast {
from,
to: PgType::Boolean,
}),
},
CastTarget::Smallint => {
let value = constant.into_i64().and_then(|v| i16::try_from(v).ok());
value
.map(CastValue::Smallint)
.ok_or(CastError::OutOfRange(PgType::Smallint))
}
CastTarget::Integer => {
let value = constant.into_i64().and_then(|v| i32::try_from(v).ok());
value
.map(CastValue::Integer)
.ok_or(CastError::OutOfRange(PgType::Integer))
}
CastTarget::Bigint => constant
.into_i64()
.map(CastValue::Bigint)
.ok_or(CastError::OutOfRange(PgType::Bigint)),
CastTarget::Numeric(typmod) => {
let value = match constant {
Constant::Integer(value) => PgNumeric::from_i64(i64::from(value)),
Constant::Bigint(value) => PgNumeric::from_i64(value),
Constant::Numeric(value) => value,
};
numeric_typmod(value, typmod)
}
CastTarget::Text | CastTarget::Varchar(_) | CastTarget::Bpchar(_) => {
let text = match constant {
Constant::Integer(value) => value.to_string(),
Constant::Bigint(value) => value.to_string(),
Constant::Numeric(value) => value.to_string(),
};
Ok(character(&text, target))
}
CastTarget::Date | CastTarget::Timestamp(_) | CastTarget::TimestampTz(_) => {
Err(CastError::CannotCast {
from,
to: target.pg_type(),
})
}
}
}
fn cast_quoted(text: &str, target: CastTarget) -> Result<CastValue, CastError> {
if text.contains('\0') {
return Err(CastError::Unsupported);
}
match target {
CastTarget::Boolean => bool_in(text).map(CastValue::Boolean),
CastTarget::Smallint => int_input(text, 16, PgType::Smallint).map(|v| {
CastValue::Smallint(i16::try_from(v).expect("int_in kept the value in 16 bits"))
}),
CastTarget::Integer => {
int_input(text, 32, PgType::Integer).map(|v| CastValue::Integer(narrow(v)))
}
CastTarget::Bigint => int_input(text, 64, PgType::Bigint).map(CastValue::Bigint),
CastTarget::Numeric(typmod) => numeric_typmod(PgNumeric::parse(text)?, typmod),
CastTarget::Text | CastTarget::Varchar(_) | CastTarget::Bpchar(_) => {
Ok(character(text, target))
}
CastTarget::Date => PgDate::parse(text, InputContext::new())
.map(CastValue::Date)
.map_err(datetime_error),
CastTarget::Timestamp(precision) => {
let at = PgTimestamp::parse(text, InputContext::new()).map_err(datetime_error)?;
let micros = adjust_timestamp_for_typmod(at.pg_micros(), precision);
Ok(CastValue::Timestamp(PgTimestamp::from_stored(micros)))
}
CastTarget::TimestampTz(precision) => {
let at = PgTimestampTz::parse(text, InputContext::new()).map_err(datetime_error)?;
let micros = adjust_timestamp_for_typmod(at.pg_micros(), precision);
Ok(CastValue::TimestampTz(PgTimestampTz::from_stored(micros)))
}
}
}
fn narrow(value: i64) -> i32 {
i32::try_from(value).expect("int_in kept the value in 32 bits")
}
fn numeric_typmod(value: PgNumeric, typmod: Option<NumericTypmod>) -> Result<CastValue, CastError> {
match typmod {
Some(typmod) => value.apply_typmod(typmod),
None => Ok(value),
}
.map(CastValue::Numeric)
}
fn character(text: &str, target: CastTarget) -> CastValue {
match target {
CastTarget::Varchar(Some(length)) => CastValue::Text(clip(text, length).into()),
CastTarget::Bpchar(Some(length)) => {
let clipped = clip(text, length);
let mut padded = String::from(clipped);
let blanks = length.0 - clipped.chars().count();
padded.extend(core::iter::repeat_n(' ', blanks));
CastValue::Bpchar(padded)
}
CastTarget::Bpchar(None) => CastValue::Bpchar(text.into()),
_ => CastValue::Text(text.into()),
}
}
fn clip(text: &str, length: CharLength) -> &str {
text.char_indices()
.nth(length.0)
.map_or(text, |(end, _)| &text[..end])
}
pub(crate) const fn is_pg_space(byte: u8) -> bool {
matches!(byte, b' ' | b'\t' | b'\n' | 0x0B | 0x0C | b'\r')
}
pub(crate) fn trim_pg_space(bytes: &[u8]) -> &[u8] {
let start = bytes.iter().take_while(|&&b| is_pg_space(b)).count();
let end = bytes
.iter()
.rposition(|&b| !is_pg_space(b))
.map_or(start, |last| last + 1);
&bytes[start..end.max(start)]
}
fn bool_in(text: &str) -> Result<bool, CastError> {
let word = trim_pg_space(text.as_bytes());
let abbreviates = |full: &[u8]| {
full.get(..word.len())
.is_some_and(|prefix| prefix.eq_ignore_ascii_case(word))
};
let value = match word {
[b't' | b'T', ..] if abbreviates(b"true") => true,
[b'f' | b'F', ..] if abbreviates(b"false") => false,
[b'y' | b'Y', ..] if abbreviates(b"yes") => true,
[b'n' | b'N', ..] if abbreviates(b"no") => false,
[b'o' | b'O', _, ..] if abbreviates(b"on") => true,
[b'o' | b'O', _, ..] if abbreviates(b"off") => false,
b"1" => true,
b"0" => false,
_ => return Err(CastError::InvalidInputSyntax(PgType::Boolean)),
};
Ok(value)
}
enum IntInputError {
Syntax,
Range,
}
fn int_input(text: &str, bits: u32, pg_type: PgType) -> Result<i64, CastError> {
int_in(text, bits).map_err(|error| match error {
IntInputError::Syntax => CastError::InvalidInputSyntax(pg_type),
IntInputError::Range => CastError::ValueOutOfRange(pg_type),
})
}
fn int_in(text: &str, bits: u32) -> Result<i64, IntInputError> {
let bytes = text.as_bytes();
let mut at = bytes.iter().take_while(|&&b| is_pg_space(b)).count();
let negative = bytes.get(at) == Some(&b'-');
at += usize::from(matches!(bytes.get(at), Some(b'+' | b'-')));
let radix = match (bytes.get(at), bytes.get(at + 1)) {
(Some(b'0'), Some(b'x' | b'X')) => 16,
(Some(b'0'), Some(b'o' | b'O')) => 8,
(Some(b'0'), Some(b'b' | b'B')) => 2,
_ => 10,
};
if radix != 10 {
at += 2;
}
let first_digit = at;
let is_digit = |byte: Option<&u8>| byte.is_some_and(|&b| char::from(b).is_digit(radix));
let limit: u64 = 1 << (bits - 1);
let mut magnitude: u64 = 0;
loop {
match bytes.get(at) {
Some(&byte) if is_digit(Some(&byte)) => {
if magnitude > limit / u64::from(radix) {
return Err(IntInputError::Range);
}
let digit = char::from(byte).to_digit(radix).expect("checked a digit");
magnitude = magnitude * u64::from(radix) + u64::from(digit);
at += 1;
}
Some(b'_') => {
if radix == 10 && at == first_digit {
return Err(IntInputError::Syntax);
}
at += 1;
if !is_digit(bytes.get(at)) {
return Err(IntInputError::Syntax);
}
}
_ => break,
}
}
if at == first_digit || !bytes[at..].iter().all(|&b| is_pg_space(b)) {
return Err(IntInputError::Syntax);
}
let value = if negative {
-i128::from(magnitude)
} else {
i128::from(magnitude)
};
let range = -i128::from(limit)..i128::from(limit);
if range.contains(&value) {
Ok(i64::try_from(value).expect("a value within 64 bits fits i64"))
} else {
Err(IntInputError::Range)
}
}
fn adjust_timestamp_for_typmod(micros: i64, precision: Option<u8>) -> i64 {
let Some(precision @ 0..6) = precision else {
return micros;
};
if micros == i64::MAX || micros == i64::MIN {
return micros;
}
let scale = 10i64.pow(6 - u32::from(precision));
let offset = scale / 2;
if micros >= 0 {
(micros + offset) / scale * scale
} else {
-((-micros + offset) / scale * scale)
}
}
fn datetime_error(error: DateTimeError) -> CastError {
match error {
DateTimeError::FieldValueOutOfRange => CastError::DateTimeFieldOutOfRange,
DateTimeError::TimeZoneDisplacementOutOfRange => CastError::TimeZoneDisplacementOutOfRange,
DateTimeError::DateOutOfRange => CastError::DateOutOfRange,
DateTimeError::TimestampOutOfRange => CastError::TimestampOutOfRange,
DateTimeError::InvalidInputSyntax(pg_type) => CastError::InvalidInputSyntax(pg_type),
DateTimeError::OutsideJiffRange
| DateTimeError::NeedsTimeZone
| DateTimeError::NeedsDateOrder
| DateTimeError::NeedsCurrentTime
| DateTimeError::TimeZoneNotRecognized => CastError::Unsupported,
}
}
impl fmt::Display for CastValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Boolean(value) => f.write_str(if *value { "t" } else { "f" }),
Self::Smallint(value) => write!(f, "{value}"),
Self::Integer(value) => write!(f, "{value}"),
Self::Bigint(value) => write!(f, "{value}"),
Self::Numeric(value) => write!(f, "{value}"),
Self::Text(text) | Self::Bpchar(text) => f.write_str(text),
Self::Date(date) => write!(f, "{date}"),
Self::Timestamp(at) => write!(f, "{at}"),
Self::TimestampTz(at) => write!(f, "{at}"),
}
}
}