config-lib 0.9.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
//! # Schema Validation
//!
//! Type-safe schema validation for configuration values.
//! Provides compile-time and runtime type checking with detailed error reporting.

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

/// Configuration schema definition
#[derive(Debug, Clone)]
pub struct Schema {
    fields: HashMap<String, FieldSchema>,
}

/// Schema definition for a single field
#[derive(Debug, Clone, PartialEq)]
pub struct FieldSchema {
    field_type: FieldType,
    required: bool,
    default: Option<Value>,
    description: Option<String>,
}

/// Supported field types for validation
#[derive(Debug, Clone, PartialEq)]
pub enum FieldType {
    /// Null value
    Null,
    /// Boolean value
    Bool,
    /// Integer value
    Integer,
    /// Float value
    Float,
    /// String value
    String,
    /// Array of specific type
    Array(Box<FieldType>),
    /// Table/object with field schemas
    Table(HashMap<String, FieldSchema>),
    /// Union of multiple types
    Union(Vec<FieldType>),
    /// Any type (no validation)
    Any,
}

/// Builder for creating schemas
pub struct SchemaBuilder {
    fields: HashMap<String, FieldSchema>,
}

impl SchemaBuilder {
    /// Create a new schema builder
    pub fn new() -> Self {
        Self {
            fields: HashMap::new(),
        }
    }

    /// Add a required string field
    pub fn require_string(mut self, name: &str) -> Self {
        self.fields.insert(
            name.to_string(),
            FieldSchema {
                field_type: FieldType::String,
                required: true,
                default: None,
                description: None,
            },
        );
        self
    }

    /// Add a required integer field
    pub fn require_integer(mut self, name: &str) -> Self {
        self.fields.insert(
            name.to_string(),
            FieldSchema {
                field_type: FieldType::Integer,
                required: true,
                default: None,
                description: None,
            },
        );
        self
    }

    /// Add a required boolean field
    pub fn require_bool(mut self, name: &str) -> Self {
        self.fields.insert(
            name.to_string(),
            FieldSchema {
                field_type: FieldType::Bool,
                required: true,
                default: None,
                description: None,
            },
        );
        self
    }

    /// Add an optional string field
    pub fn optional_string(mut self, name: &str) -> Self {
        self.fields.insert(
            name.to_string(),
            FieldSchema {
                field_type: FieldType::String,
                required: false,
                default: None,
                description: None,
            },
        );
        self
    }

    /// Add an optional integer field
    pub fn optional_integer(mut self, name: &str) -> Self {
        self.fields.insert(
            name.to_string(),
            FieldSchema {
                field_type: FieldType::Integer,
                required: false,
                default: None,
                description: None,
            },
        );
        self
    }

    /// Add an optional boolean field
    pub fn optional_bool(mut self, name: &str) -> Self {
        self.fields.insert(
            name.to_string(),
            FieldSchema {
                field_type: FieldType::Bool,
                required: false,
                default: None,
                description: None,
            },
        );
        self
    }

    /// Add a field with custom type
    pub fn field(mut self, name: &str, field_type: FieldType, required: bool) -> Self {
        self.fields.insert(
            name.to_string(),
            FieldSchema {
                field_type,
                required,
                default: None,
                description: None,
            },
        );
        self
    }

    /// Add a field with default value
    pub fn field_with_default(mut self, name: &str, field_type: FieldType, default: Value) -> Self {
        self.fields.insert(
            name.to_string(),
            FieldSchema {
                field_type,
                required: false,
                default: Some(default),
                description: None,
            },
        );
        self
    }

    /// Add description to the last added field
    pub fn with_description(mut self, description: &str) -> Self {
        if let Some((_, field)) = self.fields.iter_mut().last() {
            field.description = Some(description.to_string());
        }
        self
    }

    /// Build the schema
    pub fn build(self) -> Schema {
        Schema {
            fields: self.fields,
        }
    }
}

impl Default for SchemaBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl Schema {
    /// Create a new empty schema
    pub fn new() -> Self {
        Self {
            fields: HashMap::new(),
        }
    }

    /// Create a schema from a builder
    pub fn builder() -> SchemaBuilder {
        SchemaBuilder::new()
    }

    /// Validate a value against this schema
    pub fn validate(&self, value: &Value) -> Result<()> {
        match value {
            Value::Table(table) => self.validate_table(table, ""),
            _ => Err(Error::schema("", "Root value must be a table")),
        }
    }

    /// Validate a table against the schema
    fn validate_table(&self, table: &BTreeMap<String, Value>, path: &str) -> Result<()> {
        // Check required fields
        for (field_name, field_schema) in &self.fields {
            let field_path = if path.is_empty() {
                field_name.clone()
            } else {
                format!("{path}.{field_name}")
            };

            match table.get(field_name) {
                Some(value) => {
                    self.validate_field(value, field_schema, &field_path)?;
                }
                None => {
                    if field_schema.required {
                        return Err(Error::schema(
                            field_path,
                            format!("Required field '{field_name}' is missing"),
                        ));
                    }
                }
            }
        }

        // Check for unknown fields (optional - could be configurable)
        for field_name in table.keys() {
            if !self.fields.contains_key(field_name) {
                // For now, we allow unknown fields
                // Could add strict mode later
            }
        }

        Ok(())
    }

