#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Delimiter {
Comma,
Tab,
Pipe,
}
impl Delimiter {
#[must_use]
pub fn as_char(self) -> char {
match self {
Delimiter::Comma => ',',
Delimiter::Tab => '\t',
Delimiter::Pipe => '|',
}
}
}
fn is_toon_number(s: &str) -> bool {
if s.is_empty() || s == "-" || s == "+" || s == "." {
return false;
}
if is_non_finite_literal(s) {
return false;
}
if is_hex_literal(s) {
return true;
}
s.parse::<f64>().is_ok()
}
fn is_hex_literal(s: &str) -> bool {
let body = s.strip_prefix('-').unwrap_or(s);
let Some(hex) = body.strip_prefix("0x").or_else(|| body.strip_prefix("0X")) else {
return false;
};
!hex.is_empty() && hex.bytes().all(|b| b.is_ascii_hexdigit())
}
fn is_non_finite_literal(s: &str) -> bool {
let bytes = s.as_bytes();
let body = if let Some(&b'+' | &b'-') = bytes.first() { &bytes[1..] } else { bytes };
if body.eq_ignore_ascii_case(b"inf") || body.eq_ignore_ascii_case(b"infinity") {
return true;
}
if body.eq_ignore_ascii_case(b"nan") {
return true;
}
false
}
#[must_use]
pub fn needs_quotes(s: &str, delim: Delimiter) -> bool {
if s.is_empty() {
return true;
}
if s.starts_with(' ') || s.ends_with(' ') {
return true;
}
if matches!(s, "true" | "false" | "null") {
return true;
}
if is_toon_number(s) {
return true;
}
match s.as_bytes()[0] {
b'-' | b'[' | b'{' | b'#' => return true,
_ => {}
}
let delim_char = delim.as_char();
for ch in s.chars() {
if ch == '"' || ch == '\\' || (ch as u32) < 0x20 {
return true;
}
if ch == delim_char {
return true;
}
if ch == ':' || ch == ' ' {
return true;
}
}
false
}
pub fn escape_into(out: &mut String, s: &str) {
for ch in s.chars() {
match ch {
'\\' => out.push_str("\\\\"),
'"' => out.push_str("\\\""),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => {
use std::fmt::Write as _;
let _ = write!(out, "\\u{:04x}", c as u32);
}
c => out.push(c),
}
}
}
pub fn emit_scalar_string(out: &mut String, s: &str, delim: Delimiter) {
if needs_quotes(s, delim) {
out.push('"');
escape_into(out, s);
out.push('"');
} else {
out.push_str(s);
}
}
pub fn emit_number(out: &mut String, n: &serde_json::Number) {
use std::fmt::Write as _;
let _ = write!(out, "{n}");
}
#[must_use]
pub fn emit_json_scalar(out: &mut String, v: &serde_json::Value, delim: Delimiter) -> bool {
use serde_json::Value;
match v {
Value::Null => {
out.push_str("null");
true
}
Value::Bool(b) => {
out.push_str(if *b { "true" } else { "false" });
true
}
Value::Number(n) => {
emit_number(out, n);
true
}
Value::String(s) => {
emit_scalar_string(out, s, delim);
true
}
Value::Array(_) | Value::Object(_) => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn plain_word_unquoted() {
assert!(!needs_quotes("hello", Delimiter::Comma));
assert!(!needs_quotes("a-b-c", Delimiter::Comma)); }
#[test]
fn reserved_and_numeric_quoted() {
assert!(needs_quotes("true", Delimiter::Comma));
assert!(needs_quotes("42", Delimiter::Comma));
assert!(needs_quotes("-1.5", Delimiter::Comma));
assert!(needs_quotes("0x0", Delimiter::Comma));
assert!(needs_quotes("-0xBEEF", Delimiter::Comma));
assert!(!needs_quotes("0xG", Delimiter::Comma));
}
#[test]
fn delimiter_and_structure_quoted() {
assert!(needs_quotes("a,b", Delimiter::Comma));
assert!(!needs_quotes("a,b", Delimiter::Pipe)); assert!(needs_quotes("a|b", Delimiter::Pipe));
assert!(needs_quotes(" leading", Delimiter::Comma));
assert!(needs_quotes("", Delimiter::Comma));
}
#[test]
fn escape_only_spec_chars() {
let mut s = String::new();
escape_into(&mut s, "a\"b\\c\nd\te");
assert_eq!(s, "a\\\"b\\\\c\\nd\\te");
}
#[test]
fn emit_quotes_when_needed() {
let mut s = String::new();
emit_scalar_string(&mut s, "true", Delimiter::Comma);
assert_eq!(s, "\"true\"");
let mut s2 = String::new();
emit_scalar_string(&mut s2, "hello", Delimiter::Comma);
assert_eq!(s2, "hello");
}
#[test]
fn numbers_canonical() {
let mut s = String::new();
emit_number(&mut s, &serde_json::Number::from(42));
assert_eq!(s, "42");
let mut s2 = String::new();
emit_number(&mut s2, &serde_json::Number::from_f64(1.5).unwrap());
assert_eq!(s2, "1.5");
let mut s3 = String::new();
emit_number(&mut s3, &serde_json::Number::from_f64(11.0).unwrap());
assert_eq!(s3, "11.0");
let mut s4 = String::new();
emit_number(&mut s4, &serde_json::Number::from_f64(0.0).unwrap());
assert_eq!(s4, "0.0");
let mut s5 = String::new();
emit_number(&mut s5, &serde_json::Number::from_f64(-0.0).unwrap());
assert_eq!(s5, "-0.0");
}
#[test]
fn scalar_dispatch() {
let mut s = String::new();
assert!(emit_json_scalar(&mut s, &serde_json::json!(true), Delimiter::Comma));
assert_eq!(s, "true");
let mut s2 = String::new();
assert!(!emit_json_scalar(&mut s2, &serde_json::json!({"a":1}), Delimiter::Comma));
assert!(s2.is_empty());
}
}