Struct Settings

Source
pub struct Settings { /* private fields */ }
Expand description

Setting structure It is composed by 3 private attributes ‘path’ contains the path of the loaded settings file ‘sections’ is a vector containing Section structures inside the settings file ‘messages_table’ is a vector of strings representing all error generated by Settings

Implementations§

Source§

impl Settings

Source

pub fn new() -> Self

Associated function to create a Settings structure This function initialize the messages table with the default english language Returns an empty Setting structure

§Examples
use rssettings::Settings;
 
fn main() {
    let mut settings = Settings::new();
}
Source

pub fn new_locale_messages(settings_messages: &[&str; 12]) -> Self

Associated function to create a Settings structure This function initialize the messages table with the the user language messages ‘settings_messages’ messages vector passed has reference Returns an empty Setting structure

§Examples
use rssettings::{Settings,MESSAGES_NUMBER};
const IT_SETTINGS_MESSAGES: [&str; MESSAGES_NUMBER] = [
    "Errore apertura file di settings: '{}': '{}'",
    "Manca il tag di inizio sezione '{}' alla linea '{}' del file di settings: '{}'",
    "Manca il tag di fine sezione '{}' alla linea '{}' del file di settings: '{}'",
    "Manca il tag di assegnazione '{}' alla linea '{}' del file di settings: '{}'",
    "Manca la chiave alla linea '{}' del file di settings: '{}'",
    "Chiave duplicata '{}' alla linea '{}' precedentemente definita alla linea '{}' del file di settings: '{}'",
    "Sezione '{}' non trovata",
    "Sezione '{}' chiave '{}' non trovata",
    "Sezione '{}' chiave '{}', Errore di analisi: '{}'",
    "Errore scrittura file: '{}': '{}'",
    "Errore lettura file: '{}' alla line {}: '{}'",
    "Settings già inizializzato utilizzando il file: '{}'"
];
fn main()  {
    let mut settings = Settings::new_locale_messages(&IT_SETTINGS_MESSAGES);
    match settings.load("settings.ini") {
        Result::Ok(()) => {
        },
        Result::Err(error) => {
            eprintln!("{}", error);
        }
    }
}
  • settings_messages - A string slice vector that holds the setting error messages
Source

pub fn load<P>(&mut self, path: P) -> StdResult<(), String>
where P: AsRef<Path>,

Load a settings file Returns std::result::Result::Ok(()) if settings file correctly loaded or std::result::Result::Err(error: String) if something has gone wrong error contains a message (in english or user language according to user created Setting, Settings::new or Settings::new_locale_messages) describing the problem

§Examples
use rssettings::Settings;
 
fn main() {
    let mut settings = Settings::new();
    match settings.load("test_files/settings.ini") {
        Result::Ok(()) => {
        },
        Result::Err(error) => {
            eprintln!("{}", error);
        }
    }
}
  • self - An mutable reference to Setting struct
  • path - A Path as reference to the settings file to load
Source

pub fn save(&self) -> StdResult<(), String>

Save Settings in the file used to load it User can save Settings every time it changes one of its section/key_value pair or let the Settings save itself when it is dropped see trait Drop implementation Returns std::result::Result::Ok(()) when saving is successfuly done or std::result::Result::Err(error: String) when a problem occured error message language depends on new associated function used to crete Settings

§Examples
use rssettings::Settings;
 
fn main() {
    let mut settings = Settings::new();
    match settings.load("test_files/settings.ini") {
        Result::Ok(()) => {
            if let Result::Ok(()) = settings.set("GLOBAL", "bool_value", true) {
                if let Result::Err(error) = settings.save() {
                    eprintln!("{}", error);
                }
            }
        },
        Result::Err(error) => {
            eprintln!("{}", error);
        }
    }
}
  • self - A mutable reference to Setting struct
Source

pub fn get<T: FromStr + Display>( &self, section_name: &str, key: &str, default_value: T, ) -> SettingsValue<T>
where <T as FromStr>::Err: Debug,

