Introduction
more-config
is a crate containing all of the fundamental abstractions for configuration in Rust.
Features
This crate provides the following features:
- default - Abstractions for configuration, including the std features
- std - Standard configuration implementation
- all - Includes all features, except async
- async - Use configuration in an asynchronous context
- mem - An in-memory configuration source
- env - An environment variables configuration source
- cmd - A command-line argument configuration source
- json - A *.json file configuration source
- xml - A *.xml file configuration source
- ini - An *.ini file configuration source
- chained - Chain multiple configuration sources
- binder - Bind a configuration to strongly-typed values and structs
Use
--features all,async
for all features with asynchronous support
Contributing
more-config
is free and open source. You can find the source code on GitHub
and issues and feature requests can be posted on the GitHub issue tracker.
more-config
relies on the community to fix bugs and add features: if you'd like to contribute, please read the
CONTRIBUTING guide and consider opening
a pull request.
License
This project is licensed under the MIT license.
Getting Started
The simplest way to get started is to install the crate using all features.
cargo add more-config --features all
This includes all features except the async feature. The async feature intersects with all other features. If you would like all features with asynchronous support use:
cargo add more-config --features all,async
Once you know which configuration sources you want to support, you can limit the features to only the ones you need.
Example
Configuration is a common requirement of virtually any application and can be performed using one or more configuration providers. Configuration providers read configuration data from key-value pairs using a variety of configuration sources:
- Settings files, such as
appsettings.json
- Environment variables
- Command-line arguments
- In-memory data structures
- Custom providers
use config::{*, ext::*};
fn main() {
let config = DefaultConfigurationBuilder::new()
.add_in_memory(&[("MyKey", "MyValue")])
.add_json_file("appsettings.json".is().optional())
.add_env_vars()
.add_command_line()
.build()
.unwrap();
println!("MyKey = {}", config.get("MyKey").unwrap().as_str());
}
Configuration providers that are added later have higher priority and override previous key settings. For example, if MyKey
is set in both appsettings.json
and an environment variable, then the environment variable value is used. If appsettings.json
does not exist or contain MyKey
and there is no environment variable for MyKey
, then the in-memory value of MyValue
is used. Finally, if command-line argument --MyKey
is provided, it overrides all other values.
Abstractions
The configuration framework contains a common set of traits and behaviors for numerous scenarios.
Configuration
The Configuration
trait is the pinnacle of the entire framework. It defines the behaviors to retrieve a configured value or iterate over all key-value pairs, access or traverse child sections, and react to a reload triggered by the underlying configuration source.
pub trait Configuration {
fn get(&self, key: &str) -> Option<Value>;
fn section(&self, key: &str) -> Box<dyn ConfigurationSection>;
fn children(&self) -> Vec<Box<dyn ConfigurationSection>>;
fn reload_token(&self) -> Box<dyn ChangeToken>;
fn as_section(&self) -> Option<&dyn ConfigurationSection>;
fn iter(
&self,
path: Option<ConfigurationPath>
) -> Box<dyn Iterator<Item = (String, Value)>>;
}
Configuration Section
Hierarchical configurations are divided into sections. A configurations section is itself a nested Configuration
. A configuration section also has its own key and, possibly, a value. A configuration section which does not have a value will always yield an empty string.
pub trait ConfigurationSection:
Configuration
+ AsRef<dyn Configuration>
+ Borrow<dyn Configuration>
+ Deref<Target = dyn Configuration>
{
fn key(&self) -> &str;
fn path(&self) -> &str;
fn value(&self) -> Value;
fn as_config(&self) -> Box<dyn Configuration>;
}
Configuration Root
Every configuration has a single root. The root configuration knows about all of the associated ConfigurationProvider
instances and can reload the entire configuration.
pub trait ConfigurationRoot:
Configuration
+ AsRef<dyn Configuration>
+ Borrow<dyn Configuration>
+ Deref<Target = dyn Configuration>
+ Debug
{
fn reload(&mut self) -> ReloadResult;
fn providers(&self) -> Box<dyn ConfigurationProviderIterator + '_>;
fn as_config(&self) -> Box<dyn Configuration>;
}
Configuration Provider
A configuration provider is responsible for loading configuration from a source. A configuration provider might support automatic reloading and can advertise when a reload has occurred via a reload ChangeToken
.
pub trait ConfigurationProvider {
fn name(&self) -> &str;
fn get(&self, key: &str) -> Option<Value>;
fn reload_token(&self) -> Box<dyn ChangeToken>;
fn load(&mut self) -> LoadResult;
fn child_keys(&self, earlier_keys: &mut Vec<String>, parent_path: Option<&str>);
}
Configuration Source
A configuration source provides an abstraction over a source for configuration such as a file. The source accepts all of the information required to setup a provider and then constructs it when the configuration is built.
pub trait ConfigurationSource {
fn build(
&self,
builder: &dyn ConfigurationBuilder
) -> Box<dyn ConfigurationProvider>;
}
Configuration Builder
A configuration builder accumulates one or more configuration sources and then builds a ConfigurationRoot
. The configuration is immediately reloaded so that it is ready to use.
pub trait ConfigurationBuilder {
fn properties(&self) -> &HashMap<String, Box<dyn Any>>;
fn sources(&self) -> &[Box<dyn ConfigurationSource>];
fn add(&mut self, source: Box<dyn ConfigurationSource>);
fn build(&self) -> Result<Box<dyn ConfigurationRoot>, ReloadError>;
}
Working With Configuration Data
There are several different ways to work with configuration data. Configuration sources are normalized to a generic key-value pair format, which can then be merged and consumed universally; regardless of the original format.
Hierarchical Configuration Data
The Configuration API reads hierarchical configuration data by flattening the hierarchical data with the use of a delimiter in the configuration keys.
Consider the following appsettings.json
file:
{
"Position": {
"Title": "Editor",
"Name": "Joe Smith"
},
"MyKey": "My appsettings.json Value",
"Logging": {
"LogLevel": {
"Default": "Information",
"App": "Warning",
"App.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
The following code displays several of the configurations settings:
use config::{*, ext::*};
fn main() {
let config = DefaultConfigurationBuilder::new()
.add_json_file("appsettings.json")
.build()
.unwrap();
let my_key_value = config.get("MyKey").unwrap().as_str();
let title = config.get("Position:Title").unwrap().as_str();
let name = config.section("Position").get("Name").unwrap().as_str();
let default_log_level = config.get("Logging:LogLevel:Default").unwrap().as_str();
println!("MyKey value: {}\n\
Title: {}\n\
Name: {}\n\
Default Log Level: {}",
my_key_value,
title,
name,
default_log_level);
}
The preferred way to read hierarchical configuration data is using the Options pattern provided by the more-options crate. The section
and children
methods are available to isolate sections and children of a section in the configuration data.
Configuration Keys and Values
Configuration keys:
- Are case-insensitive; for example,
ConnectionString
andconnectionstring
are treated as equivalent keys. - If a key and value is set in more than one configuration providers, the value from the last provider added is used.
- Hierarchical keys
- Within the Configuration API, a colon separator (
:
) works on all platforms. - In environment variables, a colon separator may not work on all platforms. A double underscore,
__
, is supported by all platforms and is automatically converted into a colon:
.
- Within the Configuration API, a colon separator (
- The
ConfigurationBinder
supports binding arrays to objects using array indices in configuration keys.
Configuration values:
- Are strings
- Null values can't be stored in configuration or bound to objects
Get Value
The get_value
and get_value_or_default
methods extract a single value from configuration with a specified key and converts it to the specified type.
use config::{*, ext::*};
fn main() {
let config = DefaultConfigurationBuilder::new()
.add_json_file("settings.json")
.build()
.unwrap();
let number: Option<u8> = config.get_value("NumberKey").unwrap().unwrap_or(99);
let flag: bool = config.get_value_or_default("Enabled").unwrap();
println!("Number = {}", number);
println!("Flag = {}", flag);
}
In the preceding code, if NumberKey
isn't found in the configuration, the default value of 99
is used. If Enabled
isn't found in the configuration, it will default to false
, which is the Default::default()
for bool
.
Section, Children, and Exists
For the examples that follow, consider the following MySubsection.json
file:
{
"section0": {
"key0": "value00",
"key1": "value01"
},
"section1": {
"key0": "value10",
"key1": "value11"
},
"section2": {
"subsection0": {
"key0": "value200",
"key1": "value201"
},
"subsection1": {
"key0": "value210",
"key1": "value211"
}
}
}
Section
section
returns a configuration subsection with the specified subsection key.
The following code returns values for section1
:
let section = config.section("section1");
println!("section1:key0: {}\n\
section1:key1: {}",
section.get("key0").unwrap().as_str(),
section.get("key1").unwrap().as_str());
The following code returns values for section2:subsection0
:
let section = config.section("section2:subsection0");
println!("section2:subsection0:key0: {}\n\
section2:subsection0:key0: {}",
section.get("key0").unwrap().as_str(),
section.get("key1").unwrap().as_str());
If a matching section isn't found, an empty ConfigurationSection
is returned.
Children and Exists
The following code calls children
and returns values for section2:subsection0
:
let section = config.section("section2");
if section.exists() {
for subsection in section.children() {
let key1 = format!("{}:key0", section.key());
let key2 = format!("{}:key1", section.key());
println!("{} value: {}\n\
{} value: {}",
&key1,
&key2,
section.get(&key1).unwrap().as_str(),
section.get(&key2).unwrap().as_str());
}
} else {
println!("section2 does not exist.");
}
println!("section1:key0: {}\n\
section1:key1: {}",
section.get("key0").unwrap().as_str(),
section.get("key1").unwrap().as_str());
The preceding code uses the exists
extension to verify the section exists.
Working With Files
A ConfigurationProvider
that is based on a file should support a FileSource
:
pub struct FileSource {
pub path: PathBuf,
pub optional: bool,
pub reload_on_change: bool,
pub reload_delay: Duration,
}
An optional
file means that the path
does not need to exist. When reload_on_change
is specified, the provider will watch for changes to path
and trigger a notification via ConfigurationProvider::reload_token
. A file change might trigger before a file has been completely written, which is operating system dependent. reload_delay
indicates how long a provider should wait to reload when a change is detected. The default duration is 250 milliseconds.
All of the built-in, file-based configuration providers support accepting a FileSource
. A file source is most commonly just a file path, but it may include additional configuration features. The FileSourceBuilder
struct and FileSourceBuilderExtensions
trait provide several methods of specifying a FileSource
and its options in a fluent manner.
use config::{*, ext::*};
use std::path::PathBuf;
fn main() {
let xml = PathBuf::from("settings.xml");
let config = DefaultConfigurationBuilder::new()
.add_ini_file(FileSource::new(PathBuf::("prod.cfg.ini"), false, false, None))
.add_ini_file(FileSource::optional(PathBuf::("dev.cfg.ini")))
.add_xml_file(xml.is().optional())
.add_json_file("settings.json".is().optional().reloadable())
.build()
.unwrap();
for (key, value) in config.iter(None) {
println!("{} = {}", key, value.as_str());
}
}
In-Memory Configuration Provider
These features are only available if the mem feature is activated
The MemoryConfigurationProvider
uses an in-memory collection as configuration key-value pairs. This is most useful as a default configuration or when providing test values.
The following code adds a memory collection to the configuration system and displays the settings:
use config::{*, ext::*};
fn main() {
let config = DefaultConfigurationBuilder::new()
.add_in_memory(&[
("MyKey", "Dictionary MyKey Value"),
("Position:Title", "Dictionary_Title"),
("Position:Name", "Dictionary_Name"),
("Logging:LogLevel:Default", "Warning"),
])
.build()
.unwrap();
let my_key_value = config.get("MyKey").unwrap().as_str();
let title = config.get("Position:Title").unwrap().as_str();
let name = config.section("Position").get("Name").unwrap().as_str();
let default_log_level = config.get("Logging:LogLevel:Default").unwrap().as_str();
println!("MyKey value: {}\n\
Title: {}\n\
Name: {}\n\
Default Log Level: {}",
my_key_value,
title,
name,
default_log_level);
}
Environment Variable Configuration Provider
These features are only available if the env feature is activated
The EnvironmentVariablesConfigurationProvider
loads configuration from environment variable key-value pairs.
The :
separator doesn't work with environment variable hierarchical keys on all platforms. __
, the double underscore, is:
- Supported by all platforms; for example, the
:
separator is not supported by Bash, but__
is. - Automatically replaced by a
:
export MyKey="My key from Environment"
export Position__Title=Console
export Position__Name="John Doe"
Call add_env_vars
to add environment variables or add_env_vars_with_prefix
with a string to specify a prefix for environment variables:
use config::{*, ext::*};
fn main() {
let config = DefaultConfigurationBuilder::new()
.add_env_vars_with_prefix("MyCustomPrefix_")
.build()
.unwrap();
for (key, value) in config.iter(None) {
println!("{} = {}", key, value.as_str());
}
}
Environment variables set with the MyCustomPrefix_
prefix override the default configuration providers. This includes environment variables without the prefix. The prefix is stripped off when the configuration key-value pairs are read.
export MyCustomPrefix_MyKey="My key with MyCustomPrefix_ Environment"
export MyCustomPrefix_Position__Title="Custom Editor"
export MyCustomPrefix_Position__Name="Jane Doe"
Naming of Environment Variables
Environment variable names reflect the structure of an appsettings.json
file. Each element in the hierarchy is separated by a double underscore. When the element structure includes an array, the array index should be treated as an additional element name in this path. Consider the following appsettings.json
file and its equivalent values represented as environment variables.
{
"SmtpServer": "smtp.example.com",
"Logging":
[
{
"Name": "ToEmail",
"Level": "Critical",
"Args":
{
"FromAddress": "MySystem@example.com",
"ToAddress": "SRE@example.com"
}
},
{
"Name": "ToConsole",
"Level": "Information"
}
]
}
export SmtpServer=smtp.example.com
export Logging__0__Name=ToEmail
export Logging__0__Level=Critical
export Logging__0__Args__FromAddress=MySystem@example.com
export Logging__0__Args__ToAddress=SRE@example.com
export Logging__1__Name=ToConsole
export Logging__1__Level=Information
Command-Line Configuration Provider
These features are only available if the cmd feature is activated
The CommandLineConfigurationProvider
loads configuration from command-line argument key-value pairs. Configuration values set on the command-line can be used to override configuration values set with all the other configuration providers. When used, it is recommended that this is the last configuration provider added.
Command-line Arguments
The following command sets keys and values using =
:
myapp MyKey="Using =" Position:Title=Cmd Position:Name=Cmd_Joe
The following command sets keys and values using /
:
myapp /MyKey "Using /" /Position:Title=Cmd /Position:Name=Cmd_Joe
The following command sets keys and values using --
:
myapp --MyKey "Using --" --Position:Title=Cmd --Position:Name=Cmd_Joe
The key value:
- Must follow
=
, or the key must have a prefix of--
or/
when the value follows a space. - Isn't required if
=
is used; for example,MySetting=
.
Within the same command, don't mix command-line argument key-value pairs that use =
with key-value pairs that use a space.
use config::{*, ext::*};
fn main() {
let config = DefaultConfigurationBuilder::new()
.add_command_line()
.build()
.unwrap();
println!("Name = {}", config.section("Position").get("Name").unwrap());
}
Switch Mappings
Switch mappings allow key name replacement logic. Provide a hash map of switch replacements to the add_command_line_map
method.
When the switch mappings hash map is used, the hash map is checked for a key that matches the key provided by a command-line argument. If the command-line key is found in the hash map, the hash map value is passed back to set the key-value pair into the application's configuration. A
switch mapping is required for any command-line key prefixed with a single dash (-
).
Switch mappings hash map key rules:
- Switches must start with
-
or--
. - The switch mappings hash map must not contain duplicate keys.
To use a switch mappings hash map, pass it into the call to add_command_line_map
:
use config::{*, ext::*};
fn main() {
let switch_mappings = [
("-k1", "key1"),
("-k2", "key2"),
("--alt3", "key3"),
("--alt4", "key4"),
("--alt5", "key5"),
("--alt6", "key6"),
];
let config = DefaultConfigurationBuilder::new()
.add_command_line_map(&switch_mappings)
.build()
.unwrap();
for (key, value) in config.iter(None) {
println!("{} = {}", key, value.as_str());
}
}
Run the following command works to test key replacement:
myapp -k1 value1 -k2 value2 --alt3=value2 /alt4=value3 --alt5 value5 /alt6 value6
The following code shows the key values for the replaced keys:
println!("Key1: {}\n\
Key2: {}\n\
Key3: {}\n\
Key4: {}\n\
Key5: {}\n\
Key6: {}",
config.get("Key1").unwrap(),
config.get("Key2").unwrap(),
config.get("Key3").unwrap(),
config.get("Key4").unwrap(),
config.get("Key5").unwrap(),
config.get("Key6").unwrap());
Filtering
By default, the sequence of arguments provided by std::env::args()
is supplied to the CommandLineConfigurationSource
. If custom filtering is required, no extension method is provided to do so. The setup is still trivial albeit more verbose.
use config::{*, ext::*};
fn main() {
let mut args: Vec<_> = std::env::args().collect();
// TODO: apply filtering
let cmd = CommandLineConfigurationSource::from(args.iter());
let mut builder = DefaultConfigurationBuilder::new();
builder.add(Box::new(cmd));
let config = builder.build().unwrap();
for (key, value) in config.iter(None) {
println!("{} = {}", key, value.as_str());
}
}
JSON Configuration Provider
These features are only available if the json feature is activated
The JsonConfigurationProvider
supports loading configuration from a *.json
file.
Consider the following appsettings.json
file:
{
"Position": {
"Title": "Editor",
"Name": "Joe Smith"
},
"MyKey": "My appsettings.json Value",
"Logging": {
"LogLevel": {
"Default": "Information",
"App": "Warning",
"App.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
The following code displays several of the preceding configurations settings:
use config::{*, ext::*};
fn main() {
let config = DefaultConfigurationBuilder::new()
.add_json_file("appsettings.json")
.build()
.unwrap();
let my_key_value = config.get("MyKey").unwrap().as_str();
let title = config.get("Position:Title").unwrap().as_str();
let name = config.section("Position").get("Name").unwrap().as_str();
let default_log_level = config.get("Logging:LogLevel:Default").unwrap().as_str();
println!("MyKey value: {}\n\
Title: {}\n\
Name: {}\n\
Default Log Level: {}",
my_key_value,
title,
name,
default_log_level);
}
XML Configuration Provider
These features are only available if the xml feature is activated
The XmlConfigurationProvider
supports loading configuration from a *.xml
file.
The following code adds several configuration providers, including a couple of *.xml
files:
fn main() {
let name = env::var("ENVIRONMENT").or_else("production");
let config = DefaultConfigurationBuilder::new()
.add_xml_file("MyXmlConfig.xml".is().optional())
.add_xml_file(format!("MyXmlConfig.{}.xml", name).is().optional())
.add_env_vars()
.add_command_line()
.build()
.unwrap();
}
The XML configuration files have a few special rules that are different from other configuration providers:
- XML namespaces are not supported on elements or attributes
- The
Name
attribute (case-insensitive) is considered as a surrogate key in lieu of the element it is applied to - Duplicate key-value combinations are ambiguous and not allowed
- Repeating elements with different values are considered array-like
Consider the following configuration file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<MyKey>MyXMLFile Value</MyKey>
<Position>
<Title>Title from MyXMLFile</Title>
<Name>Name from MyXMLFile</Name>
</Position>
<Logging>
<LogLevel>
<Default>Information</Default>
<App>Warning</App>
</LogLevel>
</Logging>
</configuration>
The following code displays several of the preceding configuration settings:
let my_key_value = config.get("MyKey").unwrap().as_str();
let title = config.get("Position:Title").unwrap().as_str();
let name = config.section("Position").get("Name").unwrap().as_str();
let default_log_level = config.get("Logging:LogLevel:Default").unwrap().as_str();
println!("MyKey value: {}\n\
Title: {}\n\
Name: {}\n\
Default Log Level: {}",
my_key_value,
title,
name,
default_log_level);
Repeating elements that use the same element name work if the name
attribute is used to distinguish the elements:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<section name="section0">
<key name="key0">value 00</key>
<key name="key1">value 01</key>
</section>
<section name="section1">
<key name="key0">value 10</key>
<key name="key1">value 11</key>
</section>
</configuration>
The following code reads the previous configuration file and displays the keys and values:
use config::{*, ext::*};
fn main() {
let config = DefaultConfigurationBuilder::new()
.add_xml_file("MyXmlConfig2.xml")
.build()
.unwrap();
let val00 = config.get("section:section0:key:key0").unwrap().as_str();
let val01 = config.get("section:section0:key:key1").unwrap().as_str();
let val10 = config.get("section:section1:key:key0").unwrap().as_str();
let val11 = config.get("section:section1:key:key1").unwrap().as_str();
println!("section:section0:key:key0 value: {}\n\
section:section0:key:key1 value: {}\n\
section:section1:key:key0 value: {}\n\
section:section1:key:key1 value: {}",
val00
val01
val10
val11);
}
If the name
attribute were not used, then the elements would be treated as array-like:
- section:0:key:0
- section:0:key:1
- section:1:key:0
- section:1:key:1
Attributes can also be used to supply values:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<key attribute="value" />
<section>
<key attribute="value" />
</section>
</configuration>
The previous configuration file loads the following keys with value of value
:
- key:attribute
- section:key:attribute
INI Configuration Provider
These features are only available if the ini feature is activated
The IniConfigurationProvider
supports loading configuration from an *.ini
file.
The following code adds several configuration providers, including a couple of *.ini
files:
use config::{*, ext::*};
fn main() {
let name = std::env::var("ENVIRONMENT").or_else("production");
let config = DefaultConfigurationBuilder::new()
.add_ini_file("MyIniConfig.ini".is().optional())
.add_ini_file(format!("MyIniConfig.{}.ini", name).is().optional())
.add_env_vars()
.add_command_line()
.build()
.unwrap();
}
In the preceding code, settings in the MyIniConfig.ini
and MyIniConfig.{Environment}.ini
files are overridden by settings in the:
- Environment variables configuration provider
- Command-line configuration provider
Assume the MyIniConfig.ini
file contains:
MyKey="MyIniConfig.ini Value"
[Position]
Title="My INI Config title"
Name="My INI Config name"
[Logging:LogLevel]
Default=Information
App=Warning
The following code displays several of the preceding configurations settings:
let my_key_value = config.get("MyKey").unwrap().as_str();
let title = config.get("Position:Title").unwrap().as_str();
let name = config.section("Position").get("Name").unwrap().as_str();
let default_log_level = config.get("Logging:LogLevel:Default").unwrap().as_str();
println!("MyKey value: {}\n\
Title: {}\n\
Name: {}\n\
Default Log Level: {}",
my_key_value,
title,
name,
default_log_level);
Chained Configuration Provider
These features are only available if the chained feature is activated
Although it is not a very common usage scenario, you may encounter a scenario where you need to chain multiple configurations from different sources into a unified configuration. A practical example would be distinct configurations defined by different crates.
Let's assume that crate1
defines its default configuration as:
use config::{*, ext::*};
fn default_config() -> Box<dyn ConfigurationRoot> {
DefaultConfigurationBuilder::new()
.add_in_memory(&[("Mem1:KeyInMem1", "ValueInMem1")])
.add_in_memory(&[("Mem2:KeyInMem2", "ValueInMem2")])
.build()
.unwrap()
}
Let's assume that crate2
defines its default configuration as:
use config::{*, ext::*};
fn default_config() -> Box<dyn ConfigurationRoot> {
DefaultConfigurationBuilder::new()
.add_in_memory(&[("Mem3:KeyInMem3", "ValueInMem3")])
.build()
.unwrap()
}
An application can now compose the crate1
and crate2
configurations into its own configuration.
use config::{*, ext::*};
use crate1;
use crate2;
fn main() {
let root = DefaultConfigurationBuilder::new()
.add_configuration(crate1::default_config().as_config())
.add_configuration(crate2::default_config().as_config())
.add_env_vars()
.add_command_line()
.build()
.unwrap();
println!("mem1:keyinmem1 = {}", root.get("mem1:keyinmem1").unwrap());
println!("Mem2:KeyInMem2 = {}", root.get("Mem2:KeyInMem2").unwrap());
println!("MEM3:KEYINMEM3 = {}", root.get("ValueInMem3").unwrap());
}
This configuration would output:
mem1:keyinmem1 = mem1:keyinmem1
Mem2:KeyInMem2 = Mem2:KeyInMem2
MEM3:KEYINMEM3 = ValueInMem3
Data Binding
Data binding requires the binder feature, which will also trigger activation of the optional serde dependency and is required for deserialization.
Data binding leverages the serde crate to enable deserializing configurations in part, or in whole, into strongly-typed structures. It is also possible to retrieve strongly-typed scalar values.
A Configuration
is deserialized through the ConfigurationBinder
trait:
pub trait ConfigurationBinder {
fn reify<T: DeserializeOwned>(&self) -> T;
fn bind<T: DeserializeOwned>(&self, instance: &mut T);
fn bind_at<T: DeserializeOwned>(&self, key: impl AsRef<str>, instance: &mut T);
fn get_value<T: FromStr>(&self, key: impl AsRef<str>) -> Result<Option<T>, T::Err>;
fn get_value_or_default<T>(&self, key: impl AsRef<str>) -> Result<T, T::Err>
where
T: FromStr + Default;
}
Consider the following struct:
use serde::Deserialize;
#[derive(Default, Deserialize)]
#[serde(rename_all(deserialize = "PascalCase"))]
struct ContactOptions {
name: String,
primary: bool,
phones: Vec<String>,
}
Configuration keys are normalized or expected to otherwise be Pascal Case for consistency.
The following demonstrates how to load a configuration and then reify the configuration into the struct that was defined above. This example used the in-memory configuration provider, but any configuration provider or multiple configuration providers can be used.
use config::{*, ext::*};
fn main() {
let config = DefaultConfigurationBuilder::new()
.add_in_memory(&[
("name", "John Doe"),
("primary", "true"),
("phones:0", "+44 1234567"),
("phones:1", "+44 2345678"),
])
.build()
.unwrap();
let primary: bool = config.get_value_or_default("primary").unwrap();
let options: ContactOptions = config.reify();
println!("Is Primary: {}", primary);
println!("{}", &options.name);
println!("Phones:");
for phone in &contact.phones {
println!("\n {}", phone);
}
}
It is also possible to bind an existing structure to an entire configuration or bind at a specific configuration section.
use config::{*, ext::*};
fn main() {
let config = DefaultConfigurationBuilder::new()
.add_in_memory(&[
("name", "John Doe"),
("primary", "true"),
("phones:0", "+44 1234567"),
("phones:1", "+44 2345678"),
])
.build()
.unwrap();
let mut options = ContactOptions::default();
config.bind(&mut options);
println!("{}", &options.name);
println!("Phones:");
for phone in &contact.phones {
println!("\n {}", phone);
}
}
Note: The bound struct must implement
Deserialize::deserialize_in_place
to perform a true, in-place update. The default implementation creates a new struct and binds to it, which is essentially the same as mutating the struct to the result ofreify
.
Bind an Array
bind
supports binding arrays to objects using array indices in configuration keys.
Consider MyArray.json
:
{
"array": {
"entries": {
"0": "value00",
"1": "value10",
"2": "value20",
"4": "value40",
"5": "value50"
}
}
}
The following code reads the configuration and displays the values:
use config::{*, ext::*};
use serde::Deserialize;
#[derive(Default, Deserialize)]
#[serde(rename_all(deserialize = "PascalCase"))]
struct ArrayExample {
entries: Vec<String>,
}
fn main() {
let config = DefaultConfigurationBuilder::new()
.add_json_file("MyArray.json")
.build()
.unwrap();
let array: ArrayExample = config.reify();
for (i, item) in array.entries.iter().enumerate() {
println!("Index: {}, Value: {}", i, item );
}
}
The preceding code returns the following output. Note that index 3 has the value value40
, which corresponds to "4": "value40"
in MyArray.json
. The bound array indices are continuous and not bound to the configuration key index. The configuration binder isn't capable of binding null values or creating null entries in bound objects; however, a missing value can be mapped to Option
.
Index: 0 Value: value00
Index: 1 Value: value10
Index: 2 Value: value20
Index: 3 Value: value40
Index: 4 Value: value50