config-lib 1.3.1

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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
//! # CONF Format Parser
//!
//! High-performance parser for standard .conf configuration files.
//!
//! Supports the common configuration format used by many Unix/Linux applications:
//!
//! ```conf
//! # Comments start with #
//! key = value
//! quoted_value = "string with spaces"
//! number = 42
//! float = 3.14
//! boolean = true
//!
//! # Sections
//! [section]
//! nested_key = value
//!
//! # Arrays (space or comma separated)
//! array = item1 item2 item3
//! comma_array = item1, item2, item3
//! ```

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

/// Parse CONF format configuration
pub fn parse(source: &str) -> Result<Value> {
    let mut parser = ConfParser::new(source);
    parser.parse()
}

/// Put a section's table into the root. A section with no keys is left
/// out, as it always was.
fn close_section(root: &mut BTreeMap<String, Value>, name: String, table: BTreeMap<String, Value>) {
    if !table.is_empty() {
        root.insert(name, Value::table(table));
    }
}

/// Deepest nesting of `[...]` arrays the parser accepts.
///
/// Arrays are parsed recursively, so without a limit a value such as a
/// long run of `[` would overflow the stack. 128 matches the XML parser's
/// element limit and jsonx-lib's default depth.
const MAX_ARRAY_DEPTH: usize = 128;

/// CONF parser state.
///
/// `position` is a byte offset into `input` and always sits on a UTF-8
/// character boundary: it only moves by the encoded length of the
/// character under it. `line` and `column` count lines and characters
/// (from 1) for error messages.
struct ConfParser<'a> {
    input: &'a str,
    position: usize,
    line: usize,
    column: usize,
    depth: usize,
}

impl<'a> ConfParser<'a> {
    /// Create a new parser
    fn new(input: &'a str) -> Self {
        Self {
            input,
            position: 0,
            line: 1,
            column: 1,
            depth: 0,
        }
    }

    /// Parse the entire configuration
    fn parse(&mut self) -> Result<Value> {
        let mut root = BTreeMap::new();
        // The open section's name and table, kept out of `root` while its
        // keys are read: each key goes straight into it, and the name is
        // not copied per key.
        let mut section: Option<(String, BTreeMap<String, Value>)> = None;

        while !self.is_at_end() {
            self.skip_whitespace_and_comments();

            if self.is_at_end() {
                break;
            }

            // Check for section header
            if self.peek() == Some('[') {
                let (line, column) = (self.line, self.column);
                let name = self.parse_section_header()?;
                if let Some((open, table)) = section.take() {
                    close_section(&mut root, open, table);
                }
                // A section seen before continues where it left off. One
                // named like a key above it used to lose its keys
                // silently; it is refused.
                let table = match root.remove(name.as_str()) {
                    None => BTreeMap::new(),
                    Some(Value::Table(table)) => table,
                    Some(_) => {
                        return Err(Error::parse(
                            "A section has the name of a key above it",
                            line,
                            column,
                        ))
                    }
                };
                section = Some((name, table));
                continue;
            }

            // Parse key-value pair
            let (key, value) = self.parse_key_value()?;

            match &mut section {
                Some((_, table)) => {
                    table.insert(key, value);
                }
                None => {
                    root.insert(key, value);
                }
            }
        }

        if let Some((open, table)) = section {
            close_section(&mut root, open, table);
        }
        Ok(Value::table(root))
    }

    /// Parse a section header like [section_name]
    fn parse_section_header(&mut self) -> Result<String> {
        self.expect('[')?;
        let start = self.position;

        // Find the closing bracket
        self.advance_while(|ch| ch != ']' && ch != '\n');
        if self.peek() == Some('\n') {
            return Err(Error::parse(
                "Unterminated section header",
                self.line,
                self.column,
            ));
        }

        let section_name = self.since(start).trim().to_string();
        self.expect(']')?;

        Ok(section_name)
    }

    /// Parse a key-value pair
    fn parse_key_value(&mut self) -> Result<(String, Value)> {
        let key = self.parse_key()?;
        self.skip_whitespace();
        self.expect('=')?;
        self.skip_whitespace();
        let value = self.parse_value()?;

        Ok((key, value))
    }

