#[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
impl Ini
Sourcepub fn new() -> Ini
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.
Sourcepub fn new_cs() -> Ini
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.
Sourcepub fn new_from_defaults(defaults: IniDefault) -> Ini
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);
Sourcepub fn defaults(&self) -> IniDefault
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.
Sourcepub fn load_defaults(&mut self, defaults: IniDefault)
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.
Sourcepub fn set_default_section(&mut self, section: &str)
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.
Sourcepub fn set_comment_symbols(&mut self, symlist: &[char])
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.
Sourcepub fn set_inline_comment_symbols(&mut self, symlist: Option<&[char]>)
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.
Sourcepub fn set_multiline(&mut self, multiline: bool)
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.
Sourcepub fn sections(&self) -> Vec<String>
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>
.
Sourcepub fn load<T: AsRef<Path>>(
&mut self,
path: T,
) -> Result<Map<String, Map<String, Option<String>>>, String>
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.
Sourcepub fn load_and_append<T: AsRef<Path>>(
&mut self,
path: T,
) -> Result<Map<String, Map<String, Option<String>>>, String>
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.
Sourcepub fn read(
&mut self,
input: String,
) -> Result<Map<String, Map<String, Option<String>>>, String>
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.
Sourcepub fn read_and_append(
&mut self,
input: String,
) -> Result<Map<String, Map<String, Option<String>>>, String>
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.
Sourcepub fn write<T: AsRef<Path>>(&self, path: T) -> Result<()>
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.
Sourcepub fn pretty_write<T: AsRef<Path>>(
&self,
path: T,
write_options: &WriteOptions,
) -> Result<()>
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.
Sourcepub fn writes(&self) -> String
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.
Sourcepub fn pretty_writes(&self, write_options: &WriteOptions) -> String
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.
Sourcepub fn get(&self, section: &str, key: &str) -> Option<String>
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
.
Sourcepub fn getbool(&self, section: &str, key: &str) -> Result<Option<bool>, String>
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)
.
Sourcepub fn getboolcoerce(
&self,
section: &str,
key: &str,
) -> Result<Option<bool>, String>
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)
.
Sourcepub fn getint(&self, section: &str, key: &str) -> Result<Option<i64>, String>
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)
.
Sourcepub fn getuint(&self, section: &str, key: &str) -> Result<Option<u64>, String>
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)
.
Sourcepub fn getfloat(&self, section: &str, key: &str) -> Result<Option<f64>, String>
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)
.
Sourcepub fn get_map(&self) -> Option<Map<String, Map<String, Option<String>>>>
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
.
Sourcepub fn get_map_ref(&self) -> &Map<String, Map<String, Option<String>>>
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.
Sourcepub fn get_mut_map(&mut self) -> &mut Map<String, Map<String, Option<String>>>
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.
Sourcepub fn set(
&mut self,
section: &str,
key: &str,
value: Option<String>,
) -> Option<Option<String>>
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.
Sourcepub fn setstr(
&mut self,
section: &str,
key: &str,
value: Option<&str>,
) -> Option<Option<String>>
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.
Sourcepub fn clear(&mut self)
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.
Sourcepub fn remove_section(
&mut self,
section: &str,
) -> Option<Map<String, Option<String>>>
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
.
Sourcepub fn remove_key(&mut self, section: &str, key: &str) -> Option<Option<String>>
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
.