storm_config/file/format/
mod.rs1#![allow(unused_mut)]
4
5use crate::map::Map;
6use crate::{file::FileStoredFormat, value::Value, Format};
7use lazy_static::lazy_static;
8use std::collections::HashMap;
9use std::error::Error;
10
11mod json;
12
13#[cfg(feature = "toml")]
14mod toml;
15
16#[cfg(feature = "yaml")]
17mod yaml;
18
19#[cfg(feature = "ini")]
20mod ini;
21
22#[cfg(feature = "ron")]
23mod ron;
24
25#[cfg(feature = "json5")]
26mod json5;
27
28#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
32pub enum FileFormat {
33 Json,
35
36 #[cfg(feature = "toml")]
38 Toml,
39
40 #[cfg(feature = "yaml")]
42 Yaml,
43
44 #[cfg(feature = "ini")]
46 Ini,
47
48 #[cfg(feature = "ron")]
50 Ron,
51
52 #[cfg(feature = "json5")]
54 Json5,
55}
56
57lazy_static! {
58 #[doc(hidden)]
59 pub static ref ALL_EXTENSIONS: HashMap<FileFormat, Vec<&'static str>> = {
61 let mut formats: HashMap<FileFormat, Vec<_>> = HashMap::new();
62
63 formats.insert(FileFormat::Json, vec!["json"]);
64
65 #[cfg(feature = "toml")]
66 formats.insert(FileFormat::Toml, vec!["toml"]);
67
68 #[cfg(feature = "yaml")]
69 formats.insert(FileFormat::Yaml, vec!["yaml", "yml"]);
70
71 #[cfg(feature = "ini")]
72 formats.insert(FileFormat::Ini, vec!["ini"]);
73
74 #[cfg(feature = "ron")]
75 formats.insert(FileFormat::Ron, vec!["ron"]);
76
77 #[cfg(feature = "json5")]
78 formats.insert(FileFormat::Json5, vec!["json5"]);
79
80 formats
81 };
82}
83
84impl FileFormat {
85 pub(crate) fn extensions(&self) -> &'static [&'static str] {
86 ALL_EXTENSIONS.get(self).unwrap()
90 }
91
92 pub(crate) fn parse(
93 &self,
94 uri: Option<&String>,
95 text: &str,
96 ) -> Result<Map<String, Value>, Box<dyn Error + Send + Sync>> {
97 match self {
98 FileFormat::Json => json::parse(uri, text),
99
100 #[cfg(feature = "toml")]
101 FileFormat::Toml => toml::parse(uri, text),
102
103 #[cfg(feature = "yaml")]
104 FileFormat::Yaml => yaml::parse(uri, text),
105
106 #[cfg(feature = "ini")]
107 FileFormat::Ini => ini::parse(uri, text),
108
109 #[cfg(feature = "ron")]
110 FileFormat::Ron => ron::parse(uri, text),
111
112 #[cfg(feature = "json5")]
113 FileFormat::Json5 => json5::parse(uri, text),
114
115 #[cfg(all(
116 not(feature = "toml"),
117 not(feature = "yaml"),
118 not(feature = "ini"),
119 not(feature = "ron"),
120 not(feature = "json5"),
121 ))]
122 _ => unreachable!("No features are enabled, this library won't work without features"),
123 }
124 }
125}
126
127impl Format for FileFormat {
128 fn parse(
129 &self,
130 uri: Option<&String>,
131 text: &str,
132 ) -> Result<Map<String, Value>, Box<dyn Error + Send + Sync>> {
133 self.parse(uri, text)
134 }
135}
136
137impl FileStoredFormat for FileFormat {
138 fn file_extensions(&self) -> &'static [&'static str] {
139 self.extensions()
140 }
141}