    /// Parse a configuration key
    fn parse_key(&mut self) -> Result<String> {
        let start = self.position;

        self.advance_while(|ch| ch.is_alphanumeric() || ch == '_' || ch == '-' || ch == '.');

        if start == self.position {
            return Err(Error::parse("Expected key name", self.line, self.column));
        }

        Ok(self.since(start).to_string())
    }

    /// Parse a configuration value
    fn parse_value(&mut self) -> Result<Value> {
        self.skip_whitespace();

        match self.peek() {
            Some('"') => self.parse_quoted_string(),
            Some('\'') => self.parse_single_quoted_string(),
            Some('[') => self.parse_array(),
            _ => {
                // For all other cases (including numbers), use unquoted value parsing
                // which handles space-separated arrays
                self.parse_unquoted_value()
            }
        }
    }

    /// Parse a quoted string
    fn parse_quoted_string(&mut self) -> Result<Value> {
        self.expect('"')?;
        let _start = self.position;
        let mut result = String::new();

        while let Some(ch) = self.peek() {
            if ch == '"' {
                break;
            }
            if ch == '\\' {
                self.advance();
                match self.peek() {
                    Some('n') => result.push('\n'),
                    Some('t') => result.push('\t'),
                    Some('r') => result.push('\r'),
                    Some('\\') => result.push('\\'),
                    Some('"') => result.push('"'),
                    Some(other) => {
                        result.push('\\');
                        result.push(other);
                    }
                    None => {
                        return Err(Error::parse(
                            "Unterminated escape sequence",
                            self.line,
                            self.column,
                        ))
                    }
                }
                self.advance();
            } else {
                result.push(ch);
                self.advance();
            }
        }

        self.expect('"')?;
        Ok(Value::string(result))
    }

    /// Parse a single-quoted string (no escape sequences)
    fn parse_single_quoted_string(&mut self) -> Result<Value> {
        self.expect('\'')?;
        let start = self.position;

        while let Some(ch) = self.peek() {
            if ch == '\'' {
                break;
            }
            self.advance();
        }

        let content = self.since(start).to_string();
        self.expect('\'')?;
        Ok(Value::string(content))
    }

    /// Parse an array [item1, item2, item3]
    fn parse_array(&mut self) -> Result<Value> {
        if self.depth >= MAX_ARRAY_DEPTH {
            return Err(Error::parse(
                format!("Arrays are nested deeper than the limit of {MAX_ARRAY_DEPTH} levels"),
                self.line,
                self.column,
            ));
        }
        self.depth += 1;
        let result = self.parse_array_items();
        self.depth -= 1;
        result
    }

    /// Parse the brackets and items of one array (see [`Self::parse_array`])
    fn parse_array_items(&mut self) -> Result<Value> {
        self.expect('[')?;
        let mut items = Vec::new();

        self.skip_whitespace();

        if self.peek() == Some(']') {
            self.advance();
            return Ok(Value::array(items));
        }

        loop {
            items.push(self.parse_value()?);
            self.skip_whitespace();

            match self.peek() {
                Some(',') => {
                    self.advance();
                    self.skip_whitespace();
                }
                Some(']') => {
                    self.advance();
                    break;
                }
                _ => {
                    return Err(Error::parse(
                        "Expected ',' or ']' in array",
                        self.line,
                        self.column,
                    ))
                }
            }
        }

        Ok(Value::array(items))
    }

    /// Parse a number (integer or float)
    #[allow(dead_code)]
    fn parse_number(&mut self) -> Result<Value> {
        let start = self.position;
        let mut has_dot = false;

        // Handle sign
        if self.peek() == Some('-') || self.peek() == Some('+') {
            self.advance();
        }

        // Parse digits and optional decimal point
        while let Some(ch) = self.peek() {
            if ch.is_ascii_digit() {
                self.advance();
            } else if ch == '.' && !has_dot {
                has_dot = true;
                self.advance();
            } else {
                break;
            }
        }

        let number_str = self.since(start);

        if has_dot {
            number_str.parse::<f64>().map(Value::float).map_err(|_| {
                Error::parse(
                    format!("Invalid float: {number_str}"),
                    self.line,
                    self.column,
                )
            })
        } else {
            number_str.parse::<i64>().map(Value::integer).map_err(|_| {
                Error::parse(
                    format!("Invalid integer: {number_str}"),
                    self.line,
                    self.column,
                )
            })
        }
    }

