cornfig/
lib.rs

1use serde::Serialize;
2use std::collections::{BTreeMap, HashMap};
3
4pub use crate::parser::parse;
5pub(crate) use crate::parser::Rule;
6
7pub mod error;
8mod parser;
9
10#[cfg(feature = "wasm")]
11mod wasm;
12
13/// A map of input names and values.
14/// The names include their `$` prefix.
15pub type Inputs<'a> = HashMap<&'a str, Value<'a>>;
16
17#[derive(Serialize, Debug, Clone)]
18#[serde(untagged)]
19pub enum Value<'a> {
20    // #[serde(serialize_with = "toml::ser::tables_last")]
21    // #[serde(serialize_with = "serialize")]
22    Object(BTreeMap<&'a str, Value<'a>>),
23    Array(Vec<Value<'a>>),
24    String(String),
25    Integer(i64),
26    Float(f64),
27    Boolean(bool),
28    Null(Option<()>),
29}
30
31#[derive(Serialize, Debug)]
32pub struct Config<'a> {
33    pub inputs: Inputs<'a>,
34    pub value: Value<'a>,
35}
36
37#[derive(Serialize, Debug, Clone)]
38#[serde(untagged)]
39pub enum TomlValue {
40    #[serde(serialize_with = "toml::ser::tables_last")]
41    Object(BTreeMap<String, TomlValue>),
42    Array(Vec<TomlValue>),
43    String(String),
44    Integer(i64),
45    Float(f64),
46    Boolean(bool),
47}
48
49impl From<Value<'_>> for TomlValue {
50    fn from(value: Value) -> Self {
51        match value {
52            Value::Object(val) => {
53                let obj = val
54                    .iter()
55                    .filter_map(|(k, v)| {
56                        if let Value::Null(_) = v {
57                            None
58                        } else {
59                            Some((k.to_string(), TomlValue::from(v.clone())))
60                        }
61                    })
62                    .collect();
63
64                TomlValue::Object(obj)
65            }
66            Value::Array(val) => {
67                let arr = val
68                    .iter()
69                    .filter_map(|v| {
70                        if let Value::Null(_) = v {
71                            None
72                        } else {
73                            Some(TomlValue::from(v.clone()))
74                        }
75                    })
76                    .collect();
77                TomlValue::Array(arr)
78            }
79            Value::String(val) => TomlValue::String(val),
80            Value::Integer(val) => TomlValue::Integer(val),
81            Value::Float(val) => TomlValue::Float(val),
82            Value::Boolean(val) => TomlValue::Boolean(val),
83            Value::Null(_) => unreachable!(),
84        }
85    }
86}