    /// Validate a single field
    fn validate_field(&self, value: &Value, schema: &FieldSchema, path: &str) -> Result<()> {
        self.validate_type(value, &schema.field_type, path)
    }

    /// Validate a value against a type
    fn validate_type(&self, value: &Value, field_type: &FieldType, path: &str) -> Result<()> {
        Self::validate_type_impl(value, field_type, path)
    }

    /// Implementation of type validation (static to avoid clippy warning)
    fn validate_type_impl(value: &Value, field_type: &FieldType, path: &str) -> Result<()> {
        match (value, field_type) {
            (Value::Null, FieldType::Null) => Ok(()),
            (Value::Bool(_), FieldType::Bool) => Ok(()),
            (Value::Integer(_), FieldType::Integer) => Ok(()),
            (Value::Float(_), FieldType::Float) => Ok(()),
            (Value::String(_), FieldType::String) => Ok(()),

            // Allow integer to float conversion
            (Value::Integer(_), FieldType::Float) => Ok(()),

            // Array validation
            (Value::Array(arr), FieldType::Array(element_type)) => {
                for (i, element) in arr.iter().enumerate() {
                    let element_path = format!("{path}[{i}]");
                    Self::validate_type_impl(element, element_type, &element_path)?;
                }
                Ok(())
            }

            // Table validation
            (Value::Table(table), FieldType::Table(table_schema)) => {
                // Create a temporary schema for nested validation
                let nested_schema = Schema {
                    fields: table_schema.clone(),
                };
                nested_schema.validate_table(table, path)
            }

            // Union type validation
            (value, FieldType::Union(types)) => {
                for union_type in types {
                    if Self::validate_type_impl(value, union_type, path).is_ok() {
                        return Ok(());
                    }
                }
                Err(Error::schema(
                    path.to_string(),
                    format!("Value does not match any of the union types: {types:?}"),
                ))
            }

            // Any type always validates
            (_, FieldType::Any) => Ok(()),

            // Type mismatch
            _ => Err(Error::schema(
                path.to_string(),
                format!("Expected {:?}, found {}", field_type, value.type_name()),
            )),
        }
    }
}

impl Default for Schema {
    fn default() -> Self {
        Self::new()
    }
}

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

    #[test]
    fn test_simple_schema() {
        let schema = SchemaBuilder::new()
            .require_string("name")
            .require_integer("port")
            .optional_bool("debug")
            .build();

        // Valid config
        let mut config = BTreeMap::new();
        config.insert("name".to_string(), Value::string("test"));
        config.insert("port".to_string(), Value::integer(8080));
        let config = Value::table(config);

        assert!(schema.validate(&config).is_ok());

        // Missing required field
        let mut config = BTreeMap::new();
        config.insert("name".to_string(), Value::string("test"));
        let config = Value::table(config);

        assert!(schema.validate(&config).is_err());

        // Wrong type
        let mut config = BTreeMap::new();
        config.insert("name".to_string(), Value::string("test"));
        config.insert("port".to_string(), Value::string("not a number"));
        let config = Value::table(config);

        assert!(schema.validate(&config).is_err());
    }

    #[test]
    fn test_array_schema() {
        let schema = SchemaBuilder::new()
            .field("items", FieldType::Array(Box::new(FieldType::String)), true)
            .build();

        // Valid array
        let mut config = BTreeMap::new();
        config.insert(
            "items".to_string(),
            Value::array(vec![
                Value::string("a"),
                Value::string("b"),
                Value::string("c"),
            ]),
        );
        let config = Value::table(config);

        assert!(schema.validate(&config).is_ok());

        // Invalid array element
        let mut config = BTreeMap::new();
        config.insert(
            "items".to_string(),
            Value::array(vec![
                Value::string("a"),
                Value::integer(123), // Wrong type
                Value::string("c"),
            ]),
        );
        let config = Value::table(config);

        assert!(schema.validate(&config).is_err());
    }

    #[test]
    fn test_union_type() {
        let schema = SchemaBuilder::new()
            .field(
                "value",
                FieldType::Union(vec![FieldType::String, FieldType::Integer]),
                true,
            )
            .build();

        // String value
        let mut config = BTreeMap::new();
        config.insert("value".to_string(), Value::string("test"));
        let config = Value::table(config);
        assert!(schema.validate(&config).is_ok());

        // Integer value
        let mut config = BTreeMap::new();
        config.insert("value".to_string(), Value::integer(42));
        let config = Value::table(config);
        assert!(schema.validate(&config).is_ok());

        // Invalid type
        let mut config = BTreeMap::new();
        config.insert("value".to_string(), Value::bool(true));
        let config = Value::table(config);
        assert!(schema.validate(&config).is_err());
    }
}