Generic method use to get section/key value Generic type parameter has to implement FromStr & Display traits Returns a SettingsValue structure containing the value associated with the section and the key if both exist or a default value if not ad SettingsValue.error set with the relative error message
error message language depends on new associated function used to crete Settings

§Examples
use rssettings::Settings;
 
fn main() {
    let mut settings = Settings::new();
    match settings.load("test_files/settings.ini") {
        Result::Ok(()) => {
            let bool_value = settings.get("GLOBAL", "bool_value", false);
            if bool_value.error.len() == 0 {
                assert_eq!(true, bool_value.value);
            } else {
                eprintln!("{}", bool_value.error);
            }
        },
        Result::Err(error) => {
            eprintln!("{}", error);
        }
    }
}
  • self - An immutable reference to Setting struct
  • section_name - A string slice that holds the name of the Section
  • key - A string slice that holds the name of the key inside the Section
  • T - A default generic value returned in case an error occurs
Source

pub fn set<T: Display>( &mut self, section_name: &str, key: &str, value: T, ) -> StdResult<(), String>

§Examples
use rssettings::Settings;
 
fn main() {
    let mut settings = Settings::new();
    match settings.load("test_files/settings.ini") {
        Result::Ok(()) => {
            let orig_bool_value = settings.get("GLOBAL", "bool_value", false);
            if orig_bool_value.error.len() == 0 {
                settings.set("GLOBAL", "bool_value", false).unwrap_or_else(|error| {
                    eprintln!("{}", error);
                });
                let new_bool_value = settings.get("GLOBAL", "bool_value", true);
                assert_ne!(orig_bool_value.value, new_bool_value.value);
                settings.set("GLOBAL", "bool_value", true).unwrap_or_else(|error| {
                    eprintln!("{}", error);
                });
            } else {
                eprintln!("{}", orig_bool_value.error);
            }
        },
        Result::Err(error) => {
            eprintln!("{}", error);
        }
    }
}
  • self - A mutable reference to Setting struct
  • section_name - A string slice that holds the name of the Section
  • key - A string slice that holds the name of the key inside the Section
  • T - A new value for the key
Source

pub fn section_exists(&self, section_name: &str) -> bool

Returns if a section exists

§Examples
use rssettings::Settings;
 
fn main() {
    let mut settings = Settings::new();
    match settings.load("test_files/settings.ini") {
        Result::Ok(()) => {
            if settings.section_exists("GOOFY") {
                println!("[GOOFY] exists"); 
            } else {
                eprintln!("[GOOFY] does not exist");
            }
        },
        Result::Err(error) => {
            eprintln!("{}", error);
        }
    }
}
  • self - An immutable reference to Setting struct
  • section_name - A string slice that holds the name of the Section
Source

pub fn key_exists(&self, section_name: &str, key: &str) -> bool

Returns if a key exists in a specific section

§Examples
use rssettings::Settings;
 
fn main() {
    let mut settings = Settings::new();
    match settings.load("test_files/settings.ini") {
        Result::Ok(()) => {
            if settings.key_exists("GLOBAL", "enabled") {
                println!("key 'enabled' in section 'GLOBAL' exists"); 
            } else {
                eprintln!("key 'enabled' in section 'GLOBAL' does not exist"); 
            }
        },
        Result::Err(error) => {
            eprintln!("{}", error);
        }
    }
}
  • self - An immutable reference to Setting struct
  • section_name - A string slice that holds the name of the Section
  • key - A string slice that holds the name of the key inside the Section

Trait Implementations§

Source§

impl Display for Settings

implementation of Display trait for the Settings structure

§Examples

use rssettings::Settings;
 
fn main() {
    let mut settings = Settings::new();
    settings.load("test_files/settings");
    println!("{}", settings);
}
 
Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Drop for Settings

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

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> 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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. 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.