Debian Codegraph @

src/ini.rs

raw symbols SCIP
1 //!The ini module provides all the things necessary to load and parse ini-syntax files. The most important of which is the `Ini` struct.
2 //!See the [implementation](https://docs.rs/configparser/*/configparser/ini/struct.Ini.html) documentation for more details.
3 #[cfg(feature = "indexmap")]
4 use indexmap::IndexMap as Map;
5 #[cfg(not(feature = "indexmap"))]
6 use std::collections::HashMap as Map;
7
8 #[cfg(feature = "async-std")]
9 use async_std::{fs as async_fs, path::Path as AsyncPath};
10
11 use std::collections::HashMap;
12 use std::convert::AsRef;
13 use std::fmt::Write;
14 use std::fs;
15 use std::path::Path;
16
17 ///The `Ini` struct simply contains a nested hashmap of the loaded configuration, the default section header and comment symbols.
18 ///## Example
19 ///```rust
20 ///use configparser::ini::Ini;
21 ///
22 ///let mut config = Ini::new();
23 ///```
24 #[derive(Debug, Clone, Eq, PartialEq, Default)]
25 #[non_exhaustive]
26 pub struct Ini {
27 map: Map<String, Map<String, Option<String>>>,
28 default_section: std::string::String,
29 comment_symbols: Vec<char>,
30 delimiters: Vec<char>,
31 boolean_values: HashMap<bool, Vec<String>>,
32 case_sensitive: bool,
33 multiline: bool,
34 }
35
36 ///The `IniDefault` struct serves as a template to create other `Ini` objects from. It can be used to store and load
37 ///default properties from different `Ini` objects.
38 ///## Example
39 ///```rust
40 ///use configparser::ini::Ini;
41 ///
42 ///let mut config = Ini::new();
43 ///let default = config.defaults();
44 ///let mut config2 = Ini::new_from_defaults(default); // default gets consumed
45 ///```
46 #[derive(Debug, Clone, Eq, PartialEq)]
47 #[non_exhaustive]
48 pub struct IniDefault {
49 ///Denotes the default section header name.
50 ///## Example
51 ///```rust
52 ///use configparser::ini::Ini;
53 ///
54 ///let mut config = Ini::new();
55 ///let default = config.defaults();
56 ///assert_eq!(default.default_section, "default");
57 ///```
58 pub default_section: std::string::String,
59 ///Denotes the set comment symbols for the object.
60 ///## Example
61 ///```rust
62 ///use configparser::ini::Ini;
63 ///
64 ///let mut config = Ini::new();
65 ///let default = config.defaults();
66 ///assert_eq!(default.comment_symbols, vec![';', '#']);
67 ///```
68 pub comment_symbols: Vec<char>,
69 ///Denotes the set delimiters for the key-value pairs.
70 ///## Example
71 ///```rust
72 ///use configparser::ini::Ini;
73 ///
74 ///let mut config = Ini::new();
75 ///let default = config.defaults();
76 ///assert_eq!(default.delimiters, vec!['=', ':']);
77 ///```
78 pub delimiters: Vec<char>,
79 pub boolean_values: HashMap<bool, Vec<String>>,
80 ///Denotes if the `Ini` object is case-sensitive.
81 ///## Example
82 ///```rust
83 ///use configparser::ini::Ini;
84 ///
85 ///let mut config = Ini::new();
86 ///let default = config.defaults();
87 ///assert_eq!(default.case_sensitive, false);
88 ///```
89 pub case_sensitive: bool,
90 ///Denotes if the `Ini` object parses multiline strings.
91 ///## Example
92 ///```rust
93 ///use configparser::ini::Ini;
94 ///
95 ///let mut config = Ini::new();
96 ///let default = config.defaults();
97 ///assert_eq!(default.multiline, false);
98 ///```
99 pub multiline: bool,
100 }
101
102 impl Default for IniDefault {
103 fn default() -> Self {
104 Self {
105 default_section: "default".to_owned(),
106 comment_symbols: vec![';', '#'],
107 delimiters: vec!['=', ':'],
108 multiline: false,
109 boolean_values: [
110 (
111 true,
112 vec!["true", "yes", "t", "y", "on", "1"]
113 .iter()
114 .map(|&s| s.to_owned())
115 .collect(),
116 ),
117 (
118 false,
119 vec!["false", "no", "f", "n", "off", "0"]
120 .iter()
121 .map(|&s| s.to_owned())
122 .collect(),
123 ),
124 ]
125 .iter()
126 .cloned()
127 .collect(),
128 case_sensitive: false,
129 }
130 }
131 }
132
133 #[cfg(windows)]
134 const LINE_ENDING: &str = "\r\n";
135 #[cfg(not(windows))]
136 const LINE_ENDING: &str = "\n";
137
138 impl Ini {
139 ///Creates a new `Map` of `Map<String, Map<String, Option<String>>>` type for the struct.
140 ///All values in the Map are stored in `String` type.
141 ///
142 ///By default, [`std::collections::HashMap`] is used for the Map object.
143 ///The `indexmap` feature can be used to use an [`indexmap::map::IndexMap`] instead, which
144 ///allows keeping the insertion order for sections and keys.
145 ///
146 ///## Example
147 ///```rust
148 ///use configparser::ini::Ini;
149 ///
150 ///let mut config = Ini::new();
151 ///```
152 ///Returns the struct and stores it in the calling variable.
153 pub fn new() -> Ini {
154 Ini::new_from_defaults(IniDefault::default())
155 }
156
157 ///Creates a new **case-sensitive** `Map` of `Map<String, Map<String, Option<String>>>` type for the struct.
158 ///All values in the Map are stored in `String` type.
159 ///## Example
160 ///```rust
161 ///use configparser::ini::Ini;
162 ///
163 ///let mut config = Ini::new_cs();
164 ///```
165 ///Returns the struct and stores it in the calling variable.
166 pub fn new_cs() -> Ini {
167 Ini::new_from_defaults(IniDefault {
168 case_sensitive: true,
169 ..Default::default()
170 })
171 }
172
173 ///Creates a new `Ini` with the given defaults from an existing `IniDefault` object.
174 ///## Example
175 ///```rust
176 ///use configparser::ini::Ini;
177 ///use configparser::ini::IniDefault;
178 ///
179 ///let mut default = IniDefault::default();
180 ///default.comment_symbols = vec![';'];
181 ///default.delimiters = vec!['='];
182 ///let mut config = Ini::new_from_defaults(default.clone());
183 ///// Now, load as usual with new defaults:
184 ///let map = config.load("tests/test.ini").unwrap();
185 ///assert_eq!(config.defaults(), default);
186 ///
187 ///```
188 pub fn new_from_defaults(defaults: IniDefault) -> Ini {
189 Ini {
190 map: Map::new(),
191 default_section: defaults.default_section,
192 comment_symbols: defaults.comment_symbols,
193 delimiters: defaults.delimiters,
194 boolean_values: defaults.boolean_values,
195 case_sensitive: defaults.case_sensitive,
196 multiline: defaults.multiline,
197 }
198 }
199
200 ///Fetches the defaults from the current `Ini` object and stores it as a `IniDefault` struct for usage elsewhere.
201 ///## Example
202 ///```rust
203 ///use configparser::ini::Ini;
204 ///
205 ///let mut config = Ini::new();
206 ///let default = config.defaults();
207 ///```
208 ///Returns an `IniDefault` object. Keep in mind that it will get borrowed since it has non-`Copy` types.
209 pub fn defaults(&self) -> IniDefault {
210 IniDefault {
211 default_section: self.default_section.to_owned(),
212 comment_symbols: self.comment_symbols.to_owned(),
213 delimiters: self.delimiters.to_owned(),
214 boolean_values: self.boolean_values.to_owned(),
215 case_sensitive: self.case_sensitive,
216 multiline: self.multiline,
217 }
218 }
219
220 ///Takes an `IniDefault` object and stores its properties in the calling `Ini` object. This happens in-place and
221 ///does not work retroactively, only future operations are affected.
222 ///## Example
223 ///```rust
224 ///use configparser::ini::Ini;
225 ///use configparser::ini::IniDefault;
226 ///
227 ///let mut config = Ini::new();
228 ///let mut default = IniDefault::default();
229 ///default.case_sensitive = true;
230 ///// This is equivalent to ini_cs() defaults
231 ///config.load_defaults(default.clone());
232 ///assert_eq!(config.defaults(), default);
233 ///```
234 ///Returns nothing.
235 pub fn load_defaults(&mut self, defaults: IniDefault) {
236 self.default_section = defaults.default_section;
237 self.comment_symbols = defaults.comment_symbols;
238 self.delimiters = defaults.delimiters;
239 self.boolean_values = defaults.boolean_values;
240 self.case_sensitive = defaults.case_sensitive;
241 }
242
243 ///Sets the default section header to the defined string (the default is `default`).
244 ///It must be set before `load()` or `read()` is called in order to take effect.
245 ///## Example
246 ///```rust
247 ///use configparser::ini::Ini;
248 ///
249 ///let mut config = Ini::new();
250 ///
251 ///config.set_default_section("topsecret");
252 ///let map = config.load("tests/test.ini").unwrap();
253 ///```
254 ///Returns nothing.
255 pub fn set_default_section(&mut self, section: &str) {
256 self.default_section = section.to_owned();
257 }
258
259 ///Sets the default comment symbols to the defined character slice (the defaults are `;` and `#`).
260 ///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.
261 ///## Example
262 ///```rust
263 ///use configparser::ini::Ini;
264 ///
265 ///let mut config = Ini::new();
266 ///config.set_comment_symbols(&['!', '#']);
267 ///let map = config.load("tests/test.ini").unwrap();
268 ///```
269 ///Returns nothing.
270 pub fn set_comment_symbols(&mut self, symlist: &[char]) {
271 self.comment_symbols = symlist.to_vec();
272 }
273
274 ///Sets multiline string support.
275 ///It must be set before `load()` or `read()` is called in order to take effect.
276 ///## Example
277 ///```rust
278 ///use configparser::ini::Ini;
279 ///
280 ///let mut config = Ini::new();
281 ///config.set_multiline(true);
282 ///let map = config.load("tests/test.ini").unwrap();
283 ///```
284 ///Returns nothing.
285 pub fn set_multiline(&mut self, multiline: bool) {
286 self.multiline = multiline;
287 }
288
289 ///Gets all the sections of the currently-stored `Map` in a vector.
290 ///## Example
291 ///```rust
292 ///use configparser::ini::Ini;
293 ///
294 ///let mut config = Ini::new();
295 ///config.load("tests/test.ini");
296 ///let sections = config.sections();
297 ///```
298 ///Returns `Vec<String>`.
299 pub fn sections(&self) -> Vec<String> {
300 self.map.keys().cloned().collect()
301 }
302
303 ///Loads a file from a defined path, parses it and puts the hashmap into our struct.
304 ///At one time, it only stores one configuration, so each call to `load()` or `read()` will clear the existing `Map`, if present.
305 ///## Example
306 ///```rust
307 ///use configparser::ini::Ini;
308 ///
309 ///let mut config = Ini::new();
310 ///let map = config.load("tests/test.ini").unwrap(); // we can get a clone like this, or just store it
311 /////Then, we can use standard hashmap functions like:
312 ///let values = map.get("values").unwrap();
313 ///```
314 ///Returns `Ok(map)` with a clone of the stored `Map` if no errors are thrown or else `Err(error_string)`.
315 ///Use `get_mut_map()` if you want a mutable reference.
316 pub fn load<T: AsRef<Path>>(
317 &mut self,
318 path: T,
319 ) -> Result<Map<String, Map<String, Option<String>>>, String> {
320 self.map = match self.parse(match fs::read_to_string(&path) {
321 Err(why) => {
322 return Err(format!(
323 "couldn't read {}: {}",
324 &path.as_ref().display(),
325 why
326 ))
327 }
328 Ok(s) => s,
329 }) {
330 Err(why) => {
331 return Err(format!(
332 "couldn't read {}: {}",
333 &path.as_ref().display(),
334 why
335 ))
336 }
337 Ok(map) => map,
338 };
339 Ok(self.map.clone())
340 }
341
342 ///Loads a file from a defined path, parses it and applies it to the existing hashmap in our struct.
343 ///While `load()` will clear the existing `Map`, `load_and_append()` applies the new values on top of
344 ///the existing hashmap, preserving previous values.
345 ///## Example
346 ///```rust
347 ///use configparser::ini::Ini;
348 ///
349 ///let mut config = Ini::new();
350 ///config.load("tests/test.ini").unwrap();
351 ///config.load_and_append("tests/sys_cfg.ini").ok(); // we don't have to worry if this doesn't succeed
352 ///config.load_and_append("tests/user_cfg.ini").ok(); // we don't have to worry if this doesn't succeed
353 ///let map = config.get_map().unwrap();
354 /////Then, we can use standard hashmap functions like:
355 ///let values = map.get("values").unwrap();
356 ///```
357 ///Returns `Ok(map)` with a clone of the stored `Map` if no errors are thrown or else `Err(error_string)`.
358 ///Use `get_mut_map()` if you want a mutable reference.
359 pub fn load_and_append<T: AsRef<Path>>(
360 &mut self,
361 path: T,
362 ) -> Result<Map<String, Map<String, Option<String>>>, String> {
363 let loaded = match self.parse(match fs::read_to_string(&path) {
364 Err(why) => {
365 return Err(format!(
366 "couldn't read {}: {}",
367 &path.as_ref().display(),
368 why
369 ))
370 }
371 Ok(s) => s,
372 }) {
373 Err(why) => {
374 return Err(format!(
375 "couldn't read {}: {}",
376 &path.as_ref().display(),
377 why
378 ))
379 }
380 Ok(map) => map,
381 };
382
383 for (section, section_map) in loaded.iter() {
384 self.map
385 .entry(section.clone())
386 .or_insert_with(Map::new)
387 .extend(section_map.clone());
388 }
389
390 Ok(self.map.clone())
391 }
392
393 ///Reads an input string, parses it and puts the hashmap into our struct.
394 ///At one time, it only stores one configuration, so each call to `load()` or `read()` will clear the existing `Map`, if present.
395 ///## Example
396 ///```rust
397 ///use configparser::ini::Ini;
398 ///
399 ///let mut config = Ini::new();
400 ///let map = match config.read(String::from(
401 /// "[2000s]
402 /// 2020 = bad")) {
403 /// Err(why) => panic!("{}", why),
404 /// Ok(inner) => inner
405 ///};
406 ///let this_year = map["2000s"]["2020"].clone().unwrap();
407 ///assert_eq!(this_year, "bad"); // value accessible!
408 ///```
409 ///Returns `Ok(map)` with a clone of the stored `Map` if no errors are thrown or else `Err(error_string)`.
410 ///Use `get_mut_map()` if you want a mutable reference.
411 pub fn read(
412 &mut self,
413 input: String,
414 ) -> Result<Map<String, Map<String, Option<String>>>, String> {
415 self.map = match self.parse(input) {
416 Err(why) => return Err(why),
417 Ok(map) => map,
418 };
419 Ok(self.map.clone())
420 }
421
422 ///Reads an input string, parses it and applies it to the existing hashmap in our struct.
423 ///While `read()` and `load()` will clear the existing `Map`, `read_and_append()` applies the new
424 ///values on top of the existing hashmap, preserving previous values.
425 ///## Example
426 ///```rust
427 ///use configparser::ini::Ini;
428 ///
429 ///let mut config = Ini::new();
430 ///if let Err(why) = config.read(String::from(
431 /// "[2000s]
432 /// 2020 = bad
433 /// 2023 = better")) {
434 /// panic!("{}", why);
435 ///};
436 ///if let Err(why) = config.read_and_append(String::from(
437 /// "[2000s]
438 /// 2020 = terrible")) {
439 /// panic!("{}", why);
440 ///};
441 ///let map = config.get_map().unwrap();
442 ///let few_years_ago = map["2000s"]["2020"].clone().unwrap();
443 ///let this_year = map["2000s"]["2023"].clone().unwrap();
444 ///assert_eq!(few_years_ago, "terrible"); // value updated!
445 ///assert_eq!(this_year, "better"); // keeps old values!
446 ///```
447 ///Returns `Ok(map)` with a clone of the stored `Map` if no errors are thrown or else `Err(error_string)`.
448 ///Use `get_mut_map()` if you want a mutable reference.
449 pub fn read_and_append(
450 &mut self,
451 input: String,
452 ) -> Result<Map<String, Map<String, Option<String>>>, String> {
453 let loaded = match self.parse(input) {
454 Err(why) => return Err(why),
455 Ok(map) => map,
456 };
457
458 for (section, section_map) in loaded.iter() {
459 self.map
460 .entry(section.clone())
461 .or_insert_with(Map::new)
462 .extend(section_map.clone());
463 }
464
465 Ok(self.map.clone())
466 }
467
468 ///Writes the current configuation to the specified path. If a file is not present, it is automatically created for you, if a file already
469 ///exists, it is truncated and the configuration is written to it.
470 ///## Example
471 ///```rust
472 ///use configparser::ini::Ini;
473 ///
474 ///fn main() -> std::io::Result<()> {
475 /// let mut config = Ini::new();
476 /// config.read(String::from(
477 /// "[2000s]
478 /// 2020 = bad"));
479 /// config.write("output.ini")
480 ///}
481 ///```
482 ///Returns a `std::io::Result<()>` type dependent on whether the write was successful or not.
483 pub fn write<T: AsRef<Path>>(&self, path: T) -> std::io::Result<()> {
484 fs::write(path.as_ref(), self.unparse())
485 }
486
487 ///Returns a string with the current configuration formatted with valid ini-syntax. This is always safe since the configuration is validated during
488 ///parsing.
489 ///## Example
490 ///```rust
491 ///use configparser::ini::Ini;
492 ///
493 ///let mut config = Ini::new();
494 ///config.read(String::from(
495 /// "[2000s]
496 /// 2020 = bad"));
497 ///let outstring = config.writes();
498 ///```
499 ///Returns a `String` type contatining the ini-syntax file.
500 pub fn writes(&self) -> String {
501 self.unparse()
502 }
503
504 ///Private function that converts the currently stored configuration into a valid ini-syntax string.
505 fn unparse(&self) -> String {
506 // push key/value pairs in outmap to out string.
507 fn unparse_key_values(
508 out: &mut String,
509 outmap: &Map<String, Option<String>>,
510 multiline: bool,
511 ) {
512 for (key, val) in outmap.iter() {
513 out.push_str(key);
514
515 if let Some(value) = val {
516 out.push('=');
517
518 if multiline {
519 let mut lines = value.lines();
520
521 out.push_str(lines.next().unwrap_or_default());
522
523 for line in lines {
524 out.push_str(LINE_ENDING);
525 out.push_str(" ");
526 out.push_str(line);
527 }
528 } else {
529 out.push_str(value);
530 }
531 }
532
533 out.push_str(LINE_ENDING);
534 }
535 }
536
537 let mut out = String::new();
538
539 if let Some(defaultmap) = self.map.get(&self.default_section) {
540 unparse_key_values(&mut out, defaultmap, self.multiline);
541 }
542
543 for (section, secmap) in self.map.iter() {
544 if section != &self.default_section {
545 write!(out, "[{}]", section).unwrap();
546 out.push_str(LINE_ENDING);
547 unparse_key_values(&mut out, secmap, self.multiline);
548 }
549 }
550 out
551 }
552
553 ///Private function that parses ini-style syntax into a Map.
554 fn parse(&self, input: String) -> Result<Map<String, Map<String, Option<String>>>, String> {
555 let mut map: Map<String, Map<String, Option<String>>> = Map::new();
556 let mut section = self.default_section.clone();
557 let mut current_key: Option<String> = None;
558
559 let caser = |val: &str| {
560 if self.case_sensitive {
561 val.to_owned()
562 } else {
563 val.to_lowercase()
564 }
565 };
566
567 for (num, raw_line) in input.lines().enumerate() {
568 let line = match raw_line.find(|c: char| self.comment_symbols.contains(&c)) {
569 Some(idx) => &raw_line[..idx],
570 None => raw_line,
571 };
572
573 let trimmed = line.trim();
574
575 if trimmed.is_empty() {
576 continue;
577 }
578
579 match (trimmed.find('['), trimmed.rfind(']')) {
580 (Some(0), Some(end)) => {
581 section = caser(trimmed[1..end].trim());
582
583 continue;
584 }
585 (Some(0), None) => {
586 return Err(format!(
587 "line {}: Found opening bracket for section name but no closing bracket",
588 num
589 ));
590 }
591 _ => {}
592 }
593
594 if line.starts_with(char::is_whitespace) && self.multiline {
595 let key = match current_key.as_ref() {
596 Some(x) => x,
597 None => {
598 return Err(format!(
599 "line {}: Started with indentation but there is no current entry",
600 num,
601 ))
602 }
603 };
604
605 let valmap = map.entry(section.clone()).or_insert_with(Map::new);
606
607 let val = valmap
608 .entry(key.clone())
609 .or_insert_with(|| Some(String::new()));
610
611 match val {
612 Some(x) => {
613 x.push_str(LINE_ENDING);
614 x.push_str(trimmed);
615 }
616 None => {
617 *val = Some(format!("{}{}", LINE_ENDING, trimmed));
618 }
619 }
620
621 continue;
622 }
623
624 let valmap = map.entry(section.clone()).or_insert_with(Map::new);
625
626 match trimmed.find(&self.delimiters[..]) {
627 Some(delimiter) => {
628 let key = caser(trimmed[..delimiter].trim());
629
630 if key.is_empty() {
631 return Err(format!("line {}:{}: Key cannot be empty", num, delimiter));
632 } else {
633 current_key = Some(key.clone());
634
635 let value = trimmed[delimiter + 1..].trim().to_owned();
636
637 valmap.insert(key, Some(value));
638 }
639 }
640 None => {
641 let key = caser(trimmed);
642 current_key = Some(key.clone());
643
644 valmap.insert(key, None);
645 }
646 }
647 }
648
649 Ok(map)
650 }
651
652 ///Private function that cases things automatically depending on the set variable.
653 fn autocase(&self, section: &str, key: &str) -> (String, String) {
654 if self.case_sensitive {
655 (section.to_owned(), key.to_owned())
656 } else {
657 (section.to_lowercase(), key.to_lowercase())
658 }
659 }
660
661 ///Returns a clone of the stored value from the key stored in the defined section.
662 ///Unlike accessing the map directly, `get()` can process your input to make case-insensitive access *if* the
663 ///default constructor is used.
664 ///All `get` functions will do this automatically under the hood.
665 ///## Example
666 ///```rust
667 ///use configparser::ini::Ini;
668 ///
669 ///let mut config = Ini::new();
670 ///config.load("tests/test.ini");
671 ///let value = config.get("default", "defaultvalues").unwrap();
672 ///assert_eq!(value, String::from("defaultvalues"));
673 ///```
674 ///Returns `Some(value)` of type `String` if value is found or else returns `None`.
675 pub fn get(&self, section: &str, key: &str) -> Option<String> {
676 let (section, key) = self.autocase(section, key);
677 self.map.get(&section)?.get(&key)?.clone()
678 }
679
680 ///Parses the stored value from the key stored in the defined section to a `bool`.
681 ///For ease of use, the function converts the type case-insensitively (`true` == `True`).
682 ///## Example
683 ///```rust
684 ///use configparser::ini::Ini;
685 ///
686 ///let mut config = Ini::new();
687 ///config.load("tests/test.ini");
688 ///let value = config.getbool("values", "bool").unwrap().unwrap();
689 ///assert!(value); // value accessible!
690 ///```
691 ///Returns `Ok(Some(value))` of type `bool` if value is found or else returns `Ok(None)`.
692 ///If the parsing fails, it returns an `Err(string)`.
693 pub fn getbool(&self, section: &str, key: &str) -> Result<Option<bool>, String> {
694 let (section, key) = self.autocase(section, key);
695 match self.map.get(&section) {
696 Some(secmap) => match secmap.get(&key) {
697 Some(val) => match val {
698 Some(inner) => match inner.to_lowercase().parse::<bool>() {
699 Err(why) => Err(why.to_string()),
700 Ok(boolean) => Ok(Some(boolean)),
701 },
702 None => Ok(None),
703 },
704 None => Ok(None),
705 },
706 None => Ok(None),
707 }
708 }
709
710 ///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.
711 ///It attempts to case-insenstively find `true`, `yes`, `t`, `y`, `1` and `on` to parse it as `True`.
712 ///Similarly it attempts to case-insensitvely find `false`, `no`, `f`, `n`, `0` and `off` to parse it as `False`.
713 ///## Example
714 ///```rust
715 ///use configparser::ini::Ini;
716 ///
717 ///let mut config = Ini::new();
718 ///config.load("tests/test.ini");
719 ///let value = config.getboolcoerce("values", "boolcoerce").unwrap().unwrap();
720 ///assert!(!value); // value accessible!
721 ///```
722 ///Returns `Ok(Some(value))` of type `bool` if value is found or else returns `Ok(None)`.
723 ///If the parsing fails, it returns an `Err(string)`.
724 pub fn getboolcoerce(&self, section: &str, key: &str) -> Result<Option<bool>, String> {
725 let (section, key) = self.autocase(section, key);
726 match self.map.get(&section) {
727 Some(secmap) => match secmap.get(&key) {
728 Some(val) => match val {
729 Some(inner) => {
730 let boolval = &inner.to_lowercase()[..];
731 if self
732 .boolean_values
733 .get(&true)
734 .unwrap()
735 .iter()
736 .any(|elem| elem == boolval)
737 {
738 Ok(Some(true))
739 } else if self
740 .boolean_values
741 .get(&false)
742 .unwrap()
743 .iter()
744 .any(|elem| elem == boolval)
745 {
746 Ok(Some(false))
747 } else {
748 Err(format!(
749 "Unable to parse value into bool at {}:{}",
750 section, key
751 ))
752 }
753 }
754 None => Ok(None),
755 },
756 None => Ok(None),
757 },
758 None => Ok(None),
759 }
760 }
761
762 ///Parses the stored value from the key stored in the defined section to an `i64`.
763 ///## Example
764 ///```rust
765 ///use configparser::ini::Ini;
766 ///
767 ///let mut config = Ini::new();
768 ///config.load("tests/test.ini");
769 ///let value = config.getint("values", "int").unwrap().unwrap();
770 ///assert_eq!(value, -31415); // value accessible!
771 ///```
772 ///Returns `Ok(Some(value))` of type `i64` if value is found or else returns `Ok(None)`.
773 ///If the parsing fails, it returns an `Err(string)`.
774 pub fn getint(&self, section: &str, key: &str) -> Result<Option<i64>, String> {
775 let (section, key) = self.autocase(section, key);
776 match self.map.get(&section) {
777 Some(secmap) => match secmap.get(&key) {
778 Some(val) => match val {
779 Some(inner) => match inner.parse::<i64>() {
780 Err(why) => Err(why.to_string()),
781 Ok(int) => Ok(Some(int)),
782 },
783 None => Ok(None),
784 },
785 None => Ok(None),
786 },
787 None => Ok(None),
788 }
789 }
790
791 ///Parses the stored value from the key stored in the defined section to a `u64`.
792 ///## Example
793 ///```rust
794 ///use configparser::ini::Ini;
795 ///
796 ///let mut config = Ini::new();
797 ///config.load("tests/test.ini");
798 ///let value = config.getint("values", "Uint").unwrap().unwrap();
799 ///assert_eq!(value, 31415); // value accessible!
800 ///```
801 ///Returns `Ok(Some(value))` of type `u64` if value is found or else returns `Ok(None)`.
802 ///If the parsing fails, it returns an `Err(string)`.
803 pub fn getuint(&self, section: &str, key: &str) -> Result<Option<u64>, String> {
804 let (section, key) = self.autocase(section, key);
805 match self.map.get(&section) {
806 Some(secmap) => match secmap.get(&key) {
807 Some(val) => match val {
808 Some(inner) => match inner.parse::<u64>() {
809 Err(why) => Err(why.to_string()),
810 Ok(uint) => Ok(Some(uint)),
811 },
812 None => Ok(None),
813 },
814 None => Ok(None),
815 },
816 None => Ok(None),
817 }
818 }
819
820 ///Parses the stored value from the key stored in the defined section to a `f64`.
821 ///## Example
822 ///```rust
823 ///use configparser::ini::Ini;
824 ///
825 ///let mut config = Ini::new();
826 ///config.load("tests/test.ini");
827 ///let value = config.getfloat("values", "float").unwrap().unwrap();
828 ///assert_eq!(value, 3.1415); // value accessible!
829 ///```
830 ///Returns `Ok(Some(value))` of type `f64` if value is found or else returns `Ok(None)`.
831 ///If the parsing fails, it returns an `Err(string)`.
832 pub fn getfloat(&self, section: &str, key: &str) -> Result<Option<f64>, String> {
833 let (section, key) = self.autocase(section, key);
834 match self.map.get(&section) {
835 Some(secmap) => match secmap.get(&key) {
836 Some(val) => match val {
837 Some(inner) => match inner.parse::<f64>() {
838 Err(why) => Err(why.to_string()),
839 Ok(float) => Ok(Some(float)),
840 },
841 None => Ok(None),
842 },
843 None => Ok(None),
844 },
845 None => Ok(None),
846 }
847 }
848
849 ///Returns a clone of the `Map` stored in our struct.
850 ///## Example
851 ///```rust
852 ///use configparser::ini::Ini;
853 ///
854 ///let mut config = Ini::new();
855 ///config.read(String::from(
856 /// "[section]
857 /// key=values"));
858 ///let map = config.get_map().unwrap();
859 ///assert_eq!(map, *config.get_map_ref()); // the cloned map is basically a snapshot that you own
860 ///```
861 ///Returns `Some(map)` if map is non-empty or else returns `None`.
862 ///Similar to `load()` but returns an `Option` type with the currently stored `Map`.
863 pub fn get_map(&self) -> Option<Map<String, Map<String, Option<String>>>> {
864 if self.map.is_empty() {
865 None
866 } else {
867 Some(self.map.clone())
868 }
869 }
870
871 ///Returns an immutable reference to the `Map` stored in our struct.
872 ///## Example
873 ///```rust
874 ///use configparser::ini::Ini;
875 ///
876 ///let mut config = Ini::new();
877 ///let mapclone = config.read(String::from
878 /// ("[topsecrets]
879 /// Valueless key")).unwrap();
880 /////Think of the clone as being a snapshot at a point of time while the reference always points to the current configuration.
881 ///assert_eq!(*config.get_map_ref(), mapclone); // same as expected.
882 ///```
883 ///If you just need to definitely mutate the map, use `get_mut_map()` instead. Alternatively, you can generate a snapshot by getting a clone
884 ///with `get_map()` and work with that.
885 pub fn get_map_ref(&self) -> &Map<String, Map<String, Option<String>>> {
886 &self.map
887 }
888
889 ///Returns a mutable reference to the `Map` stored in our struct.
890 ///## Example
891 ///```rust
892 ///use configparser::ini::Ini;
893 ///
894 ///let mut config = Ini::new();
895 ///config.read(String::from
896 /// ("[topsecrets]
897 /// Valueless key"));
898 /////We can then get the mutable map and insert a value like:
899 ///config.get_mut_map().get_mut("topsecrets").unwrap().insert(String::from("nuclear launch codes"), None);
900 ///assert_eq!(config.get("topsecrets", "nuclear launch codes"), None); // inserted successfully!
901 ///```
902 ///If you just need to access the map without mutating, use `get_map_ref()` or make a clone with `get_map()` instead.
903 pub fn get_mut_map(&mut self) -> &mut Map<String, Map<String, Option<String>>> {
904 &mut self.map
905 }
906
907 ///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.
908 ///An existing value in the map will be overwritten. You can also set `None` safely.
909 ///## Example
910 ///```rust
911 ///use configparser::ini::Ini;
912 ///
913 ///let mut config = Ini::new();
914 ///config.read(String::from(
915 /// "[section]
916 /// key=value"));
917 ///let key_value = String::from("value");
918 ///config.set("section", "key", Some(key_value));
919 ///config.set("section", "key", None); // also valid!
920 ///assert_eq!(config.get("section", "key"), None); // correct!
921 ///```
922 ///Returns `None` if there is no existing value, else returns `Some(Option<String>)`, with the existing value being the wrapped `Option<String>`.
923 ///If you want to insert using a string literal, use `setstr()` instead.
924 pub fn set(
925 &mut self,
926 section: &str,
927 key: &str,
928 value: Option<String>,
929 ) -> Option<Option<String>> {
930 let (section, key) = self.autocase(section, key);
931 match self.map.get_mut(&section) {
932 Some(secmap) => secmap.insert(key, value),
933 None => {
934 let mut valmap: Map<String, Option<String>> = Map::new();
935 valmap.insert(key, value);
936 self.map.insert(section, valmap);
937 None
938 }
939 }
940 }
941
942 ///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.
943 ///An existing value in the map will be overwritten. You can also set `None` safely.
944 ///## Example
945 ///```rust
946 ///use configparser::ini::Ini;
947 ///
948 ///let mut config = Ini::new();
949 ///config.read(String::from(
950 /// "[section]
951 /// key=notvalue"));
952 ///config.setstr("section", "key", Some("value"));
953 ///config.setstr("section", "key", None); // also valid!
954 ///assert_eq!(config.get("section", "key"), None); // correct!
955 ///```
956 ///Returns `None` if there is no existing value, else returns `Some(Option<String>)`, with the existing value being the wrapped `Option<String>`.
957 ///If you want to insert using a `String`, use `set()` instead.
958 pub fn setstr(
959 &mut self,
960 section: &str,
961 key: &str,
962 value: Option<&str>,
963 ) -> Option<Option<String>> {
964 let (section, key) = self.autocase(section, key);
965 self.set(&section, &key, value.map(String::from))
966 }
967
968 ///Clears the map, removing all sections and properties from the hashmap. It keeps the allocated memory for reuse.
969 ///## Example
970 ///```rust
971 ///use configparser::ini::Ini;
972 ///
973 ///let mut config = Ini::new();
974 ///config.read(String::from(
975 /// "[section]
976 /// key=somevalue"));
977 ///config.clear();
978 ///assert!(config.get_map_ref().is_empty()); // our map is empty!
979 ///```
980 ///Returns nothing.
981 pub fn clear(&mut self) {
982 self.map.clear();
983 }
984
985 ///Removes a section from the hashmap, returning the properties stored in the section if the section was previously in the map.
986 ///## Example
987 ///```rust
988 ///use configparser::ini::Ini;
989 ///
990 ///let mut config = Ini::new();
991 ///config.read(String::from(
992 /// "[section]
993 /// updog=whatsupdog"));
994 ///config.remove_section("section"); // this will return a cloned hashmap of the stored property
995 ///assert!(config.get_map_ref().is_empty()); // with the last section removed, our map is now empty!
996 ///```
997 ///Returns `Some(section_map)` if the section exists or else, `None`.
998 pub fn remove_section(&mut self, section: &str) -> Option<Map<String, Option<String>>> {
999 let section = if self.case_sensitive {
1000 section.to_owned()
1001 } else {
1002 section.to_lowercase()
1003 };
1004 self.map.remove(&section)
1005 }
1006
1007 ///Removes a key from a section in the hashmap, returning the value attached to the key if it was previously in the map.
1008 ///## Example
1009 ///```rust
1010 ///use configparser::ini::Ini;
1011 ///
1012 ///let mut config = Ini::new();
1013 ///config.read(String::from(
1014 /// "[section]
1015 /// updog=whatsupdog
1016 /// [anothersection]
1017 /// updog=differentdog"));
1018 ///let val = config.remove_key("anothersection", "updog").unwrap().unwrap();
1019 ///assert_eq!(val, String::from("differentdog")); // with the last section removed, our map is now empty!
1020 ///```
1021 ///Returns `Some(Option<String>)` if the value exists or else, `None`.
1022 pub fn remove_key(&mut self, section: &str, key: &str) -> Option<Option<String>> {
1023 let (section, key) = self.autocase(section, key);
1024 self.map.get_mut(&section)?.remove(&key)
1025 }
1026 }
1027
1028 #[cfg(feature = "async-std")]
1029 impl Ini {
1030 ///Loads a file asynchronously from a defined path, parses it and puts the hashmap into our struct.
1031 ///At one time, it only stores one configuration, so each call to `load()` or `read()` will clear the existing `Map`, if present.
1032 ///
1033 ///Usage is similar to `load`, but `.await` must be called after along with the usual async rules.
1034 ///
1035 ///Returns `Ok(map)` with a clone of the stored `Map` if no errors are thrown or else `Err(error_string)`.
1036 ///Use `get_mut_map()` if you want a mutable reference.
1037 pub async fn load_async<T: AsRef<AsyncPath>>(
1038 &mut self,
1039 path: T,
1040 ) -> Result<Map<String, Map<String, Option<String>>>, String> {
1041 self.map = match self.parse(match async_fs::read_to_string(&path).await {
1042 Err(why) => {
1043 return Err(format!(
1044 "couldn't read {}: {}",
1045 &path.as_ref().display(),
1046 why
1047 ))
1048 }
1049 Ok(s) => s,
1050 }) {
1051 Err(why) => {
1052 return Err(format!(
1053 "couldn't read {}: {}",
1054 &path.as_ref().display(),
1055 why
1056 ))
1057 }
1058 Ok(map) => map,
1059 };
1060 Ok(self.map.clone())
1061 }
1062
1063 ///Loads a file from a defined path, parses it and applies it to the existing hashmap in our struct.
1064 ///While `load_async()` will clear the existing `Map`, `load_and_append_async()` applies the new values on top
1065 ///of the existing hashmap, preserving previous values.
1066 ///
1067 ///Usage is similar to `load_and_append`, but `.await` must be called after along with the usual async rules.
1068 ///
1069 ///Returns `Ok(map)` with a clone of the stored `Map` if no errors are thrown or else `Err(error_string)`.
1070 ///Use `get_mut_map()` if you want a mutable reference.
1071 pub async fn load_and_append_async<T: AsRef<AsyncPath>>(
1072 &mut self,
1073 path: T,
1074 ) -> Result<Map<String, Map<String, Option<String>>>, String> {
1075 let loaded = match self.parse(match async_fs::read_to_string(&path).await {
1076 Err(why) => {
1077 return Err(format!(
1078 "couldn't read {}: {}",
1079 &path.as_ref().display(),
1080 why
1081 ))
1082 }
1083 Ok(s) => s,
1084 }) {
1085 Err(why) => {
1086 return Err(format!(
1087 "couldn't read {}: {}",
1088 &path.as_ref().display(),
1089 why
1090 ))
1091 }
1092 Ok(map) => map,
1093 };
1094
1095 for (section, section_map) in loaded.iter() {
1096 self.map
1097 .entry(section.clone())
1098 .or_insert_with(Map::new)
1099 .extend(section_map.clone());
1100 }
1101
1102 Ok(self.map.clone())
1103 }
1104
1105 ///Writes the current configuation to the specified path asynchronously. If a file is not present, it is automatically created for you, if a file already
1106 ///exists, it is truncated and the configuration is written to it.
1107 ///
1108 ///Usage is the same as `write`, but `.await` must be called after along with the usual async rules.
1109 ///
1110 ///Returns a `std::io::Result<()>` type dependent on whether the write was successful or not.
1111 pub async fn write_async<T: AsRef<Path>>(&self, path: T) -> std::io::Result<()> {
1112 async_fs::write(path.as_ref(), self.unparse()).await
1113 }
1114 }