Struct Ini

Source
#[non_exhaustive]
pub struct Ini { /* private fields */ }
Expand description

The Ini struct simply contains a nested hashmap of the loaded configuration, the default section header and comment symbols.

§Example

use configparser::ini::Ini;

let mut config = Ini::new();

Implementations§

Source§

impl Ini

Source

pub fn new() -> Ini

Creates a new Map of Map<String, Map<String, Option<String>>> type for the struct. All values in the Map are stored in String type.

By default, std::collections::HashMap is used for the Map object. The indexmap feature can be used to use an [indexmap::map::IndexMap] instead, which allows keeping the insertion order for sections and keys.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();

Returns the struct and stores it in the calling variable.

Source

pub fn new_cs() -> Ini

Creates a new case-sensitive Map of Map<String, Map<String, Option<String>>> type for the struct. All values in the Map are stored in String type.

§Example
use configparser::ini::Ini;

let mut config = Ini::new_cs();

Returns the struct and stores it in the calling variable.

Source

pub fn new_from_defaults(defaults: IniDefault) -> Ini

Creates a new Ini with the given defaults from an existing IniDefault object.

§Example
use configparser::ini::Ini;
use configparser::ini::IniDefault;

let mut default = IniDefault::default();
default.comment_symbols = vec![';'];
default.delimiters = vec!['='];
let mut config = Ini::new_from_defaults(default.clone());
let map = config.load("tests/test.ini").unwrap();
assert_eq!(config.defaults(), default);
Source

pub fn defaults(&self) -> IniDefault

Fetches the defaults from the current Ini object and stores it as a IniDefault struct for usage elsewhere.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();
let default = config.defaults();

Returns an IniDefault object. Keep in mind that it will get borrowed since it has non-Copy types.

Source

pub fn load_defaults(&mut self, defaults: IniDefault)

Takes an IniDefault object and stores its properties in the calling Ini object. This happens in-place and does not work retroactively, only future operations are affected.

§Example
use configparser::ini::Ini;
use configparser::ini::IniDefault;

let mut config = Ini::new();
let mut default = IniDefault::default();
default.case_sensitive = true;
config.load_defaults(default.clone());
assert_eq!(config.defaults(), default);

Returns nothing.

Source

pub fn set_default_section(&mut self, section: &str)

Sets the default section header to the defined string (the default is default). It must be set before load() or read() is called in order to take effect.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();

config.set_default_section("topsecret");
let map = config.load("tests/test.ini").unwrap();

Returns nothing.

Source

pub fn set_comment_symbols(&mut self, symlist: &[char])

