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
//! # XML Configuration Parser
//!
//! High-performance XML configuration parser using zero-copy parsing.
//! Supports common XML configuration patterns used in enterprise Java/.NET environments.
//!
//! ## Performance Features
//! - Zero-copy parsing using `quick-xml`
//! - Streaming parser for memory efficiency
//! - Feature-gated to ensure zero impact when disabled
//!
//! ## Supported XML Patterns
//! - Spring Boot application.xml
//! - ASP.NET Core appsettings.xml
//! - Maven/Gradle configuration XML
//! - Generic key-value XML structures

use crate::{error::Error, Result, Value};
#[cfg(feature = "xml")]
use quick_xml::{
    escape::resolve_predefined_entity,
    events::{BytesStart, Event},
    Reader, XmlVersion,
};
use std::collections::BTreeMap;

/// XML configuration parser with zero-copy optimizations
#[cfg(feature = "xml")]
pub struct XmlParser<'a> {
    reader: Reader<&'a [u8]>,
}

/// Deepest element nesting accepted. Deeper input is rejected so that
/// building and dropping the value tree cannot overflow the stack.
#[cfg(feature = "xml")]
const MAX_DEPTH: usize = 128;

/// An element whose end tag has not been seen yet
#[cfg(feature = "xml")]
struct OpenElement {
    name: String,
    children: BTreeMap<String, Value>,
    text: String,
}

#[cfg(feature = "xml")]
impl<'a> XmlParser<'a> {
    /// Create a new XML parser for the given content
    pub fn new(content: &'a str) -> Self {
        let reader = Reader::from_str(content);
        Self { reader }
    }

    /// Parse XML content into a Value tree.
    ///
    /// Elements become tables keyed by tag name and attributes become string
    /// entries. An element holding only text becomes that text, converted to a
    /// bool, integer or float when it parses as one; text next to child
    /// elements or attributes is stored under `"text"`. Repeated sibling
    /// elements with the same name are collected into an array in document
    /// order. Entity and character references (`&amp;`, `&#x41;`) and CDATA
    /// sections are resolved into the text.
    ///
    /// Errors are [`Error::Parse`] with the line and column (since v1.4.0;
    /// before, every XML error was an `Error::Io` with no position). The
    /// message never quotes the input.
    pub fn parse(&mut self) -> Result<Value> {
        self.parse_events().map_err(|e| match e {
            Error::Io { path, source } if path == XML_ERROR => {
                let (line, column) = self.position();
                Error::parse(source.to_string(), line, column)
            }
            other => other,
        })
    }

    /// Line and column (from 1) of the reader's position, or of its last
    /// syntax error
    fn position(&self) -> (usize, usize) {
        let at = match self.reader.error_position() {
            0 => self.reader.buffer_position(),
            p => p,
        };
        let bytes: &[u8] = self.reader.get_ref();
        let end = usize::try_from(at).unwrap_or(usize::MAX).min(bytes.len());
        let before = &bytes[..end];
        let line = before.split(|&b| b == b'\n').count();
        let line_start = before
            .iter()
            .rposition(|&b| b == b'\n')
            .map_or(0, |i| i + 1);
        // Count characters, not bytes: UTF-8 continuation bytes are skipped
        let column = before[line_start..]
            .iter()
            .filter(|&&b| b & 0xc0 != 0x80)
            .count()
            + 1;
        (line, column)
    }

    fn parse_events(&mut self) -> Result<Value> {
        let mut stack: Vec<OpenElement> = Vec::new();
        let mut root = BTreeMap::new();
        let mut buf = Vec::new();

        loop {
            match self.reader.read_event_into(&mut buf) {
                Ok(Event::Start(e)) => {
                    if stack.len() >= MAX_DEPTH {
                        return Err(xml_problem(
                            "XML elements are nested deeper than 128 levels",
                        ));
                    }
                    let (name, children) = Self::element(&e)?;
                    stack.push(OpenElement {
                        name,
                        children,
                        text: String::new(),
                    });
                }

                Ok(Event::End(_)) => {
                    if let Some(element) = stack.pop() {
                        let value = self.finish(element.children, element.text.trim());
                        let parent = match stack.last_mut() {
                            Some(parent) => &mut parent.children,
                            None => &mut root,
                        };
                        insert_child(parent, element.name, value);
                    }
                }

                Ok(Event::Empty(e)) => {
                    let (name, children) = Self::element(&e)?;
                    let parent = match stack.last_mut() {
                        Some(parent) => &mut parent.children,
                        None => &mut root,
                    };
                    insert_child(parent, name, Value::table(children));
                }

                Ok(Event::Text(e)) => {
                    if let Some(element) = stack.last_mut() {
                        element
                            .text
                            .push_str(&e.xml10_content().map_err(xml_error)?);
                    }
                }

                Ok(Event::CData(e)) => {
                    if let Some(element) = stack.last_mut() {
                        element
                            .text
                            .push_str(&e.xml10_content().map_err(xml_error)?);
                    }
                }

                Ok(Event::GeneralRef(e)) => {
                    if let Some(element) = stack.last_mut() {
                        if let Some(ch) = e.resolve_char_ref().map_err(xml_error)? {
                            element.text.push(ch);
                        } else {
                            let name = e.decode().map_err(xml_error)?;
                            match resolve_predefined_entity(&name) {
                                Some(text) => element.text.push_str(text),
                                None => return Err(xml_problem("XML unknown entity reference")),
                            }
                        }
                    }
                }

                Ok(Event::Eof) => {
                    if !stack.is_empty() {
                        return Err(xml_problem("XML element is not closed"));
                    }
                    break;
                }

                Err(e) => return Err(xml_error(e)),

                _ => {}
            }
            buf.clear();
        }

        Ok(Value::table(root))
    }

