1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//! TOML configuration parser.
//!
//! This is only usable if you enabled `toml` Cargo feature.
//!
//! ### Example
//! ```rust
//! use plugx_config::parser::{ConfigurationParser, toml::ConfigurationParserToml};
//! use plugx_input::Input;
//!
//! let bytes = br#"
//! hello=["w", "o", "l", "d"]
//!
//! [foo]
//! bar = {baz = "Qux", abc = 3.14}
//! xyz = false
//! "#;
//!
//! let parser = ConfigurationParserToml::new();
//! let parsed: Input = parser.parse(bytes.as_slice()).unwrap();
//! assert!(parsed.is_map());
//! let map = parsed.as_map();
//! assert!(
//!     map.len() == 2 &&
//!     map.contains_key("foo") &&
//!     map.contains_key("hello")
//! );
//! ```

use crate::parser::ConfigurationParser;
use anyhow::anyhow;
use cfg_if::cfg_if;
use plugx_input::Input;
use std::fmt::Debug;

#[derive(Default, Debug, Clone, Copy)]
pub struct ConfigurationParserToml;

impl ConfigurationParserToml {
    pub fn new() -> Self {
        Default::default()
    }
}

impl ConfigurationParser for ConfigurationParserToml {
    fn name(&self) -> String {
        "TOML".to_string()
    }

    fn supported_format_list(&self) -> Vec<String> {
        ["toml".into()].into()
    }

    fn try_parse(&self, bytes: &[u8]) -> anyhow::Result<Input> {
        String::from_utf8(bytes.to_vec())
            .map_err(|error| anyhow!("Could not decode contents to UTF-8 ({error})"))
            .and_then(|text| {
                toml::from_str(text.as_str())
                    .map(|parsed: Input| {
                        cfg_if! {
                            if #[cfg(feature = "tracing")] {
                                tracing::trace!(
                                    input=text,
                                    output=%parsed,
                                    "Parsed TOML contents"
                                );
                            } else if #[cfg(feature = "logging")] {
                                log::trace!(
                                    "msg=\"Parsed TOML contents\" input={text:?} output={:?}",
                                    parsed.to_string()
                                );
                            }
                        }
                        parsed
                    })
                    .map_err(|error| anyhow!(error))
            })
    }

    fn is_format_supported(&self, bytes: &[u8]) -> Option<bool> {
        Some(if let Ok(text) = String::from_utf8(bytes.to_vec()) {
            toml::from_str::<toml::Value>(text.as_str()).is_ok()
        } else {
            false
        })
    }
}