pub trait JsonElement {
fn push_json(&self, out: &mut String);
}
impl<T: JsonElement + ?Sized> JsonElement for &T {
#[inline]
fn push_json(&self, out: &mut String) {
T::push_json(self, out);
}
}
pub fn json_elements<T: JsonElement>(items: &[T]) -> String {
let mut out = String::from("[");
for (i, item) in items.iter().enumerate() {
if i > 0 {
out.push(',');
}
item.push_json(&mut out);
}
out.push(']');
out
}
fn push_json_string(out: &mut String, text: &str) {
use core::fmt::Write;
out.push('"');
for ch in text.chars() {
match ch {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
ch if (ch as u32) < 0x20 => {
let _ = write!(out, "\\u{:04x}", ch as u32);
}
ch => out.push(ch),
}
}
out.push('"');
}
fn push_hex(out: &mut String, bytes: &[u8]) {
const HEX: &[u8; 16] = b"0123456789abcdef";
out.push('"');
for &byte in bytes {
out.push(char::from(HEX[usize::from(byte >> 4)]));
out.push(char::from(HEX[usize::from(byte & 0x0f)]));
}
out.push('"');
}
macro_rules! json_number {
($( $ty:ty ),+ $(,)?) => {
$(
impl JsonElement for $ty {
#[inline]
fn push_json(&self, out: &mut String) {
use core::fmt::Write;
let _ = write!(out, "{self}");
}
}
)+
};
}
macro_rules! json_quoted_number {
($( $ty:ty ),+ $(,)?) => {
$(
impl JsonElement for $ty {
#[inline]
fn push_json(&self, out: &mut String) {
use core::fmt::Write;
out.push('"');
let _ = write!(out, "{self}");
out.push('"');
}
}
)+
};
}
json_number!(i8, i16, i32, i64, u8, u16, u32, f64);
json_quoted_number!(u64, u128, i128);
impl JsonElement for bool {
#[inline]
fn push_json(&self, out: &mut String) {
out.push_str(if *self { "true" } else { "false" });
}
}
impl JsonElement for f32 {
#[inline]
fn push_json(&self, out: &mut String) {
f64::from(*self).push_json(out);
}
}
impl<S: crate::ConfidenceCarrier + JsonElement> JsonElement for crate::Confidence<S> {
#[inline]
fn push_json(&self, out: &mut String) {
self.get().push_json(out);
}
}
impl JsonElement for str {
#[inline]
fn push_json(&self, out: &mut String) {
push_json_string(out, self);
}
}
impl JsonElement for String {
#[inline]
fn push_json(&self, out: &mut String) {
push_json_string(out, self);
}
}
impl JsonElement for [u8] {
#[inline]
fn push_json(&self, out: &mut String) {
push_hex(out, self);
}
}
impl JsonElement for Vec<u8> {
#[inline]
fn push_json(&self, out: &mut String) {
push_hex(out, self);
}
}
impl<const N: usize> JsonElement for [u8; N] {
#[inline]
fn push_json(&self, out: &mut String) {
push_hex(out, self);
}
}
#[cfg(feature = "smol_str")]
impl JsonElement for smol_str::SmolStr {
#[inline]
fn push_json(&self, out: &mut String) {
push_json_string(out, self);
}
}
impl JsonElement for bytes::Bytes {
#[inline]
fn push_json(&self, out: &mut String) {
push_hex(out, self);
}
}
#[cfg(test)]
mod tests;