Skip to main content

sword_core/config/
registrar.rs

1use crate::{Config, State};
2use serde::de::DeserializeOwned;
3
4/// A struct that holds a function to register a config type.
5/// Used by the inventory system to collect all config types at compile time.
6pub struct ConfigRegistrar {
7    pub register: fn(&State, &Config) -> (),
8}
9
10impl ConfigRegistrar {
11    pub const fn new(register: fn(&State, &Config) -> ()) -> Self {
12        Self { register }
13    }
14}
15
16inventory::collect!(ConfigRegistrar);
17
18/// Trait for configuration section types.
19///
20/// Types implementing this trait can be used with `Config::get()` to extract
21/// and deserialize specific sections from the configuration table.
22///
23/// Use the `#[config(key = "section_name")]` macro to automatically implement this trait.
24/// The macro will also auto-register the config type using the `inventory` crate.
25///
26/// ```rust,ignore
27/// use sword::prelude::*;
28///
29/// #[config(key = "my_section")]
30/// struct MyConfig {
31///     value: String,
32/// }
33/// ```
34pub trait ConfigItem: DeserializeOwned + Clone + Send + Sync + 'static {
35    /// Returns the TOML section key for this configuration type.
36    fn toml_key() -> &'static str;
37
38    /// Registers this config type in the application State.
39    /// This is called automatically during application bootstrap.
40    fn register(state: &State, config: &Config) {
41        let config_item = config.get::<Self>().unwrap_or_else(|_| {
42            panic!(
43                "Failed to load config item '{}' from the configuration file",
44                Self::toml_key()
45            )
46        });
47
48        state.insert(config_item);
49    }
50}