config-lib 1.4.0

Enterprise-grade multi-format configuration library supporting 8 formats (CONF, INI, Properties, JSON, XML, HCL, TOML, NOML) with sub-50ns caching, hot reloading, and comprehensive validation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
//! INI format parser implementation
//!
//! Supports standard INI format with:
//! - Sections: \[section_name\]
//! - Key-value pairs: key=value or key:value
//! - Comments: ; comment or # comment
//! - Escape sequences: \n, \t, \\, etc.
//! - Quoted values with spaces
//! - Case-sensitive keys and sections

use crate::error::{Error, Result};
use crate::value::Value;
use std::collections::BTreeMap;

/// Parse INI format configuration
pub fn parse(source: &str) -> Result<Value> {
    parse_ini(source)
}

/// Parse INI format string into a Value::Table
pub fn parse_ini(content: &str) -> Result<Value> {
    let mut parser = IniParser::new(content);
    parser.parse()
}

/// INI parser state.
///
/// `position` is a byte offset into `content` and always sits on a UTF-8
/// character boundary: it only moves by the encoded length of the
/// character under it.
struct IniParser<'a> {
    content: &'a str,
    position: usize,
    line: usize,
    current_section: Option<String>,
    result: BTreeMap<String, Value>,
}

impl<'a> IniParser<'a> {
    fn new(content: &'a str) -> Self {
        Self {
            content,
            position: 0,
            line: 1,
            current_section: None,
            result: BTreeMap::new(),
        }
    }

    fn parse(&mut self) -> Result<Value> {
        loop {
            self.skip_whitespace_and_comments()?;

            match self.peek() {
                None => break,
                Some('[') => self.parse_section()?,
                Some(_) => self.parse_key_value()?,
            }
        }

        Ok(Value::Table(std::mem::take(&mut self.result)))
    }

    /// The character at the current position, or `None` at the end.
    ///
    /// O(1): `position` is a byte offset on a character boundary, so this
    /// decodes one character instead of counting from the start.
    fn peek(&self) -> Option<char> {
        self.content.get(self.position..)?.chars().next()
    }

    fn advance(&mut self) {
        if let Some(ch) = self.peek() {
            self.position += ch.len_utf8();
        }
    }