    /// Tag name and attributes of a start or empty tag
    fn element(e: &BytesStart<'_>) -> Result<(String, BTreeMap<String, Value>)> {
        let name = String::from_utf8_lossy(e.name().as_ref()).into_owned();
        let mut attributes = BTreeMap::new();
        for attr in e.attributes() {
            let attr = attr.map_err(xml_error)?;
            let key = String::from_utf8_lossy(attr.key.as_ref()).into_owned();
            let value = attr
                .normalized_value(XmlVersion::Implicit1_0)
                .map_err(xml_error)?
                .into_owned();
            attributes.insert(key, Value::string(value));
        }
        Ok((name, attributes))
    }

    /// Value of a closed element from its children/attributes and text
    fn finish(&self, mut children: BTreeMap<String, Value>, text: &str) -> Value {
        if text.is_empty() {
            Value::table(children)
        } else if children.is_empty() {
            self.parse_value(text)
        } else {
            children.insert("text".to_string(), self.parse_value(text));
            Value::table(children)
        }
    }

    /// Parse a text value into appropriate type
    fn parse_value(&self, text: &str) -> Value {
        // Try parsing as different types
        if let Ok(bool_val) = text.parse::<bool>() {
            Value::bool(bool_val)
        } else if let Ok(int_val) = text.parse::<i64>() {
            Value::integer(int_val)
        } else if let Ok(float_val) = text.parse::<f64>() {
            Value::float(float_val)
        } else {
            Value::string(text)
        }
    }
}

/// Store a child element, turning repeated names into an array
#[cfg(feature = "xml")]
fn insert_child(parent: &mut BTreeMap<String, Value>, name: String, value: Value) {
    match parent.get_mut(&name) {
        // Element values are never arrays themselves, so an array here was
        // built from earlier siblings with the same name
        Some(Value::Array(items)) => items.push(value),
        Some(existing) => {
            let first = std::mem::replace(existing, Value::Null);
            *existing = Value::array(vec![first, value]);
        }
        None => {
            parent.insert(name, value);
        }
    }
}

/// Marks an error raised while reading XML; [`XmlParser::parse`] turns it
/// into [`Error::Parse`] with a position
#[cfg(feature = "xml")]
const XML_ERROR: &str = "XML parsing error";

/// A problem found by this parser, with fixed text
#[cfg(feature = "xml")]
fn xml_problem(message: &'static str) -> Error {
    Error::io(
        XML_ERROR,
        std::io::Error::new(std::io::ErrorKind::InvalidData, message),
    )
}

/// A quick-xml error. Its text can hold a name or text from the input, so
/// only the fact of a syntax error is kept.
#[cfg(feature = "xml")]
fn xml_error(_err: impl std::fmt::Display) -> Error {
    xml_problem("XML syntax error")
}

#[cfg(feature = "xml")]
impl From<quick_xml::Error> for Error {
    fn from(err: quick_xml::Error) -> Self {
        Error::io(
            "XML parsing error".to_string(),
            std::io::Error::new(std::io::ErrorKind::InvalidData, err),
        )
    }
}

/// Parse XML format configuration
#[cfg(feature = "xml")]
pub fn parse(source: &str) -> Result<Value> {
    parse_xml(source)
}

/// Parse XML format configuration (fallback when XML is not available)
#[cfg(not(feature = "xml"))]
pub fn parse(_source: &str) -> Result<Value> {
    Err(crate::error::Error::feature_not_enabled("xml"))
}

/// Parse XML configuration from string
#[cfg(feature = "xml")]
pub fn parse_xml(content: &str) -> Result<Value> {
    let mut parser = XmlParser::new(content);
    parser.parse()
}

