use serde_json::Value;
pub fn json_kind(v: &Value) -> &'static str {
match v {
Value::Null => "null",
Value::Bool(_) => "boolean",
Value::Number(_) => "number",
Value::String(_) => "string",
Value::Array(_) => "array",
Value::Object(_) => "object",
}
}
pub fn json_kind_article(v: &Value) -> &'static str {
article(json_kind(v))
}
pub fn json_text_kind_article(text: &str) -> &'static str {
match text.trim_start().as_bytes().first() {
Some(b'n') => "null",
Some(b't' | b'f') => "a boolean",
Some(b'"') => "a string",
Some(b'[') => "an array",
Some(b'{') => "an object",
_ => "a number",
}
}
pub fn json_expected_found(expected: &str, found: &Value) -> String {
format!("expected {expected}, found {}", json_kind_article(found))
}
fn article(kind: &'static str) -> &'static str {
match kind {
"boolean" => "a boolean",
"number" => "a number",
"string" => "a string",
"array" => "an array",
"object" => "an object",
_ => "null",
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn kinds_and_articles() {
for (v, kind, with_article, text) in [
(json!(null), "null", "null", "null"),
(json!(true), "boolean", "a boolean", " false"),
(json!(1.5), "number", "a number", "-1"),
(json!("s"), "string", "a string", "\"s\""),
(json!([1]), "array", "an array", "[1]"),
(json!({"a": 1}), "object", "an object", "{}"),
] {
assert_eq!(json_kind(&v), kind);
assert_eq!(json_kind_article(&v), with_article);
assert_eq!(json_text_kind_article(text), with_article);
}
}
#[test]
fn expected_found_text() {
assert_eq!(
json_expected_found("a JSON object", &json!([])),
"expected a JSON object, found an array"
);
}
}