summaryrefslogtreecommitdiffstats
path: root/examples
diff options
context:
space:
mode:
authorRadosław Kot <rdkt13@gmail.com>2021-07-31 21:42:49 +0200
committerRadosław Kot <rdkt13@gmail.com>2021-10-23 16:58:41 +0200
commit6fa1b27f08afb8e8ec81f36ddfff69a23c2d73d6 (patch)
tree7bbd0b5eb5a96261ff62c1a82c45c670d8aafc1b /examples
parentbb23458eb91c3c62a50b5a8bc9dccbcf902ff070 (diff)
Add custom_format example
Diffstat (limited to 'examples')
-rw-r--r--examples/custom_format/main.rs55
1 files changed, 55 insertions, 0 deletions
diff --git a/examples/custom_format/main.rs b/examples/custom_format/main.rs
new file mode 100644
index 0000000..981dcb4
--- /dev/null
+++ b/examples/custom_format/main.rs
@@ -0,0 +1,55 @@
+use std::collections::HashMap;
+
+use config::{Config, File, FileExtensions, Format, Value, ValueKind};
+
+fn main() {
+ let config = Config::builder()
+ .add_source(File::from_str("bad", MyFormat))
+ .add_source(File::from_str("good", MyFormat))
+ .build();
+
+ match config {
+ Ok(cfg) => println!("A config: {:#?}", cfg),
+ Err(e) => println!("An error: {}", e),
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct MyFormat;
+
+impl Format for MyFormat {
+ fn parse(
+ &self,
+ uri: Option<&String>,
+ text: &str,
+ ) -> Result<
+ std::collections::HashMap<String, config::Value>,
+ Box<dyn std::error::Error + Send + Sync>,
+ > {
+ // Let's assume our format is somewhat crippled, but this is fine
+ // In real life anything can be used here - nom, serde or other.
+ //
+ // For some more real-life examples refer to format implementation within the library code
+ let mut result = HashMap::new();
+
+ if text == "good" {
+ result.insert(
+ "key".to_string(),
+ Value::new(uri, ValueKind::String(text.into())),
+ );
+ } else {
+ println!("Something went wrong in {:?}", uri);
+ }
+
+ Ok(result)
+ }
+}
+
+// As crazy as it seems for config sourced from a string, legacy demands its sacrifice
+// It is only required for File source, custom sources can use Format without caring for extensions
+static MY_FORMAT_EXT: Vec<&'static str> = vec![];
+impl FileExtensions for MyFormat {
+ fn extensions(&self) -> &Vec<&'static str> {
+ &MY_FORMAT_EXT
+ }
+}