spin_factors/runtime_config/
toml.rs

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
//! Helpers for reading runtime configuration from a TOML file.

use std::{cell::RefCell, collections::HashSet};

/// A trait for getting a TOML value by key.
pub trait GetTomlValue {
    fn get(&self, key: &str) -> Option<&toml::Value>;
}

impl GetTomlValue for toml::Table {
    fn get(&self, key: &str) -> Option<&toml::Value> {
        self.get(key)
    }
}

#[derive(Debug, Clone)]
/// A helper for tracking which keys have been used in a TOML table.
pub struct TomlKeyTracker<'a> {
    unused_keys: RefCell<HashSet<&'a str>>,
    table: &'a toml::Table,
}

impl<'a> TomlKeyTracker<'a> {
    pub fn new(table: &'a toml::Table) -> Self {
        Self {
            unused_keys: RefCell::new(table.keys().map(String::as_str).collect()),
            table,
        }
    }

    pub fn validate_all_keys_used(&self) -> crate::Result<()> {
        if !self.unused_keys.borrow().is_empty() {
            return Err(crate::Error::RuntimeConfigUnusedKeys {
                keys: self
                    .unused_keys
                    .borrow()
                    .iter()
                    .map(|s| (*s).to_owned())
                    .collect(),
            });
        }
        Ok(())
    }
}

impl GetTomlValue for TomlKeyTracker<'_> {
    fn get(&self, key: &str) -> Option<&toml::Value> {
        self.unused_keys.borrow_mut().remove(key);
        self.table.get(key)
    }
}

impl AsRef<toml::Table> for TomlKeyTracker<'_> {
    fn as_ref(&self) -> &toml::Table {
        self.table
    }
}