use std::str;
use mz_ore::fmt::FormatBuffer;
use mz_repr::adt::char::Char;
use mz_repr::adt::system::PgLegacyChar;
use mz_repr::adt::varchar::{VarChar, VarCharMaxLength};
use crate::EvalError;
pub fn format_pg_legacy_char<B>(buf: &mut B, c: u8) -> Result<(), EvalError>
where
B: FormatBuffer,
{
match str::from_utf8(&[c]) {
Ok(s) => {
buf.write_str(s);
Ok(())
}
Err(_) => Err(EvalError::InvalidByteSequence {
byte_sequence: format!("{:#02x}", c).into(),
encoding_name: "UTF8".into(),
}),
}
}
sqlfunc!(
#[sqlname = "\"char\"_to_text"]
#[preserves_uniqueness = true]
#[inverse = to_unary!(super::CastStringToPgLegacyChar)]
fn cast_pg_legacy_char_to_string(a: PgLegacyChar) -> Result<String, EvalError> {
let mut buf = String::new();
format_pg_legacy_char(&mut buf, a.0)?;
Ok(buf)
}
);
sqlfunc!(
#[sqlname = "\"char\"_to_char"]
#[preserves_uniqueness = true]
#[inverse = to_unary!(super::CastStringToPgLegacyChar)]
fn cast_pg_legacy_char_to_char(a: PgLegacyChar) -> Result<Char<String>, EvalError> {
let mut buf = String::new();
format_pg_legacy_char(&mut buf, a.0)?;
Ok(Char(buf))
}
);
sqlfunc!(
#[sqlname = "\"char\"_to_varchar"]
#[preserves_uniqueness = true]
#[inverse = to_unary!(super::CastStringToVarChar{fail_on_len: false, length: Some(VarCharMaxLength::try_from(1).unwrap())})]
fn cast_pg_legacy_char_to_var_char(a: PgLegacyChar) -> Result<VarChar<String>, EvalError> {
let mut buf = String::new();
format_pg_legacy_char(&mut buf, a.0)?;
Ok(VarChar(buf))
}
);
sqlfunc!(
#[sqlname = "\"char\"_to_integer"]
#[preserves_uniqueness = true]
#[inverse = to_unary!(super::CastInt32ToPgLegacyChar)]
fn cast_pg_legacy_char_to_int32(a: PgLegacyChar) -> i32 {
i32::from(i8::from_ne_bytes([a.0]))
}
);