use std::fmt::Write;
use chrono::{Datelike, NaiveDate, NaiveDateTime, Timelike};
use crate::temporal::Duration;
use crate::{HawDBError, Result, ValueRef};
const MICROS_PER_SECOND: u128 = 1_000_000;
const MICROS_PER_MINUTE: u128 = 60 * MICROS_PER_SECOND;
const MICROS_PER_HOUR: u128 = 60 * MICROS_PER_MINUTE;
pub(super) fn rendered_len(value: ValueRef<'_>) -> Result<usize> {
let mut counter = ByteCounter(0);
write_value(&mut counter, value)?;
Ok(counter.0)
}
pub(super) fn render(value: ValueRef<'_>, len: usize) -> Result<String> {
let mut out = String::with_capacity(len);
write_value(&mut out, value)?;
debug_assert_eq!(out.len(), len, "rendered_len must be exact");
Ok(out)
}
struct ByteCounter(usize);
impl Write for ByteCounter {
fn write_str(&mut self, text: &str) -> std::fmt::Result {
self.0 = self.0.checked_add(text.len()).ok_or(std::fmt::Error)?;
Ok(())
}
}
fn put<W: Write>(out: &mut W, text: &str) -> Result<()> {
out.write_str(text).map_err(text_too_long)
}
fn put_fmt<W: Write>(out: &mut W, arguments: std::fmt::Arguments<'_>) -> Result<()> {
out.write_fmt(arguments).map_err(text_too_long)
}
fn text_too_long(_: std::fmt::Error) -> HawDBError {
HawDBError::Execution("string() result length overflows usize".to_owned())
}
fn write_value<W: Write>(out: &mut W, value: ValueRef<'_>) -> Result<()> {
match value {
ValueRef::Null => {}
ValueRef::Bool(value) => put(out, if value { "True" } else { "False" })?,
ValueRef::Int(value) => put_fmt(out, format_args!("{value}"))?,
ValueRef::Float(value) => write_float(out, value)?,
ValueRef::String(value) => put(out, value)?,
ValueRef::Binary(bytes) => write_blob(out, bytes)?,
ValueRef::Uuid(value) => put_fmt(out, format_args!("{}", value.hyphenated()))?,
ValueRef::Vector(vector) => {
put(out, "[")?;
for (index, coordinate) in vector.coordinates().enumerate() {
if index > 0 {
put(out, ",")?;
}
write_float(out, f64::from(coordinate))?;
}
put(out, "]")?;
}
ValueRef::List(values) => {
put(out, "[")?;
for (index, value) in values.iter().enumerate() {
if index > 0 {
put(out, ",")?;
}
write_value(out, value.as_ref())?;
}
put(out, "]")?;
}
ValueRef::Map(entries) => {
put(out, "{")?;
for (index, (key, value)) in entries.iter().enumerate() {
if index > 0 {
put(out, ", ")?;
}
put(out, key)?;
put(out, ": ")?;
write_value(out, value.as_ref())?;
}
put(out, "}")?;
}
ValueRef::Date(date) => write_date(out, date)?,
ValueRef::LocalDateTime(value) => write_timestamp(out, value)?,
ValueRef::DateTime(value) => write_timestamp(out, value.naive_utc())?,
ValueRef::Duration(value) => write_interval(out, value)?,
ValueRef::Decimal(_) | ValueRef::LocalTime(_) => {
return Err(HawDBError::Execution(format!(
"string() has no Kùzu-compatible text for a {} value",
super::type_name(value)
)))
}
}
Ok(())
}
fn write_float<W: Write>(out: &mut W, value: f64) -> Result<()> {
if value.is_nan() {
put(
out,
if value.is_sign_negative() {
"-nan"
} else {
"nan"
},
)
} else if value.is_infinite() {
put(out, if value > 0.0 { "inf" } else { "-inf" })
} else {
put_fmt(out, format_args!("{value:.6}"))
}
}
fn write_blob<W: Write>(out: &mut W, bytes: &[u8]) -> Result<()> {
for &byte in bytes {
if (0x20..=0x7e).contains(&byte) && !matches!(byte, b'\\' | b'\'' | b'"') {
out.write_char(char::from(byte)).map_err(text_too_long)?;
} else {
put_fmt(out, format_args!("\\x{byte:02X}"))?;
}
}
Ok(())
}
fn write_date<W: Write>(out: &mut W, date: NaiveDate) -> Result<()> {
let year = date.year();
let (year, era) = if year <= 0 {
(1 - i64::from(year), " (BC)")
} else {
(i64::from(year), "")
};
put_fmt(
out,
format_args!("{year:04}-{:02}-{:02}{era}", date.month(), date.day()),
)
}
fn write_timestamp<W: Write>(out: &mut W, value: NaiveDateTime) -> Result<()> {
write_date(out, value.date())?;
put_fmt(
out,
format_args!(
" {:02}:{:02}:{:02}",
value.hour(),
value.minute(),
value.second()
),
)?;
write_micros_fraction(out, (value.nanosecond() % 1_000_000_000) / 1_000)
}
fn write_micros_fraction<W: Write>(out: &mut W, micros: u32) -> Result<()> {
if micros == 0 {
return Ok(());
}
let (mut digits, mut width) = (micros, 6);
while digits % 10 == 0 {
digits /= 10;
width -= 1;
}
put_fmt(out, format_args!(".{digits:0width$}"))
}
fn write_interval<W: Write>(out: &mut W, duration: &Duration) -> Result<()> {
let mut first = true;
let mut separate = |out: &mut W| {
let separator = if first { "" } else { " " };
first = false;
put(out, separator)
};
for (count, unit) in [
(duration.months / 12, "year"),
(duration.months % 12, "month"),
(duration.days, "day"),
] {
if count != 0 {
separate(out)?;
let plural = if count == 1 { "" } else { "s" };
put_fmt(out, format_args!("{count} {unit}{plural}"))?;
}
}
let micros = duration.time_nanos() / 1_000;
if micros != 0 {
separate(out)?;
if micros < 0 {
put(out, "-")?;
}
let micros = micros.unsigned_abs();
let hours = micros / MICROS_PER_HOUR;
let minutes = micros % MICROS_PER_HOUR / MICROS_PER_MINUTE;
let seconds = micros % MICROS_PER_MINUTE / MICROS_PER_SECOND;
put_fmt(out, format_args!("{hours:02}:{minutes:02}:{seconds:02}"))?;
write_micros_fraction(
out,
u32::try_from(micros % MICROS_PER_SECOND).expect("below one second"),
)?;
} else if first {
put(out, "00:00:00")?;
}
Ok(())
}