    /// Parse an unquoted value (string, boolean, or array). Inside
    /// brackets an item ends at `,` or `]`, so `[80, 443]` is two items.
    fn parse_unquoted_value(&mut self) -> Result<Value> {
        let start = self.position;
        let in_array = self.depth > 0;

        // Read until end of line, comment, or special character
        self.advance_while(|ch| {
            !(ch == '\n' || ch == '\r' || ch == '#' || (in_array && (ch == ',' || ch == ']')))
        });

        let raw_value = self.since(start).trim();

        if raw_value.is_empty() {
            return Ok(Value::null());
        }

        // Try to parse as boolean or null. The words are ASCII and no
        // other character lower-cases to one of their letters, so an
        // ASCII comparison matches what `to_lowercase` did, without
        // allocating a lowered copy of every value.
        let is = |word: &str| raw_value.eq_ignore_ascii_case(word);
        if is("true") || is("yes") || is("on") {
            return Ok(Value::bool(true));
        }
        if is("false") || is("no") || is("off") {
            return Ok(Value::bool(false));
        }
        if is("null") || is("nil") {
            return Ok(Value::null());
        }

        // Check if it's a space or comma separated array (not inside
        // brackets, where the brackets make the array)
        if !in_array && (raw_value.contains(' ') || raw_value.contains(',')) {
            let items: Vec<Value> = raw_value
                .split([' ', ','])
                .map(|s| s.trim())
                .filter(|s| !s.is_empty())
                .map(|s| self.parse_simple_value(s))
                .collect::<Result<Vec<_>>>()?;

            if items.len() > 1 {
                return Ok(Value::array(items));
            }
        }

        // Parse as simple value
        self.parse_simple_value(raw_value)
    }

    /// Parse a simple value (no arrays or complex types)
    fn parse_simple_value(&self, value: &str) -> Result<Value> {
        // Try integer
        if let Ok(i) = value.parse::<i64>() {
            return Ok(Value::integer(i));
        }

        // Try float
        if let Ok(f) = value.parse::<f64>() {
            return Ok(Value::float(f));
        }

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

    /// Skip whitespace but not newlines
    fn skip_whitespace(&mut self) {
        self.advance_while(|ch| ch == ' ' || ch == '\t');
    }

    /// Skip whitespace and comments
    fn skip_whitespace_and_comments(&mut self) {
        loop {
            self.skip_whitespace();

            // Skip comments
            if self.peek() == Some('#') {
                self.advance_while(|ch| ch != '\n');
                self.advance();
                continue;
            }

            // Skip newlines
            if self.peek() == Some('\n') || self.peek() == Some('\r') {
                self.advance();
                continue;
            }

            break;
        }
    }

    /// Peek at the current character.
    ///
    /// 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.input.get(self.position..)?.chars().next()
    }

