Struct Settings

Source
pub struct Settings<T>
where T: Format + Clone,
{ /* private fields */ }
Expand description

Basic one file settings

The main guts of Settingsfile-rs. The Settings struct interacts with the file system to serialize / deserialize configurations / settings and then allow easy navigation and maniulation.

Settings only reads data from one source and doesn’t do any ‘shadowing’, so if you want to override settings based on a local user configuration, use the ShadowSettings struct instead.

§Examples

§General Use

Say a file looked like this, and was defined in the Format Config

{
    "user" : {
        "name" : "user's name",
        "email" : "user's email"
    }
}

We could access the data like this.

use settingsfile::Settings;
use settingsfile::EmptyConfig; // dumb config for examples and testing
 
let app_settings = Settings::new(EmptyConfig{});
if let Some(value) = app_settings.get_value("user.name") {
    // prints "username is user's name"
    println!("username is {}",value); 
}

And if we weren’t sure if the user would set a certain value, but would need something during running we can define a default value.

use settingsfile::Settings;
use settingsfile::EmptyConfig; // dumb config for examples and testing
 
let app_settings = Settings::new(EmptyConfig{});
let font_size = app_settings.get_value_or("font.size",&12);
println!("Font size is {}",font_size); // will either be 12 or whatever the user sets.

§Data Validation

Rust is heavy on type safe, and so is settingsfile. By default a settings file can only contain the following types (defined in the Type enum)

  • Text
  • Int
  • Float
  • Switch
  • Array (of any combination of above)
  • HashMap (of any combination of above)

Every result of a get will return a Type that you will need to match in order to use the data. The only except is when you print / format it, as Type implements display.

Using the fontsize example above.

use settingsfile::Settings;
use settingsfile::Type;
use settingsfile::EmptyConfig; // dumb config for examples and testing
 
let app_settings = Settings::new(EmptyConfig{});
if let Type::Int(size) = app_settings.get_value_or("font.size",&12) {
    println!("Setting font size to {}",size);
} else {
    println!("Setting font.size must be an int!");
}

Implementations§

Source§

impl<T> Settings<T>
where T: Format + Clone,

Source

pub fn new(config: T) -> Settings<T>

Creates an empty Settings from a configuration.

Initally the settings doesn’t have any data and needs to have data inserted, set or loaded, ::load().

Source

pub fn new_and_load(config: T) -> Settings<T>

A onliner to create a Settings and load from the config location.

Basically the same thing as .new() and .load(). The main difference is you don’t need to give your Settings mutability if you don’t need it.

Will return an empty setting if it fails loading the file for some reason. A warn!() (from the log crate) will be used if the loading fails.

Source

pub fn create_from(file: &File, config: T) -> Result<Settings<T>, Error>

Loads the content of a File using the configuration, but doesn’t use a path or doesn’t infer the path from the config.

Primariy made for testing serializing and deserializing the struture, but can also because to force the setting to load from a file buffer

Source

pub fn create_from_or_empty(file: &File, config: T) -> Settings<T>

Wrapper around load_from so the return value isn’t an result. loads a new setting object from a path, or creates an empty object if file doesn’t exist or errors in any way.

Source

pub fn load(&mut self) -> Result<(), Error>

Loads Setting data from the file defined in the configuration.

If nothing exists it throws an error. This shouldn’t be used for initalizing a new Settings, look at create and create_from for that.

Will override the existing data of a Setting

Source

pub fn load_from(&mut self, file: &mut File) -> Result<(), Error>

Loads into the current Setting from a file.

Will override the existing data of a Setting

Source

pub fn save(&self) -> Result<(), Error>

Saves the setting to a file defined in the configuraton.

Source

pub fn save_to(&self, file: &File) -> Result<(), Error>

saves the setting to a file buffer.

Source

pub fn get_value(&self, key_path: &str) -> Option<Type>

Get the saved value inside of a Setting

Looks for a key_path in dot notation and returns an Option containing the value if it exists.

Source

pub fn get_value_or<A>(&self, key_path: &str, default_value: &A) -> Type
where A: SupportedType + ?Sized,

Wraps get_value so instead of an Option the result will always be a type.

The default value can be any type that implements SupportedType

Source

pub fn set_value<A>(&mut self, key_path: &str, value: &A) -> Result<(), Error>
where A: SupportedType + ?Sized,

sets the value of a key, uses a generic that must implement the SupportedType trait

Source

pub fn delete_key(&mut self, key_path: &str) -> Option<Type>

Deletes the key and returns the current value, returns none if the key didn’t exist.

Source

pub fn delete_file(&self) -> bool

Deletes the physical file from the disk

Source

pub fn keys(&self) -> Vec<String>

Trait Implementations§

Source§

impl<T> Add for Settings<T>
where T: Format + Clone,

Source§

fn add(self, other: Settings<T>) -> Settings<T>

implementing add so you should be able to use ‘+’ on two settings, useful because you may want to combine settings from different locations.

Adding to Settings works by overlaying the two Settings on top of each other, if the same “key” has multiple “values”, the “self” is overwritten with the “other”. So Adding a Settings means you are overlaying it ontop of the existing data.

Source§

type Output = Settings<T>

The resulting type after applying the + operator.
Source§

impl<T> AddAssign for Settings<T>
where T: Format + Clone,

Source§

fn add_assign(&mut self, other: Settings<T>)

AddAssign follows the same logic as Add, and allows you to use += with Settings

Source§

impl<T> Clone for Settings<T>
where T: Format + Clone + Clone,

Source§

fn clone(&self) -> Settings<T>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<'de, T> Deserialize<'de> for Settings<T>
where T: Format + Clone + Deserialize<'de>,

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<T> Serialize for Settings<T>
where T: Format + Clone + Serialize,

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl<T> Freeze for Settings<T>
where T: Freeze,

§

impl<T> RefUnwindSafe for Settings<T>
where T: RefUnwindSafe,

§

impl<T> Send for Settings<T>
where T: Send,

§

impl<T> Sync for Settings<T>
where T: Sync,

§

impl<T> Unpin for Settings<T>
where T: Unpin,

§

impl<T> UnwindSafe for Settings<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,