use core::fmt::{self, Write};
use super::BuiltinType;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShowType {
Never,
IfNeeded,
Always,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConstExprContext<'a> {
pub standard_conforming_strings: bool,
pub collation: Option<&'a str>,
}
impl Default for ConstExprContext<'_> {
fn default() -> Self {
Self {
standard_conforming_strings: true,
collation: None,
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct ConstExpr<'a> {
output: Option<&'a str>,
target: BuiltinType,
show_type: ShowType,
context: ConstExprContext<'a>,
}
impl<'a> ConstExpr<'a> {
#[must_use]
pub fn new(output: Option<&'a str>, target: BuiltinType, show_type: ShowType) -> Self {
Self {
output,
target,
show_type,
context: ConstExprContext::default(),
}
}
#[must_use]
pub const fn with_context(mut self, context: ConstExprContext<'a>) -> Self {
self.context = context;
self
}
#[must_use]
pub fn needs_type_label(&self) -> bool {
self.decoration().1
}
fn decoration(&self) -> (bool, bool) {
let (quoted, needed) = match self.output {
Some(output) => match self.target {
BuiltinType::Boolean => (false, false),
BuiltinType::Integer if !output.starts_with('-') => (false, false),
BuiltinType::Numeric(modifier)
if output.as_bytes().first().is_some_and(u8::is_ascii_digit)
&& output.contains(['e', 'E', '.']) =>
{
(false, modifier.is_some())
}
_ => (true, self.target != BuiltinType::Unknown),
},
None => (false, true),
};
(
quoted,
match self.show_type {
ShowType::Never => false,
ShowType::IfNeeded => needed,
ShowType::Always => true,
},
)
}
}
impl fmt::Display for ConstExpr<'_> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let (quoted, needs_label) = self.decoration();
if let Some(output) = self.output {
if quoted {
quote_literal(formatter, output, self.context.standard_conforming_strings)?;
} else if self.target == BuiltinType::Boolean {
formatter.write_str(if output == "t" { "true" } else { "false" })?;
} else {
formatter.write_str(output)?;
}
} else {
formatter.write_str("NULL")?;
}
if needs_label {
write!(formatter, "::{}", self.target)?;
}
if self.show_type != ShowType::Never
&& let Some(collation) = self.context.collation
{
write!(formatter, " COLLATE {collation}")?;
}
Ok(())
}
}
fn quote_literal(
formatter: &mut fmt::Formatter<'_>,
output: &str,
standard_strings: bool,
) -> fmt::Result {
formatter.write_char('\'')?;
let mut start = 0;
for (index, character) in output.char_indices() {
if character == '\'' || (character == '\\' && !standard_strings) {
formatter.write_str(&output[start..index])?;
formatter.write_char(character)?;
start = index;
}
}
formatter.write_str(&output[start..])?;
formatter.write_char('\'')
}