gadk_platform/
json_kind.rs1use serde_json::Value;
19
20pub fn json_kind(v: &Value) -> &'static str {
23 match v {
24 Value::Null => "null",
25 Value::Bool(_) => "boolean",
26 Value::Number(_) => "number",
27 Value::String(_) => "string",
28 Value::Array(_) => "array",
29 Value::Object(_) => "object",
30 }
31}
32
33pub fn json_kind_article(v: &Value) -> &'static str {
36 article(json_kind(v))
37}
38
39pub fn json_text_kind_article(text: &str) -> &'static str {
42 match text.trim_start().as_bytes().first() {
43 Some(b'n') => "null",
44 Some(b't' | b'f') => "a boolean",
45 Some(b'"') => "a string",
46 Some(b'[') => "an array",
47 Some(b'{') => "an object",
48 _ => "a number",
49 }
50}
51
52pub fn json_expected_found(expected: &str, found: &Value) -> String {
54 format!("expected {expected}, found {}", json_kind_article(found))
55}
56
57fn article(kind: &'static str) -> &'static str {
59 match kind {
60 "boolean" => "a boolean",
61 "number" => "a number",
62 "string" => "a string",
63 "array" => "an array",
64 "object" => "an object",
65 _ => "null",
66 }
67}
68
69#[cfg(test)]
70mod tests {
71 use super::*;
72 use serde_json::json;
73
74 #[test]
75 fn kinds_and_articles() {
76 for (v, kind, with_article, text) in [
77 (json!(null), "null", "null", "null"),
78 (json!(true), "boolean", "a boolean", " false"),
79 (json!(1.5), "number", "a number", "-1"),
80 (json!("s"), "string", "a string", "\"s\""),
81 (json!([1]), "array", "an array", "[1]"),
82 (json!({"a": 1}), "object", "an object", "{}"),
83 ] {
84 assert_eq!(json_kind(&v), kind);
85 assert_eq!(json_kind_article(&v), with_article);
86 assert_eq!(json_text_kind_article(text), with_article);
87 }
88 }
89
90 #[test]
91 fn expected_found_text() {
92 assert_eq!(
93 json_expected_found("a JSON object", &json!([])),
94 "expected a JSON object, found an array"
95 );
96 }
97}