    /// 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.input.get(start..self.position).unwrap_or("")
    }

    /// Advance to the next character
    fn advance(&mut self) -> Option<char> {
        if let Some(ch) = self.peek() {
            self.position += ch.len_utf8();
            if ch == '\n' {
                self.line += 1;
                self.column = 1;
            } else {
                self.column += 1;
            }
            Some(ch)
        } else {
            None
        }
    }

    /// Advance over every character for which `keep` holds.
    ///
    /// An ASCII byte is checked and stepped over directly; anything else
    /// is decoded as a character, so `position` stays on a character
    /// boundary and `line` and `column` count as [`advance`] does.
    ///
    /// [`advance`]: ConfParser::advance
    fn advance_while(&mut self, keep: impl Fn(char) -> bool) {
        let bytes = self.input.as_bytes();
        while let Some(&byte) = bytes.get(self.position) {
            if byte.is_ascii() {
                let ch = char::from(byte);
                if !keep(ch) {
                    break;
                }
                self.position += 1;
                if byte == b'\n' {
                    self.line += 1;
                    self.column = 1;
                } else {
                    self.column += 1;
                }
            } else {
                match self.peek() {
                    Some(ch) if keep(ch) => {
                        self.advance();
                    }
                    _ => break,
                }
            }
        }
    }

    /// Expect a specific character
    fn expect(&mut self, expected: char) -> Result<()> {
        match self.advance() {
            Some(ch) if ch == expected => Ok(()),
            Some(ch) => Err(Error::parse(
                format!("Expected '{expected}', found '{ch}'"),
                self.line,
                self.column,
            )),
            None => Err(Error::parse(
                format!("Expected '{expected}', found end of input"),
                self.line,
                self.column,
            )),
        }
    }

    /// Check if we're at the end of input
    fn is_at_end(&self) -> bool {
        self.position >= self.input.len()
    }
}

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

    #[test]
    fn test_simple_key_value() {
        let config = parse("key = value").unwrap();
        assert_eq!(config.get("key").unwrap().as_string().unwrap(), "value");
    }

    #[test]
    fn test_numbers() {
        let config = parse("int = 42\nfloat = 1.234").unwrap();
        assert_eq!(config.get("int").unwrap().as_integer().unwrap(), 42);
        assert_eq!(config.get("float").unwrap().as_float().unwrap(), 1.234);
    }

    #[test]
    fn test_booleans() {
        let config = parse("bool1 = true\nbool2 = false").unwrap();
        assert!(config.get("bool1").unwrap().as_bool().unwrap());
        assert!(!config.get("bool2").unwrap().as_bool().unwrap());
    }

    #[test]
    fn test_quoted_strings() {
        let config = parse(r#"quoted = "hello world""#).unwrap();
        assert_eq!(
            config.get("quoted").unwrap().as_string().unwrap(),
            "hello world"
        );
    }

    #[test]
    fn test_sections() {
        let config = parse("[section]\nkey = value").unwrap();
        assert_eq!(
            config.get("section.key").unwrap().as_string().unwrap(),
            "value"
        );
    }

    #[test]
    fn test_arrays() {
        let config = parse("arr = item1 item2 item3").unwrap();
        let arr = config.get("arr").unwrap().as_array().unwrap();
        assert_eq!(arr.len(), 3);
        assert_eq!(arr[0].as_string().unwrap(), "item1");
    }

    #[test]
    fn test_bracket_arrays_of_unquoted_items() {
        let config = parse("ports = [80, 443]\nhosts = [a, b c]\nnested = [[1, 2], [3]]").unwrap();
        let ports = config.get("ports").unwrap().as_array().unwrap();
        assert_eq!(ports.len(), 2);
        assert_eq!(ports[1].as_integer().unwrap(), 443);
        let hosts = config.get("hosts").unwrap().as_array().unwrap();
        assert_eq!(hosts.len(), 2);
        assert_eq!(hosts[1].as_string().unwrap(), "b c");
        let nested = config.get("nested").unwrap().as_array().unwrap();
        assert_eq!(nested.len(), 2);
        assert_eq!(nested[0].as_array().unwrap().len(), 2);
        // Without brackets, spaces and commas still make a list.
        let config = parse("list = 1, 2 3").unwrap();
        assert_eq!(config.get("list").unwrap().as_array().unwrap().len(), 3);
    }

    #[test]
    fn test_a_repeated_section_continues_and_an_empty_one_is_left_out() {
        let value = parse("[a]\nx = 1\n[empty]\n[b]\ny = 2\n[a]\nz = 3\n").unwrap();
        let root = value.as_table().unwrap();
        assert_eq!(root.len(), 2);
        let a = root["a"].as_table().unwrap();
        assert_eq!(a["x"].as_integer().unwrap(), 1);
        assert_eq!(a["z"].as_integer().unwrap(), 3);
        assert_eq!(root["b"].as_table().unwrap()["y"].as_integer().unwrap(), 2);
    }

    #[test]
    fn test_a_section_named_like_a_key_is_refused() {
        // Its keys used to be dropped without a word.
        match parse("db = on\n[db]\npassword = hunter2\n") {
            Err(Error::Parse { line, message, .. }) => {
                assert_eq!(line, 2);
                assert!(!message.contains("hunter2"));
            }
            other => panic!("expected a parse error, got {other:?}"),
        }
    }

    #[test]
    fn test_words_match_in_any_ascii_case() {
        let value = parse("a = TRUE\nb = Off\nc = NiL\nd = truth\ne = Ünïcode\n").unwrap();
        let root = value.as_table().unwrap();
        assert!(root["a"].as_bool().unwrap());
        assert!(!root["b"].as_bool().unwrap());
        assert!(root["c"].is_null());
        assert_eq!(root["d"].as_string().unwrap(), "truth");
        assert_eq!(root["e"].as_string().unwrap(), "Ünïcode");
    }

    #[test]
    fn test_comments() {
        let config = parse("# This is a comment\nkey = value # inline comment").unwrap();
        assert_eq!(config.get("key").unwrap().as_string().unwrap(), "value");
    }

    #[test]
    fn non_ascii_comment_before_section_does_not_panic() {
        // Used to slice at a character count instead of a byte offset
        let config = parse("#\u{e9}\u{e9}\u{e9}\n[a]\nk = 1\n").unwrap();
        assert_eq!(config.get("a.k").unwrap().as_integer().unwrap(), 1);
    }

    #[test]
    fn non_ascii_keys_values_and_comments() {
        let source = "# caf\u{e9} \u{4e2d}\u{6587}\n\
                      n\u{e4}me = J\u{fc}rgen # \u{2713}\n\
                      [se\u{e7}\u{e3}o]\n\
                      \u{43a}\u{43b}\u{44e}\u{447} = '\u{1F600} single'\n\
                      quoted = \"\u{3b1}\\t\u{3b2}\"\n\
                      list = [\"\u{e9}\", '\u{fc}']\n";
        let config = parse(source).unwrap();
        assert_eq!(
            config.get("n\u{e4}me").unwrap().as_string().unwrap(),
            "J\u{fc}rgen"
        );
        let section = config.get("se\u{e7}\u{e3}o").unwrap();
        assert_eq!(
            section
                .get("\u{43a}\u{43b}\u{44e}\u{447}")
                .unwrap()
                .as_string()
                .unwrap(),
            "\u{1F600} single"
        );
        assert_eq!(
            section.get("quoted").unwrap().as_string().unwrap(),
            "\u{3b1}\t\u{3b2}"
        );
        let list = section.get("list").unwrap().as_array().unwrap();
        assert_eq!(list[0].as_string().unwrap(), "\u{e9}");
        assert_eq!(list[1].as_string().unwrap(), "\u{fc}");
    }

    #[test]
    fn error_columns_count_characters() {
        // Four two-byte characters and four one-byte characters give the
        // same column: columns count characters, not bytes.
        let wide = parse("\u{43a}\u{43b}\u{44e}\u{447} ? 1").unwrap_err();
        let narrow = parse("abcd ? 1").unwrap_err();
        for err in [wide, narrow] {
            match err {
                Error::Parse { line, column, .. } => assert_eq!((line, column), (1, 7)),
                other => panic!("expected a parse error, got {other:?}"),
            }
        }
        match parse("# \u{e9}\u{e9}\n\u{e9} = 1\n[open\n").unwrap_err() {
            Error::Parse { line, .. } => assert_eq!(line, 3),
            other => panic!("expected a parse error, got {other:?}"),
        }
    }

    #[test]
    fn deep_array_nesting_is_an_error() {
        let ok = format!(
            "k = {}{}",
            "[".repeat(MAX_ARRAY_DEPTH),
            "]".repeat(MAX_ARRAY_DEPTH)
        );
        assert!(parse(&ok).is_ok());
        let deep = format!("k = {}", "[".repeat(MAX_ARRAY_DEPTH + 1));
        assert!(parse(&deep).is_err());
        // A million levels is an error, not a stack overflow
        assert!(parse(&format!("k = {}", "[".repeat(1_000_000))).is_err());
    }
}