use crate::serde_json::Value;
pub const PATH_SEPARATOR: char = '.';
pub const LABEL_SEPARATOR: &str = ": ";
#[must_use]
pub fn fields(document: &Value) -> Vec<(String, String)> {
let mut found = Vec::new();
walk(String::new(), document, &mut found);
found
}
#[must_use]
pub fn line((at, value): &(String, String)) -> String {
format!("{at}{LABEL_SEPARATOR}{value}\n")
}
fn walk(at: String, value: &Value, found: &mut Vec<(String, String)>) {
let under = |name: &str| {
if at.is_empty() {
name.to_owned()
} else {
format!("{at}{PATH_SEPARATOR}{name}")
}
};
match value {
Value::Array(entries) if !entries.is_empty() && numbers_alone(value) => {
found.push((at, value.to_string()));
}
Value::Object(entries) if !entries.is_empty() => {
for (name, held) in entries {
walk(under(name), held, found);
}
}
Value::Array(entries) if !entries.is_empty() => {
for (index, held) in entries.iter().enumerate() {
walk(under(&index.to_string()), held, found);
}
}
Value::Object(_) => found.push((at, "{}".to_owned())),
Value::Array(_) => found.push((at, "[]".to_owned())),
Value::String(text) => found.push((at, text.clone())),
other => found.push((at, other.to_string())),
}
}
fn numbers_alone(value: &Value) -> bool {
match value {
Value::Number(_) => true,
Value::Array(entries) => !entries.is_empty() && entries.iter().all(numbers_alone),
_ => false,
}
}