Skip to main content

Ini

Struct Ini 

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

Structure for INI-file data

Implementations§

Source§

impl Ini

Source

pub fn new() -> Ini

Create an empty Ini (similar to Ini::default)

Source

pub fn from_file<S>(path: &S) -> Result<Ini, Error>
where S: AsRef<Path> + ?Sized,

Construct Ini from file

§Errors

This function will return an Error if file cannot be opened or parsed

§Examples

You may use Path

let path = Path::new("example.ini");

let conf = Ini::from_file(path);

assert!(conf.ok().is_some());

or &str

let conf = Ini::from_file("example.ini");

assert!(conf.ok().is_some());
Source

pub fn from_reader<R>(reader: &mut R) -> Result<Ini, Error>
where R: Read,

Construct Ini from any struct who implement Read trait

§Errors

This function will return an Error if reader cannot be read or parsed

§Example
let f = "[section]\nitem=value".as_bytes();
let mut reader = BufReader::new(f);

let conf = Ini::from_reader(&mut reader);

assert!(conf.ok().is_some());
Source

pub fn from_string<S>(buf: S) -> Result<Ini, Error>
where S: Into<String>,

Construct Ini from any type of string which can be Intoed to String

§Errors

This function will return an Error if buffer cannot be parsed

§Example
let conf = Ini::from_string("[section]\none = 1").unwrap();

let value: Option<u8> = conf.get("section", "one");
assert_eq!(value, Some(1));
Source

pub fn to_file<S>(&self, path: &S) -> Result<(), Error>
where S: AsRef<Path> + ?Sized,

Write Ini to file. This function is similar to from_file in use.

§Errors

Errors returned by File::create and Write::write_all

Source

pub fn to_writer<W>(&self, writer: &mut W) -> Result<(), Error>
where W: Write,

Write Ini to any struct who implement Write trait.

§Errors

Errors returned by Write::write_all

§Example
let conf = Ini::default().section("a").item("a", 1);

// create output Vec<u8> buffer
let mut output = Vec::new();
// let's write data to Vec<u8>
conf.to_writer(&mut output);

// cast Vec<u8> to utf-8 string
let casted_result = String::from_utf8(output).unwrap();
assert_eq!(casted_result, "[a]\na = 1\n")
Source

pub fn section<S>(self, name: S) -> Self
where S: Into<String>,

Set section name for the following methods in chain (item(), items(), etc.)

§Warning

This function doesn’t create a section.

§Example
let mut conf = Ini::new().section("empty");
assert_eq!(conf.to_string(), "");

// but section will be created on item() call
conf = conf.section("one").item("a", 1);
assert_eq!(conf.to_string(), "[one]\na = 1\n");
Source

pub fn item<N, V>(self, name: N, value: V) -> Self
where N: Into<String>, V: Display,

Add key-value pair to the end of section, specified in last section() call, or replace value if key already in section

§Example
let mut conf = Ini::new().section("test")
                     .item("value", 10);

assert_eq!(conf.to_string(), "[test]\nvalue = 10\n");

// change existing value
conf = conf.section("test").item("value", "updated");
assert_eq!(conf.to_string(), "[test]\nvalue = updated\n");
Source

pub fn item_vec_with_sep<S, V>(self, name: S, vector: &[V], sep: &str) -> Self
where S: Into<String>, V: Display,

Like item(), but for vectors

  • name must support Into to String
  • vector elements must support Display to support conversion to String
  • sep arbitrary string delimiter
§Example
let conf = Ini::new()
    .section("default")
// add a vector with `,` separator: 1,2,3,4
    .item_vec_with_sep("a", &[1, 2, 3, 4], ",")
// add a vector with `|` separator: a|b|c
    .item_vec_with_sep("b", &vec!["a", "b", "c"], "|");

let va: Option<Vec<u8>> = conf.get_vec("default", "a");
let vb: Vec<String> = conf.get_vec_with_sep("default", "b", "|").unwrap();

assert_eq!(va, Some(vec![1, 2, 3, 4]));
assert_eq!(vb, ["a", "b", "c"]);
Source

pub fn item_vec<S, V>(self, name: S, vector: &[V]) -> Self
where S: Into<String>, V: Display,

Equivalent of item_vec_with_sep(name, vector, ", ")

§Example
let conf = Ini::new()
    .section("default")
// add vector with default separator `, `
    .item_vec("a", &[1, 2, 3, 4])
// and another vector
    .item_vec("b", &vec!["a", "b", "c"]);

let va: Option<Vec<u8>> = conf.get_vec("default", "a");
let vb: Vec<String> = conf.get_vec("default", "b").unwrap();

assert_eq!(va, Some(vec![1, 2, 3, 4]));
assert_eq!(vb, ["a", "b", "c"]);
Source

pub fn items<K, V, I>(self, items: I) -> Self
where K: Into<String>, V: Display, I: IntoIterator<Item = (K, V)>,

Append pairs from any object supporting IntoIterator to the section, specified in last section() call.

