|
| 1 | +use serde_derive::Deserialize; |
| 2 | + |
| 3 | +use std::collections::HashMap; |
| 4 | +use std::error::Error; |
| 5 | + |
| 6 | +use crate::error::{ConfigError, Unexpected}; |
| 7 | +use crate::value::{Value, ValueKind}; |
| 8 | + |
| 9 | +#[derive(Deserialize, Debug)] |
| 10 | +#[serde(untagged)] |
| 11 | +pub enum Val { |
| 12 | + Null, |
| 13 | + Boolean(bool), |
| 14 | + Integer(i64), |
| 15 | + Float(f64), |
| 16 | + String(String), |
| 17 | + Array(Vec<Val>), |
| 18 | + Object(HashMap<String, Val>), |
| 19 | +} |
| 20 | + |
| 21 | +pub fn parse( |
| 22 | + uri: Option<&String>, |
| 23 | + text: &str, |
| 24 | +) -> Result<HashMap<String, Value>, Box<dyn Error + Send + Sync>> { |
| 25 | + let root = json5_rs::from_str::<Val>(&text)?; |
| 26 | + if let Some(err) = match root { |
| 27 | + Val::String(ref value) => Some(Unexpected::Str(value.clone())), |
| 28 | + Val::Integer(value) => Some(Unexpected::Integer(value)), |
| 29 | + Val::Float(value) => Some(Unexpected::Float(value)), |
| 30 | + Val::Boolean(value) => Some(Unexpected::Bool(value)), |
| 31 | + Val::Object(_) => None, |
| 32 | + Val::Array(_) => Some(Unexpected::Seq), |
| 33 | + Val::Null => Some(Unexpected::Unit), |
| 34 | + } { |
| 35 | + return Err(ConfigError::invalid_root(uri, err)); |
| 36 | + } |
| 37 | + |
| 38 | + let value = from_json5_value(uri, root); |
| 39 | + match value.kind { |
| 40 | + ValueKind::Table(map) => Ok(map), |
| 41 | + |
| 42 | + _ => Ok(HashMap::new()), |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +fn from_json5_value(uri: Option<&String>, value: Val) -> Value { |
| 47 | + match value { |
| 48 | + Val::String(v) => Value::new(uri, ValueKind::String(v)), |
| 49 | + |
| 50 | + Val::Integer(v) => Value::new(uri, ValueKind::Integer(v)), |
| 51 | + |
| 52 | + Val::Float(v) => Value::new(uri, ValueKind::Float(v)), |
| 53 | + |
| 54 | + Val::Boolean(v) => Value::new(uri, ValueKind::Boolean(v)), |
| 55 | + |
| 56 | + Val::Object(table) => { |
| 57 | + let mut m = HashMap::new(); |
| 58 | + |
| 59 | + for (key, value) in table { |
| 60 | + m.insert(key, from_json5_value(uri, value)); |
| 61 | + } |
| 62 | + |
| 63 | + Value::new(uri, ValueKind::Table(m)) |
| 64 | + } |
| 65 | + |
| 66 | + Val::Array(array) => { |
| 67 | + let mut l = Vec::new(); |
| 68 | + |
| 69 | + for value in array { |
| 70 | + l.push(from_json5_value(uri, value)); |
| 71 | + } |
| 72 | + |
| 73 | + Value::new(uri, ValueKind::Array(l)) |
| 74 | + } |
| 75 | + |
| 76 | + Val::Null => Value::new(uri, ValueKind::Nil), |
| 77 | + } |
| 78 | +} |
0 commit comments