Struct tini::Ini[][src]

pub struct Ini { /* fields omitted */ }
Expand description

Structure for INI-file data

Implementations

impl Ini[src]

pub fn new() -> Ini[src]

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

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

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

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

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

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

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));

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

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

Errors

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

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

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")

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

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");

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

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");

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

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"]);

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

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"]);

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

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"));

pub fn clear(self) -> Self[src]

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");

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

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");

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

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));

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

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]));

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

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]));

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

Notable traits for SectionIter<'a>

impl<'a> Iterator for SectionIter<'a> type Item = (&'a String, &'a String);
[src]

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

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);

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

Notable traits for IniIter<'a>

impl<'a> Iterator for IniIter<'a> type Item = (&'a String, SectionIter<'a>);
[src]

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

Example

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

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

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

Notable traits for IniIterMut<'a>

impl<'a> Iterator for IniIterMut<'a> type Item = (&'a String, SectionIterMut<'a>);
[src]

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_iter) in conf.iter_mut() {
    for (key, val) in section_iter {
        *val = String::from("replaced");
    }
}

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

Trait Implementations

impl Debug for Ini[src]

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

Formats the value using the given formatter. Read more

impl Default for Ini[src]

fn default() -> Self[src]

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

impl Display for Ini[src]

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

Formats the value using the given formatter. Read more

Auto Trait Implementations

impl RefUnwindSafe for Ini

impl Send for Ini

impl Sync for Ini

impl Unpin for Ini

impl UnwindSafe for Ini

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

pub fn type_id(&self) -> TypeId[src]

Gets the TypeId of self. Read more

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

pub fn borrow(&self) -> &T[src]

Immutably borrows from an owned value. Read more

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

pub fn borrow_mut(&mut self) -> &mut T[src]

Mutably borrows from an owned value. Read more

impl<T> From<T> for T[src]

pub fn from(t: T) -> T[src]

Performs the conversion.

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

pub fn into(self) -> U[src]

Performs the conversion.

impl<T> ToString for T where
    T: Display + ?Sized
[src]

pub default fn to_string(&self) -> String[src]

Converts the given value to a String. Read more

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

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

Performs the conversion.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

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

The type returned in the event of a conversion error.

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

Performs the conversion.