§Example
use std::collections::HashMap;

let mut conf = Ini::new()
               .section("colors")
               .items(vec![("black", "#000000"),
                           ("white", "#ffffff")]);

// create custom section
let mut numbers = HashMap::new();
numbers.insert("round_pi", 3);
// and add to `conf`
conf = conf.section("numbers").items(numbers);

assert_eq!(conf.to_string(), [
                              "[colors]",
                              "black = #000000",
                              "white = #ffffff",
                              "",
                              "[numbers]",
                              "round_pi = 3",
                              ""
                             ].join("\n"));
Source

pub fn clear(self) -> Self

Remove section from Ini.

§Example
let mut config = Ini::from_string([
                                   "[one]",
                                   "a = 1",
                                   "[two]",
                                   "b = 2"
                                  ].join("\n")).unwrap();
// remove section
config = config.section("one").clear();
assert_eq!(config.to_string(), "[two]\nb = 2\n");

// clear section from old data and add new
config = config.section("two").clear().item("a", 1);
assert_eq!(config.to_string(), "[two]\na = 1\n");
Source

pub fn erase(self, key: &str) -> Self

Remove item from section.

§Example
let mut config = Ini::from_string([
                                   "[one]",
                                   "a = 1",
                                   "b = 2"
                                  ].join("\n")).unwrap();

config = config.section("one").erase("b");

assert_eq!(config.to_string(), "[one]\na = 1\n");
Source

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

Get scalar value of key in section.

  • output type T must implement FromStr trait for auto conversion
§Example
let conf = Ini::from_string("[section]\none = 1").unwrap();

let value: Option<u8> = conf.get("section", "one");

assert_eq!(value, Some(1));
Source

pub fn get_vec<T>(&self, section: &str, key: &str) -> Option<Vec<T>>
where T: FromStr,

Get vector value of key in section. Value should use , as separator.

The function returns None if one of the elements can not be parsed.

  • output type T must implement FromStr trait for auto conversion
§Example
let conf = Ini::from_string("[section]\nlist = 1, 2, 3, 4").unwrap();

let value: Option<Vec<u8>> = conf.get_vec("section", "list");

assert_eq!(value, Some(vec![1, 2, 3, 4]));
Source

pub fn get_vec_with_sep<T>( &self, section: &str, key: &str, sep: &str, ) -> Option<Vec<T>>
where T: FromStr,

Get vector value of key in section separated by sep string.

The function returns None if one of the elements can not be parsed or not found.

  • output type T must implement FromStr trait for auto conversion
§Example
let conf = Ini::from_string("[section]\nlist = 1|2|3|4").unwrap();

let value: Option<Vec<u8>> = conf.get_vec_with_sep("section", "list", "|");

assert_eq!(value, Some(vec![1, 2, 3, 4]));
Source

pub fn section_iter(&self, section: &str) -> SectionIter<'_>

An iterator visiting all key-value pairs of a section in order of appearance.

If section with given name doesn’t exist in document, method returns empty iterator

§Example
let conf = Ini::from_string(["[search]",
                             "g = google.com",
                             "dd = duckduckgo.com"].join("\n")).unwrap();

let mut search = conf.section_iter("search");
assert_eq!(search.next(), Some((&"g".to_string(), &"google.com".to_string())));
assert_eq!(search.next(), Some((&"dd".to_string(), &"duckduckgo.com".to_string())));
assert_eq!(search.next(), None);

assert_eq!(conf.section_iter("absent").count(), 0);
Source

pub fn iter(&self) -> IniIter<'_>

Iterate over all sections in order of appearance, yielding pairs of section name and section instance, which can be iterated over or queried similarly to Ini instances.

§Example
let conf = Ini::new().section("foo")
                     .item("item", "value")
                     .item("other", "something")
                     .section("bar")
                     .item("one", "1");

for (name, section) in conf.iter() {
    match name.as_str() {
        "foo" => assert_eq!(section.iter().count(), 2),
        "bar" => assert_eq!(section.iter().count(), 1),
        _ => assert!(false),
    }
}
Source

pub fn iter_mut(&mut self) -> IniIterMut<'_>

Iterate over all sections in arbitrary order, yielding pairs of section name and mutable iterator over the section elements. The concrete iterator element type is (&'a String, SectionIterMut<'a>).

§Example
let mut conf = Ini::new().section("foo")
                         .item("item", "value")
                         .item("other", "something")
                         .section("bar")
                         .item("one", "1");

for (name, section) in conf.iter_mut() {
    for (key, val) in section.iter_mut() {
        *val = String::from("replaced");
    }
}

for (name, section) in conf.iter() {
    for (key, val) in section.iter() {
        assert_eq!(val.as_str(), "replaced");
    }
}

Trait Implementations§

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() -> Self

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

impl Display for Ini

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Ini

§

impl RefUnwindSafe for Ini

§

impl Send for Ini

§

impl Sync for Ini

§

impl Unpin for Ini

§

impl UnsafeUnpin 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> 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.