Sets the default comment symbols to the defined character slice (the defaults are ; and #). Keep in mind that this will remove the default symbols. It must be set before load() or read() is called in order to take effect.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();
config.set_comment_symbols(&['!', '#']);
let map = config.load("tests/test.ini").unwrap();

Returns nothing.

Source

pub fn set_inline_comment_symbols(&mut self, symlist: Option<&[char]>)

Sets the default inline comment symbols to the defined character slice (the default is None which falls back to the normal comment symbols). Keep in mind that this will remove the default symbols. It must be set before load() or read() is called in order to take effect.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();
config.set_inline_comment_symbols(Some(&['!', '#']));
let map = config.load("tests/test.ini").unwrap();

Returns nothing.

Source

pub fn set_multiline(&mut self, multiline: bool)

Sets multiline string support. It must be set before load() or read() is called in order to take effect.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();
config.set_multiline(true);
let map = config.load("tests/test.ini").unwrap();

Returns nothing.

Source

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

Gets all the sections of the currently-stored Map in a vector.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();
config.load("tests/test.ini");
let sections = config.sections();

Returns Vec<String>.

Source

pub fn load<T: AsRef<Path>>( &mut self, path: T, ) -> Result<Map<String, Map<String, Option<String>>>, String>

Loads a file from a defined path, parses it and puts the hashmap into our struct. At one time, it only stores one configuration, so each call to load() or read() will clear the existing Map, if present.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();
let map = config.load("tests/test.ini").unwrap();  // we can get a clone like this, or just store it
let values = map.get("values").unwrap();

Returns Ok(map) with a clone of the stored Map if no errors are thrown or else Err(error_string). Use get_mut_map() if you want a mutable reference.

Source

pub fn load_and_append<T: AsRef<Path>>( &mut self, path: T, ) -> Result<Map<String, Map<String, Option<String>>>, String>

Loads a file from a defined path, parses it and applies it to the existing hashmap in our struct. While load() will clear the existing Map, load_and_append() applies the new values on top of the existing hashmap, preserving previous values.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();
config.load("tests/test.ini").unwrap();
config.load_and_append("tests/sys_cfg.ini").ok();  // we don't have to worry if this doesn't succeed
config.load_and_append("tests/user_cfg.ini").ok();  // we don't have to worry if this doesn't succeed
let map = config.get_map().unwrap();
let values = map.get("values").unwrap();

Returns Ok(map) with a clone of the stored Map if no errors are thrown or else Err(error_string). Use get_mut_map() if you want a mutable reference.

Source

pub fn read( &mut self, input: String, ) -> Result<Map<String, Map<String, Option<String>>>, String>

Reads an input string, parses it and puts the hashmap into our struct. At one time, it only stores one configuration, so each call to load() or read() will clear the existing Map, if present.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();
let map = match config.read(String::from(
    "[2000s]
    2020 = bad")) {
    Err(why) => panic!("{}", why),
    Ok(inner) => inner
};
let this_year = map["2000s"]["2020"].clone().unwrap();
assert_eq!(this_year, "bad"); // value accessible!

Returns Ok(map) with a clone of the stored Map if no errors are thrown or else Err(error_string). Use get_mut_map() if you want a mutable reference.

Source

pub fn read_and_append( &mut self, input: String, ) -> Result<Map<String, Map<String, Option<String>>>, String>

Reads an input string, parses it and applies it to the existing hashmap in our struct. While read() and load() will clear the existing Map, read_and_append() applies the new values on top of the existing hashmap, preserving previous values.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();
if let Err(why) = config.read(String::from(
    "[2000s]
    2020 = bad
    2023 = better")) {
    panic!("{}", why);
};
if let Err(why) = config.read_and_append(String::from(
    "[2000s]
    2020 = terrible")) {
    panic!("{}", why);
};
let map = config.get_map().unwrap();
let few_years_ago = map["2000s"]["2020"].clone().unwrap();
let this_year = map["2000s"]["2023"].clone().unwrap();
assert_eq!(few_years_ago, "terrible"); // value updated!
assert_eq!(this_year, "better"); // keeps old values!

Returns Ok(map) with a clone of the stored Map if no errors are thrown or else Err(error_string). Use get_mut_map() if you want a mutable reference.

Source

pub fn write<T: AsRef<Path>>(&self, path: T) -> Result<()>

Writes the current configuation to the specified path using default formatting. If a file is not present then it is automatically created for you. If a file already exists then it is overwritten.

§Example
use configparser::ini::Ini;

fn main() -> std::io::Result<()> {
  let mut config = Ini::new();
  config.read(String::from(
    "[2000s]
    2020 = bad"));
  config.write("output.ini")
}

Returns a std::io::Result<()> type dependent on whether the write was successful or not.

Source

pub fn pretty_write<T: AsRef<Path>>( &self, path: T, write_options: &WriteOptions, ) -> Result<()>

Writes the current configuation to the specified path using the given formatting options. If a file is not present then it is automatically created for you. If a file already exists then it is overwritten.

§Example
use configparser::ini::{Ini, WriteOptions};

fn main() -> std::io::Result<()> {
  let mut write_options = WriteOptions::default();
  write_options.space_around_delimiters = true;
  write_options.multiline_line_indentation = 2;
  write_options.blank_lines_between_sections = 1;

  let mut config = Ini::new();
  config.read(String::from(
    "[2000s]
    2020 = bad"));
  config.pretty_write("output.ini", &write_options)
}

Returns a std::io::Result<()> type dependent on whether the write was successful or not.

Source

pub fn writes(&self) -> String

Returns a string with the current configuration formatted with valid ini-syntax using default formatting. This is always safe since the configuration is validated during parsing.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();
config.read(String::from(
  "[2000s]
  2020 = bad"));
let outstring = config.writes();

Returns a String type contatining the ini-syntax file.

Source

pub fn pretty_writes(&self, write_options: &WriteOptions) -> String

Returns a string with the current configuration formatted with valid ini-syntax using the given formatting options. This is always safe since the configuration is validated during parsing.

§Example
use configparser::ini::{Ini, WriteOptions};

let mut write_options = WriteOptions::default();
write_options.space_around_delimiters = true;
write_options.multiline_line_indentation = 2;
write_options.blank_lines_between_sections = 1;

let mut config = Ini::new();
config.read(String::from(
  "[2000s]
  2020 = bad"));
let outstring = config.pretty_writes(&write_options);

Returns a String type contatining the ini-syntax file.

Source

pub fn get(&self, section: &str, key: &str) -> Option<String>

Returns a clone of the stored value from the key stored in the defined section. Unlike accessing the map directly, get() can process your input to make case-insensitive access if the default constructor is used. All get functions will do this automatically under the hood.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();
config.load("tests/test.ini");
let value = config.get("default", "defaultvalues").unwrap();
assert_eq!(value, String::from("defaultvalues"));

Returns Some(value) of type String if value is found or else returns None.

Source

pub fn getbool(&self, section: &str, key: &str) -> Result<Option<bool>, String>

Parses the stored value from the key stored in the defined section to a bool. For ease of use, the function converts the type case-insensitively (true == True).

§Example
use configparser::ini::Ini;

let mut config = Ini::new();
config.load("tests/test.ini");
let value = config.getbool("values", "bool").unwrap().unwrap();
assert!(value);  // value accessible!

Returns Ok(Some(value)) of type bool if value is found or else returns Ok(None). If the parsing fails, it returns an Err(string).

Source

pub fn getboolcoerce( &self, section: &str, key: &str, ) -> Result<Option<bool>, String>

Parses the stored value from the key stored in the defined section to a bool. For ease of use, the function converts the type coerces a match. It attempts to case-insenstively find true, yes, t, y, 1 and on to parse it as True. Similarly it attempts to case-insensitvely find false, no, f, n, 0 and off to parse it as False.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();
config.load("tests/test.ini");
let value = config.getboolcoerce("values", "boolcoerce").unwrap().unwrap();
assert!(!value);  // value accessible!

Returns Ok(Some(value)) of type bool if value is found or else returns Ok(None). If the parsing fails, it returns an Err(string).

Source

pub fn getint(&self, section: &str, key: &str) -> Result<Option<i64>, String>

Parses the stored value from the key stored in the defined section to an i64.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();
config.load("tests/test.ini");
let value = config.getint("values", "int").unwrap().unwrap();
assert_eq!(value, -31415);  // value accessible!

Returns Ok(Some(value)) of type i64 if value is found or else returns Ok(None). If the parsing fails, it returns an Err(string).

Source

pub fn getuint(&self, section: &str, key: &str) -> Result<Option<u64>, String>

Parses the stored value from the key stored in the defined section to a u64.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();
config.load("tests/test.ini");
let value = config.getint("values", "Uint").unwrap().unwrap();
assert_eq!(value, 31415);  // value accessible!

Returns Ok(Some(value)) of type u64 if value is found or else returns Ok(None). If the parsing fails, it returns an Err(string).

Source

pub fn getfloat(&self, section: &str, key: &str) -> Result<Option<f64>, String>

Parses the stored value from the key stored in the defined section to a f64.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();
config.load("tests/test.ini");
let value = config.getfloat("values", "float").unwrap().unwrap();
assert_eq!(value, 3.1415);  // value accessible!

Returns Ok(Some(value)) of type f64 if value is found or else returns Ok(None). If the parsing fails, it returns an Err(string).

Source

pub fn get_map(&self) -> Option<Map<String, Map<String, Option<String>>>>

Returns a clone of the Map stored in our struct.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();
config.read(String::from(
  "[section]
  key=values"));
let map = config.get_map().unwrap();
assert_eq!(map, *config.get_map_ref());  // the cloned map is basically a snapshot that you own

Returns Some(map) if map is non-empty or else returns None. Similar to load() but returns an Option type with the currently stored Map.

Source

pub fn get_map_ref(&self) -> &Map<String, Map<String, Option<String>>>

Returns an immutable reference to the Map stored in our struct.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();
let mapclone = config.read(String::from
  ("[topsecrets]
  Valueless key")).unwrap();
assert_eq!(*config.get_map_ref(), mapclone);  // same as expected.

If you just need to definitely mutate the map, use get_mut_map() instead. Alternatively, you can generate a snapshot by getting a clone with get_map() and work with that.

Source

pub fn get_mut_map(&mut self) -> &mut Map<String, Map<String, Option<String>>>

Returns a mutable reference to the Map stored in our struct.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();
config.read(String::from
  ("[topsecrets]
  Valueless key"));
config.get_mut_map().get_mut("topsecrets").unwrap().insert(String::from("nuclear launch codes"), None);
assert_eq!(config.get("topsecrets", "nuclear launch codes"), None);  // inserted successfully!

If you just need to access the map without mutating, use get_map_ref() or make a clone with get_map() instead.

Source

pub fn set( &mut self, section: &str, key: &str, value: Option<String>, ) -> Option<Option<String>>

Sets an Option<String> in the Map stored in our struct. If a particular section or key does not exist, it will be automatically created. An existing value in the map will be overwritten. You can also set None safely.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();
config.read(String::from(
  "[section]
  key=value"));
let key_value = String::from("value");
config.set("section", "key", Some(key_value));
config.set("section", "key", None);  // also valid!
assert_eq!(config.get("section", "key"), None);  // correct!

Returns None if there is no existing value, else returns Some(Option<String>), with the existing value being the wrapped Option<String>. If you want to insert using a string literal, use setstr() instead.

Source

pub fn setstr( &mut self, section: &str, key: &str, value: Option<&str>, ) -> Option<Option<String>>

Sets an Option<&str> in the Map stored in our struct. If a particular section or key does not exist, it will be automatically created. An existing value in the map will be overwritten. You can also set None safely.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();
config.read(String::from(
  "[section]
  key=notvalue"));
config.setstr("section", "key", Some("value"));
config.setstr("section", "key", None);  // also valid!
assert_eq!(config.get("section", "key"), None);  // correct!

Returns None if there is no existing value, else returns Some(Option<String>), with the existing value being the wrapped Option<String>. If you want to insert using a String, use set() instead.

Source

pub fn clear(&mut self)

Clears the map, removing all sections and properties from the hashmap. It keeps the allocated memory for reuse.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();
config.read(String::from(
  "[section]
  key=somevalue"));
config.clear();
assert!(config.get_map_ref().is_empty());  // our map is empty!

Returns nothing.

Source

pub fn remove_section( &mut self, section: &str, ) -> Option<Map<String, Option<String>>>

Removes a section from the hashmap, returning the properties stored in the section if the section was previously in the map.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();
config.read(String::from(
  "[section]
  updog=whatsupdog"));
config.remove_section("section");  // this will return a cloned hashmap of the stored property
assert!(config.get_map_ref().is_empty());  // with the last section removed, our map is now empty!

Returns Some(section_map) if the section exists or else, None.

Source

pub fn remove_key(&mut self, section: &str, key: &str) -> Option<Option<String>>

Removes a key from a section in the hashmap, returning the value attached to the key if it was previously in the map.

§Example
use configparser::ini::Ini;

let mut config = Ini::new();
config.read(String::from(
  "[section]
  updog=whatsupdog
  [anothersection]
  updog=differentdog"));
let val = config.remove_key("anothersection", "updog").unwrap().unwrap();
assert_eq!(val, String::from("differentdog"));  // with the last section removed, our map is now empty!

Returns Some(Option<String>) if the value exists or else, None.

Trait Implementations§

Source§

impl Clone for Ini

Source§

fn clone(&self) -> Ini

Returns a copy 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 Debug for Ini

Source§

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

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

impl Default for Ini

Source§

fn default() -> Ini

Returns the “default value” for a type. Read more
Source§

impl PartialEq for Ini

Source§

fn eq(&self, other: &Ini) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for Ini

Source§

impl StructuralPartialEq for Ini

Auto Trait Implementations§

§

impl Freeze for Ini

§

impl RefUnwindSafe for Ini

§

impl Send for Ini

§

impl Sync for Ini

§

impl Unpin for Ini

§

impl UnwindSafe for Ini

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.