/// Placeholder when XML feature is disabled
#[cfg(not(feature = "xml"))]
pub fn parse_xml(_content: &str) -> Result<Value> {
    Err(crate::error::Error::feature_not_enabled("xml"))
}

#[cfg(all(test, feature = "xml"))]
mod tests {
    use super::*;

    #[test]
    fn test_basic_xml_parsing() -> crate::Result<()> {
        let xml = r#"
        <configuration>
            <database>
                <host>localhost</host>
                <port>5432</port>
                <enabled>true</enabled>
            </database>
            <app>
                <name>TestApp</name>
                <version>1.0</version>
            </app>
        </configuration>
        "#;

        let result = parse_xml(xml)?;

        if let Value::Table(config) = result {
            if let Some(Value::Table(db)) = config.get("configuration").and_then(|v| {
                if let Value::Table(t) = v {
                    t.get("database")
                } else {
                    None
                }
            }) {
                assert_eq!(db.get("host"), Some(&Value::string("localhost")));
                assert_eq!(db.get("port"), Some(&Value::integer(5432)));
                assert_eq!(db.get("enabled"), Some(&Value::bool(true)));
            } else {
                return Err(crate::Error::Parse {
                    message: "Expected database configuration".to_string(),
                    line: 0,
                    column: 0,
                    file: None,
                });
            }
        } else {
            return Err(crate::Error::Parse {
                message: "Expected table result".to_string(),
                line: 0,
                column: 0,
                file: None,
            });
        }
        Ok(())
    }

    #[test]
    fn test_xml_with_attributes() -> crate::Result<()> {
        let xml = r#"
        <config>
            <server host="localhost" port="8080" ssl="true">
                <name>MainServer</name>
            </server>
        </config>
        "#;

        let result = parse_xml(xml)?;

        if let Value::Table(config) = result {
            if let Some(Value::Table(server_config)) = config.get("config").and_then(|v| {
                if let Value::Table(t) = v {
                    t.get("server")
                } else {
                    None
                }
            }) {
                assert_eq!(server_config.get("host"), Some(&Value::string("localhost")));
                assert_eq!(server_config.get("port"), Some(&Value::string("8080")));
                assert_eq!(server_config.get("ssl"), Some(&Value::string("true")));
                assert_eq!(
                    server_config.get("name"),
                    Some(&Value::string("MainServer"))
                );
            } else {
                return Err(crate::Error::Parse {
                    message: "Expected server configuration".to_string(),
                    line: 0,
                    column: 0,
                    file: None,
                });
            }
        } else {
            return Err(crate::Error::Parse {
                message: "Expected table result".to_string(),
                line: 0,
                column: 0,
                file: None,
            });
        }
        Ok(())
    }

    #[test]
    fn test_self_closing_tags() -> crate::Result<()> {
        let xml = r#"
        <config>
            <feature name="auth" enabled="true" />
            <feature name="cache" enabled="false" />
        </config>
        "#;

        let result = parse_xml(xml)?;

        // Test passes if parsing doesn't panic
        assert!(matches!(result, Value::Table(_)));
        Ok(())
    }

    #[test]
    fn test_entities_cdata_and_repeated_elements() -> crate::Result<()> {
        let xml = r#"<config>
            <title>Tom &amp; Jerry &#x41;</title>
            <query><![CDATA[a < b && c]]></query>
            <server name="a &amp; b" />
            <host>one</host>
            <host>two</host>
            <host>three</host>
        </config>"#;
        let value = parse_xml(xml)?;
        let config = value.get("config").and_then(|v| v.as_table().ok()).cloned();
        let config = config.expect("config table");
        assert_eq!(config.get("title"), Some(&Value::string("Tom & Jerry A")));
        assert_eq!(config.get("query"), Some(&Value::string("a < b && c")));
        assert_eq!(
            config
                .get("server")
                .and_then(|s| s.as_table().ok())
                .and_then(|t| t.get("name")),
            Some(&Value::string("a & b"))
        );
        assert_eq!(
            config.get("host"),
            Some(&Value::array(vec![
                Value::string("one"),
                Value::string("two"),
                Value::string("three"),
            ]))
        );
        Ok(())
    }

    #[test]
    fn test_malformed_xml_is_an_error() {
        assert!(parse_xml("<a><b>1</b>").is_err(), "unclosed element");
        assert!(parse_xml("<a></b>").is_err(), "mismatched end tag");
        assert!(parse_xml("<a>&bogus;</a>").is_err(), "unknown entity");
        let deep = format!("{}1{}", "<a>".repeat(100_000), "</a>".repeat(100_000));
        assert!(parse_xml(&deep).is_err(), "nesting limit");
        let ok = format!("{}1{}", "<a>".repeat(128), "</a>".repeat(128));
        assert!(parse_xml(&ok).is_ok());
    }
}