use std::fmt;
use std::fmt::Write;
use std::io;
use crate::Value;
pub(crate) type DynFormatter = dyn Fn(&mut Formatter<'_>, &Value) -> Result + Sync + Send + 'static;
pub struct Formatter<'a> {
buf: &'a mut (dyn fmt::Write + 'a),
}
pub type Result = std::result::Result<(), Error>;
#[derive(Debug, Clone)]
pub struct Error(Option<String>);
pub(crate) struct Writer<W> {
writer: W,
err: Option<io::Error>,
}
impl<'a> Formatter<'a> {
pub(crate) fn with_string(buf: &'a mut String) -> Self {
Self { buf }
}
pub(crate) fn with_writer<W>(buf: &'a mut Writer<W>) -> Self
where
W: io::Write,
{
Self { buf }
}
}
impl fmt::Write for Formatter<'_> {
#[inline]
fn write_str(&mut self, s: &str) -> fmt::Result {
fmt::Write::write_str(self.buf, s)
}
#[inline]
fn write_char(&mut self, c: char) -> fmt::Result {
fmt::Write::write_char(self.buf, c)
}
#[inline]
fn write_fmt(&mut self, args: fmt::Arguments<'_>) -> fmt::Result {
fmt::Write::write_fmt(self.buf, args)
}
}
impl Error {
pub(crate) fn message(self) -> Option<String> {
self.0
}
}
impl std::error::Error for Error {}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.0 {
Some(msg) => write!(f, "{msg}"),
None => write!(f, "format error"),
}
}
}
impl From<&str> for Error {
fn from(msg: &str) -> Self {
Self(Some(msg.to_owned()))
}
}
impl From<String> for Error {
fn from(msg: String) -> Self {
Self(Some(msg))
}
}
impl From<fmt::Error> for Error {
fn from(_: fmt::Error) -> Self {
Self(None)
}
}
impl<W> Writer<W>
where
W: io::Write,
{
pub fn new(writer: W) -> Self {
Self { writer, err: None }
}
pub fn take_err(&mut self) -> Option<io::Error> {
self.err.take()
}
}
impl<W> fmt::Write for Writer<W>
where
W: io::Write,
{
#[inline]
fn write_str(&mut self, s: &str) -> fmt::Result {
self.writer.write_all(s.as_bytes()).map_err(|e| {
self.err = Some(e);
fmt::Error
})
}
#[inline]
fn write_char(&mut self, c: char) -> fmt::Result {
self.writer
.write_all(c.encode_utf8(&mut [0; 4]).as_bytes())
.map_err(|e| {
self.err = Some(e);
fmt::Error
})
}
}
#[inline]
pub fn default(f: &mut Formatter<'_>, value: &Value) -> Result {
match value {
Value::None => {}
Value::Bool(b) => write!(f, "{b}")?,
Value::Integer(n) => write!(f, "{n}")?,
Value::Float(n) => write!(f, "{n}")?,
Value::String(s) => write!(f, "{s}")?,
value => {
return Err(Error::from(format!(
"expression evaluated to unformattable type {}",
value.human()
)));
}
}
Ok(())
}