    /// The input from byte offset `start` to the current position.
    ///
    /// Both ends are character boundaries, because positions only move by
    /// whole characters; the empty fallback is never taken.
    fn since(&self, start: usize) -> &'a str {
        self.content.get(start..self.position).unwrap_or("")
    }

    /// Skip spaces and tabs on the current line
    fn skip_spaces(&mut self) {
        while let Some(' ' | '\t') = self.peek() {
            self.advance();
        }
    }

    fn skip_whitespace_and_comments(&mut self) -> Result<()> {
        loop {
            match self.peek() {
                Some(' ' | '\t' | '\r') => self.advance(),
                Some(';' | '#') => {
                    // Skip comment until end of line
                    while !matches!(self.peek(), None | Some('\n')) {
                        self.advance();
                    }
                }
                Some('\n') => {
                    self.advance();
                    self.line += 1;
                }
                _ => break,
            }
        }
        Ok(())
    }

    fn parse_section(&mut self) -> Result<()> {
        self.advance(); // Skip '['
        let start = self.position;

        // Find closing bracket
        while !matches!(self.peek(), None | Some(']')) {
            if self.peek() == Some('\n') {
                return Err(Error::Parse {
                    message: "Unterminated section".to_string(),
                    line: self.line,
                    column: 1,
                    file: None,
                });
            }
            self.advance();
        }

        if self.peek() != Some(']') {
            return Err(Error::Parse {
                message: "Missing closing bracket for section".to_string(),
                line: self.line,
                column: 1,
                file: None,
            });
        }

        let section_name = self.since(start).trim().to_string();
        self.advance(); // Skip ']'

        if section_name.is_empty() {
            return Err(Error::Parse {
                message: "Empty section name".to_string(),
                line: self.line,
                column: 1,
                file: None,
            });
        }

        self.current_section = Some(section_name);
        Ok(())
    }

    fn parse_key_value(&mut self) -> Result<()> {
        let key = self.parse_key()?;

        if key.is_empty() {
            // A line that starts with '=' or ':'. Returning without
            // consuming anything used to loop forever here.
            return Err(Error::Parse {
                message: "Expected a key name".to_string(),
                line: self.line,
                column: 1,
                file: None,
            });
        }

        // The separator and the value are on the key's line: an empty
        // value must not take the next line as its text.
        self.skip_spaces();

        if !matches!(self.peek(), Some('=' | ':')) {
            return Err(Error::Parse {
                // The key is not quoted back: a line holding only a token
                // can be a pasted secret
                message: "Expected '=' or ':' after the key".to_string(),
                line: self.line,
                column: 1,
                file: None,
            });
        }

        self.advance(); // Skip separator
        self.skip_spaces();

        let value = self.parse_value()?;

        // Store the key-value pair
        let full_key = match &self.current_section {
            Some(section) => format!("{section}.{key}"),
            None => key,
        };

        self.result.insert(full_key, value);
        Ok(())
    }

    fn parse_key(&mut self) -> Result<String> {
        let start = self.position;

        while let Some(ch) = self.peek() {
            match ch {
                '=' | ':' | '\n' | '\r' => break,
                ';' | '#' => break, // Comment starts
                _ => self.advance(),
            }
        }

        let key = self.since(start).trim();
        Ok(key.to_string())
    }

    fn parse_value(&mut self) -> Result<Value> {
        let mut value_chars = Vec::new();
        let mut in_quotes = false;
        // Set at the closing quote: the value was quoted and its escapes
        // were already read, so it is neither trimmed nor read again.
        let mut quoted = false;
        let mut quote_char = '\0';
        let first_line = self.line;

        while let Some(ch) = self.peek() {
            match ch {
                // Only a value's first character opens a quote: an
                // apostrophe inside text (`name = O'Brien`) is text, not
                // the start of a value that runs to the next quote.
                '"' | '\'' if !in_quotes && value_chars.is_empty() => {
                    in_quotes = true;
                    quote_char = ch;
                    self.advance();
                    // Don't include the opening quote
                }
                '\\' if in_quotes => {
                    // Handle escape sequences within quotes
                    self.advance(); // Skip backslash
                    if let Some(escaped_char) = self.peek() {
                        match escaped_char {
                            'n' => value_chars.push('\n'),
                            't' => value_chars.push('\t'),
                            'r' => value_chars.push('\r'),
                            '\\' => value_chars.push('\\'),
                            '"' => value_chars.push('"'),
                            '\'' => value_chars.push('\''),
                            _ => {
                                value_chars.push('\\');
                                value_chars.push(escaped_char);
                            }
                        }
                        self.advance();
                    }
                }
                ch if in_quotes && ch == quote_char => {
                    in_quotes = false;
                    quoted = true;
                    self.advance();
                    // Don't include the closing quote
                    break;
                }
                '\n' | '\r' if !in_quotes => break,
                // An inline comment starts only after whitespace, so
                // `abc;def` and `http://h/#frag` stay whole values
                ';' | '#'
                    if !in_quotes
                        && value_chars
                            .last()
                            .map_or(true, |c: &char| c.is_whitespace()) =>
                {
                    break
                }
                _ => {
                    if ch == '\n' {
                        // A line end inside quotes
                        self.line += 1;
                    }
                    value_chars.push(ch);
                    self.advance();
                }
            }
        }

        if in_quotes {
            // The value's text is not quoted back: it may be a secret.
            return Err(Error::Parse {
                message: "Unterminated quoted value".to_string(),
                line: first_line,
                column: 1,
                file: None,
            });
        }
        let value_str: String = value_chars.into_iter().collect();
        // A quoted value had its escapes read above and keeps its spaces;
        // an unquoted one is trimmed and its escapes read here, once.
        let processed_value = if quoted {
            value_str
        } else {
            self.process_escape_sequences(value_str.trim_end())
        };

        // Try to parse as different types
        self.parse_typed_value(&processed_value)
    }

    fn process_escape_sequences(&self, value: &str) -> String {
        let mut result = String::new();
        let mut chars = value.chars().peekable();

        while let Some(ch) = chars.next() {
            if ch == '\\' {
                match chars.peek() {
                    Some('n') => {
                        chars.next();
                        result.push('\n');
                    }
                    Some('t') => {
                        chars.next();
                        result.push('\t');
                    }
                    Some('r') => {
                        chars.next();
                        result.push('\r');
                    }
                    Some('\\') => {
                        chars.next();
                        result.push('\\');
                    }
                    Some('"') => {
                        chars.next();
                        result.push('"');
                    }
                    Some('\'') => {
                        chars.next();
                        result.push('\'');
                    }
                    _ => result.push(ch),
                }
            } else {
                result.push(ch);
            }
        }

        result
    }

    fn parse_typed_value(&self, value: &str) -> Result<Value> {
        if value.is_empty() {
            return Ok(Value::String(String::new()));
        }

        // Try boolean
        match value.to_lowercase().as_str() {
            // `1` and `0` stay integers (since v1.4.0), so integer reads of
            // them work; `as_bool` still reads them as true and false
            "true" | "yes" | "on" => return Ok(Value::Bool(true)),
            "false" | "no" | "off" => return Ok(Value::Bool(false)),
            _ => {}
        }

        // Try integer
        if let Ok(int_val) = value.parse::<i64>() {
            return Ok(Value::Integer(int_val));
        }

        // Try float (decimal syntax only, so `nan` and `inf` stay text)
        if let Some(float_val) = super::decimal_float(value) {
            return Ok(Value::Float(float_val));
        }

        // Default to string
        Ok(Value::String(value.to_string()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_simple_ini() {
        let content = r#"
key1=value1
key2=value2
        "#;

        let result = parse_ini(content).unwrap();
        if let Value::Table(map) = result {
            assert_eq!(map.get("key1").unwrap().as_string().unwrap(), "value1");
            assert_eq!(map.get("key2").unwrap().as_string().unwrap(), "value2");
        } else {
            panic!("Expected table");
        }
    }

    #[test]
    fn test_sections() -> crate::Result<()> {
        let content = r#"
[section1]
key1=value1

[section2]
key2=value2
        "#;

        let result = parse_ini(content)?;
        if let Value::Table(map) = result {
            let key1 = map
                .get("section1.key1")
                .ok_or_else(|| crate::Error::KeyNotFound {
                    key: "section1.key1".to_string(),
                    available: map.keys().cloned().collect(),
                })?;
            assert_eq!(key1.as_string()?, "value1");

            let key2 = map
                .get("section2.key2")
                .ok_or_else(|| crate::Error::KeyNotFound {
                    key: "section2.key2".to_string(),
                    available: map.keys().cloned().collect(),
                })?;
            assert_eq!(key2.as_string()?, "value2");
        } else {
            return Err(crate::Error::Parse {
                message: "Expected table".to_string(),
                line: 0,
                column: 0,
                file: None,
            });
        }
        Ok(())
    }

    #[test]
    fn test_comments() {
        let content = r#"
; This is a comment
key1=value1  ; Inline comment
# Hash comment
key2=value2
        "#;

        let result = parse_ini(content).unwrap();
        if let Value::Table(map) = result {
            assert_eq!(map.get("key1").unwrap().as_string().unwrap(), "value1");
            assert_eq!(map.get("key2").unwrap().as_string().unwrap(), "value2");
        } else {
            panic!("Expected table");
        }
    }

    #[test]
    fn test_quoted_values() {
        let content = r#"
key1="quoted value"
key2='single quoted'
key3="value with spaces"
        "#;

        let result = parse_ini(content).unwrap();
        if let Value::Table(map) = result {
            assert_eq!(
                map.get("key1").unwrap().as_string().unwrap(),
                "quoted value"
            );
            assert_eq!(
                map.get("key2").unwrap().as_string().unwrap(),
                "single quoted"
            );
            assert_eq!(
                map.get("key3").unwrap().as_string().unwrap(),
                "value with spaces"
            );
        } else {
            panic!("Expected table");
        }
    }

    #[test]
    fn test_escape_sequences() {
        let content = r#"
key1="line1\nline2"
key2="tab\there"
key3="quote\"here"
        "#;

        let result = parse_ini(content).unwrap();
        if let Value::Table(map) = result {
            assert_eq!(
                map.get("key1").unwrap().as_string().unwrap(),
                "line1\nline2"
            );
            assert_eq!(map.get("key2").unwrap().as_string().unwrap(), "tab\there");
            assert_eq!(map.get("key3").unwrap().as_string().unwrap(), "quote\"here");
        } else {
            panic!("Expected table");
        }
    }

    #[test]
    fn test_quoted_escapes_are_read_once() {
        // `\\n` in quotes is a backslash and an `n`, not a line break, and
        // the spaces inside the quotes are kept.
        let content = "path=\"C:\\\\new\"\npad=\"two  \"\nplain=a\\tb\n";
        let result = parse_ini(content).unwrap();
        let Value::Table(map) = result else {
            panic!("Expected table");
        };
        assert_eq!(map.get("path").unwrap().as_string().unwrap(), "C:\\new");
        assert_eq!(map.get("pad").unwrap().as_string().unwrap(), "two  ");
        assert_eq!(map.get("plain").unwrap().as_string().unwrap(), "a\tb");
    }

    #[test]
    fn test_a_quote_inside_text_is_text() {
        let content = "name = O'Brien\nnext = it's here\n";
        let result = parse_ini(content).unwrap();
        let Value::Table(map) = result else {
            panic!("Expected table");
        };
        assert_eq!(map.get("name").unwrap().as_string().unwrap(), "O'Brien");
        assert_eq!(map.get("next").unwrap().as_string().unwrap(), "it's here");
    }

    #[test]
    fn test_an_unterminated_quote_is_refused_at_its_line() {
        let content = "a = 1\nsecret = \"hunter2\nb = 2\n";
        match parse_ini(content) {
            Err(Error::Parse { line, message, .. }) => {
                assert_eq!(line, 2);
                assert!(!message.contains("hunter2"));
            }
            other => panic!("expected a parse error, got {other:?}"),
        }
    }

    #[test]
    fn test_data_types() {
        let content = r#"
string_val=hello
int_val=42
float_val=1.234
bool_true=true
bool_false=false
bool_yes=yes
bool_no=no
        "#;

        let result = parse_ini(content).unwrap();
        if let Value::Table(map) = result {
            assert_eq!(map.get("string_val").unwrap().as_string().unwrap(), "hello");
            assert_eq!(map.get("int_val").unwrap().as_integer().unwrap(), 42);
            assert_eq!(map.get("float_val").unwrap().as_float().unwrap(), 1.234);
            assert!(map.get("bool_true").unwrap().as_bool().unwrap());
            assert!(!map.get("bool_false").unwrap().as_bool().unwrap());
            assert!(map.get("bool_yes").unwrap().as_bool().unwrap());
            assert!(!map.get("bool_no").unwrap().as_bool().unwrap());
        } else {
            panic!("Expected table");
        }
    }

    #[test]
    fn test_colon_separator() {
        let content = r#"
key1:value1
key2:value2
        "#;

        let result = parse_ini(content).unwrap();
        if let Value::Table(map) = result {
            assert_eq!(map.get("key1").unwrap().as_string().unwrap(), "value1");
            assert_eq!(map.get("key2").unwrap().as_string().unwrap(), "value2");
        } else {
            panic!("Expected table");
        }
    }

    #[test]
    fn non_ascii_text_parses() {
        let content = "; caf\u{e9}\n[se\u{e7}\u{e3}o]\nn\u{e4}me = J\u{fc}rgen ; \u{2713}\n\
                       quoted = \"\u{3b1} \u{3b2}\"\n";
        let Value::Table(map) = parse_ini(content).unwrap() else {
            panic!("Expected table");
        };
        assert_eq!(
            map.get("se\u{e7}\u{e3}o.n\u{e4}me")
                .unwrap()
                .as_string()
                .unwrap(),
            "J\u{fc}rgen"
        );
        assert_eq!(
            map.get("se\u{e7}\u{e3}o.quoted")
                .unwrap()
                .as_string()
                .unwrap(),
            "\u{3b1} \u{3b2}"
        );
    }

    #[test]
    fn line_starting_with_separator_is_an_error() {
        // The first three used to loop forever; a NUL used to read as the end
        for content in ["=x\n", ":x\n", "a=1\n= 2\n", "\0"] {
            assert!(parse_ini(content).is_err(), "{content:?}");
        }
    }

    #[test]
    fn empty_value_does_not_take_the_next_line() {
        let Value::Table(map) = parse_ini("a=\nb=2\n").unwrap() else {
            panic!("Expected table");
        };
        assert_eq!(map.get("a").unwrap().as_string().unwrap(), "");
        assert_eq!(map.get("b").unwrap().as_integer().unwrap(), 2);
    }

    #[test]
    fn crlf_counts_one_line() {
        match parse_ini("a=1\r\nb=2\r\n[open\r\n").unwrap_err() {
            Error::Parse { line, .. } => assert_eq!(line, 3),
            other => panic!("expected a parse error, got {other:?}"),
        }
    }

    #[test]
    fn test_error_handling() {
        // Test unterminated section
        let content = "[section";
        assert!(parse_ini(content).is_err());

        // Test invalid key-value
        let content = "key_without_value";
        assert!(parse_ini(content).is_err());
    }
}