//! Utilities
use std::fmt::Write;
use std::fmt::{self, Display};

pub trait TqlQuote {
    fn tql_quote(&self) -> impl Display;
}

impl TqlQuote for &str {
    fn tql_quote(&self) -> impl Display {
        TqlQuotedStr(self)
    }
}

pub struct TqlQuotedStr<'a>(pub &'a str);

impl Display for TqlQuotedStr<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_char('"')?;
        for c in self.0.chars() {
            match c {
                '\n' => f.write_str(r#"\n"#)?,
                '\r' => f.write_str(r#"\r"#)?,
                '\\' => f.write_str(r#"\\"#)?,
                '"' => f.write_str(r#"\""#)?,
                c => f.write_char(c)?,
            }
        }
        f.write_char('"')
    }
}
