babbel_yaml 0.1.0

Fast, modular YAML 1.2 parser and emitter with anchors, aliases, and tags
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
//! Schema Definition Types for YAML Validation
//!
//! This module provides types and structures for defining the expected schema of YAML documents,
//! similar to JSON Schema. It enables specifying types, constraints, and validation rules for YAML data.
//!
//! # Features
//! - Schema types for YAML nodes
//! - Support for constraints and validation rules
//! - Enables schema-driven validation
//!
//! # Usage
//! Use these types to define and enforce the structure of YAML documents.

use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::vec::Vec;

/// Schema type specifying the expected YAML node type
#[derive(Debug, Clone, PartialEq)]
pub enum SchemaType {
    /// String value
    String,
    /// Numeric value (integer or float)
    Number,
    /// Integer value only
    Integer,
    /// Float value only
    Float,
    /// Boolean value
    Boolean,
    /// Null value
    Null,
    /// Array/sequence
    Array,
    /// Object/mapping
    Object,
    /// Any type allowed
    Any,
}

/// Schema for object/mapping properties
#[derive(Debug, Clone)]
pub struct PropertySchema {
    /// Type of this property
    pub schema_type: SchemaType,
    /// Whether this property is required
    pub required: bool,
    /// Description of this property
    pub description: Option<String>,
    /// Minimum value (for numbers)
    pub minimum: Option<f64>,
    /// Maximum value (for numbers)
    pub maximum: Option<f64>,
    /// Minimum length (for strings/arrays)
    pub min_length: Option<usize>,
    /// Maximum length (for strings/arrays)
    pub max_length: Option<usize>,
    /// Pattern to match (for strings)
    pub pattern: Option<String>,
    /// Enum of allowed values (for strings)
    pub enum_values: Option<Vec<String>>,
    /// Nested schema for objects
    pub properties: Option<BTreeMap<String, PropertySchema>>,
    /// Schema for array items
    pub items: Option<Box<PropertySchema>>,
    /// Default value
    pub default: Option<String>,
}

impl PropertySchema {
    /// Create a new property schema with the given type
    pub fn new(schema_type: SchemaType) -> Self {
        Self {
            schema_type,
            required: false,
            description: None,
            minimum: None,
            maximum: None,
            min_length: None,
            max_length: None,
            pattern: None,
            enum_values: None,
            properties: None,
            items: None,
            default: None,
        }
    }

    /// Mark this property as required
    pub fn required(mut self) -> Self {
        self.required = true;
        self
    }

    /// Set description
    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
        self.description = Some(desc.into());
        self
    }

    /// Set minimum value
    pub fn with_minimum(mut self, min: f64) -> Self {
        self.minimum = Some(min);
        self
    }

    /// Set maximum value
    pub fn with_maximum(mut self, max: f64) -> Self {
        self.maximum = Some(max);
        self
    }

    /// Set minimum length
    pub fn with_min_length(mut self, len: usize) -> Self {
        self.min_length = Some(len);
        self
    }

    /// Set maximum length
    pub fn with_max_length(mut self, len: usize) -> Self {
        self.max_length = Some(len);
        self
    }

    /// Set pattern
    pub fn with_pattern(mut self, pattern: impl Into<String>) -> Self {
        self.pattern = Some(pattern.into());
        self
    }

    /// Set enum values
    pub fn with_enum(mut self, values: Vec<String>) -> Self {
        self.enum_values = Some(values);
        self
    }

    /// Set object properties
    pub fn with_properties(mut self, props: BTreeMap<String, PropertySchema>) -> Self {
        self.properties = Some(props);
        self
    }

    /// Set array items schema
    pub fn with_items(mut self, items: PropertySchema) -> Self {
        self.items = Some(Box::new(items));
        self
    }

    /// Set default value
    pub fn with_default(mut self, default: impl Into<String>) -> Self {
        self.default = Some(default.into());
        self
    }
}

/// Schema for arrays
#[derive(Debug, Clone)]
pub struct ArraySchema {
    /// Schema for items in the array
    pub items: PropertySchema,
    /// Minimum number of items
    pub min_items: Option<usize>,
    /// Maximum number of items
    pub max_items: Option<usize>,
    /// Whether items must be unique
    pub unique_items: bool,
}

impl ArraySchema {
    /// Create a new array schema
    pub fn new(items: PropertySchema) -> Self {
        Self {
            items,
            min_items: None,
            max_items: None,
            unique_items: false,
        }
    }

    /// Set minimum items
    pub fn with_min_items(mut self, min: usize) -> Self {
        self.min_items = Some(min);
        self
    }

    /// Set maximum items
    pub fn with_max_items(mut self, max: usize) -> Self {
        self.max_items = Some(max);
        self
    }

    /// Require unique items
    pub fn with_unique_items(mut self) -> Self {
        self.unique_items = true;
        self
    }
}

/// Schema for objects/mappings
#[derive(Debug, Clone)]
pub struct ObjectSchema {
    /// Properties of this object
    pub properties: BTreeMap<String, PropertySchema>,
    /// Required property names
    pub required: Vec<String>,
    /// Whether additional properties are allowed
    pub additional_properties: bool,
}

impl ObjectSchema {
    /// Create a new object schema
    pub fn new() -> Self {
        Self {
            properties: BTreeMap::new(),
            required: Vec::new(),
            additional_properties: true,
        }
    }

    /// Add a property
    pub fn with_property(mut self, name: impl Into<String>, schema: PropertySchema) -> Self {
        let name_str = name.into();
        if schema.required {
            self.required.push(name_str.clone());
        }
        self.properties.insert(name_str, schema);
        self
    }

    /// Disallow additional properties
    pub fn no_additional_properties(mut self) -> Self {
        self.additional_properties = false;
        self
    }

    /// Add a required property
    pub fn require(mut self, name: impl Into<String>) -> Self {
        self.required.push(name.into());
        self
    }
}

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

/// Complete schema for a YAML document
#[derive(Debug, Clone)]
pub struct Schema {
    /// Root schema type
    pub root: PropertySchema,
    /// Schema title
    pub title: Option<String>,
    /// Schema description
    pub description: Option<String>,
}

impl Schema {
    /// Create a new schema with the given root type
    pub fn new(root: PropertySchema) -> Self {
        Self {
            root,
            title: None,
            description: None,
        }
    }

    /// Set schema title
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Set schema description
    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
        self.description = Some(desc.into());
        self
    }

    /// Create a simple string schema
    pub fn string() -> Self {
        Self::new(PropertySchema::new(SchemaType::String))
    }

    /// Create a simple number schema
    pub fn number() -> Self {
        Self::new(PropertySchema::new(SchemaType::Number))
    }

    /// Create a simple integer schema
    pub fn integer() -> Self {
        Self::new(PropertySchema::new(SchemaType::Integer))
    }

    /// Create a simple boolean schema
    pub fn boolean() -> Self {
        Self::new(PropertySchema::new(SchemaType::Boolean))
    }

    /// Create an array schema
    pub fn array(items: PropertySchema) -> Self {
        Self::new(PropertySchema::new(SchemaType::Array).with_items(items))
    }

    /// Create an object schema
    pub fn object(properties: BTreeMap<String, PropertySchema>) -> Self {
        Self::new(PropertySchema::new(SchemaType::Object).with_properties(properties))
    }
}

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

    #[test]
    fn test_property_schema_builder() {
        let schema = PropertySchema::new(SchemaType::String)
            .required()
            .with_min_length(5)
            .with_max_length(50)
            .with_description("A test string");

        assert_eq!(schema.schema_type, SchemaType::String);
        assert!(schema.required);
        assert_eq!(schema.min_length, Some(5));
        assert_eq!(schema.max_length, Some(50));
        assert_eq!(schema.description, Some("A test string".to_string()));
    }

    #[test]
    fn test_array_schema() {
        let array = ArraySchema::new(PropertySchema::new(SchemaType::Integer))
            .with_min_items(1)
            .with_max_items(10)
            .with_unique_items();

        assert_eq!(array.items.schema_type, SchemaType::Integer);
        assert_eq!(array.min_items, Some(1));
        assert_eq!(array.max_items, Some(10));
        assert!(array.unique_items);
    }

    #[test]
    fn test_object_schema() {
        let obj = ObjectSchema::new()
            .with_property("name", PropertySchema::new(SchemaType::String).required())
            .with_property("age", PropertySchema::new(SchemaType::Integer))
            .no_additional_properties();

        assert_eq!(obj.properties.len(), 2);
        assert_eq!(obj.required.len(), 1);
        assert!(!obj.additional_properties);
    }

    #[test]
    fn test_schema_builders() {
        let string_schema = Schema::string();
        assert!(matches!(string_schema.root.schema_type, SchemaType::String));

        let number_schema = Schema::number();
        assert!(matches!(number_schema.root.schema_type, SchemaType::Number));

        let int_schema = Schema::integer();
        assert!(matches!(int_schema.root.schema_type, SchemaType::Integer));
    }

    #[test]
    fn test_schema_with_metadata() {
        let schema = Schema::string()
            .with_title("User Name")
            .with_description("The name of the user");

        assert_eq!(schema.title, Some("User Name".to_string()));
        assert_eq!(schema.description, Some("The name of the user".to_string()));
    }
}

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

    #[test]
    fn test_property_schema_default_values() {
        let schema = PropertySchema::new(SchemaType::Boolean);
        assert!(!schema.required);
        assert!(schema.description.is_none());
        assert!(schema.minimum.is_none());
        assert!(schema.maximum.is_none());
        assert!(schema.min_length.is_none());
        assert!(schema.max_length.is_none());
        assert!(schema.pattern.is_none());
        assert!(schema.enum_values.is_none());
        assert!(schema.properties.is_none());
        assert!(schema.items.is_none());
        assert!(schema.default.is_none());
    }

    #[test]
    fn test_property_schema_with_enum() {
        let schema = PropertySchema::new(SchemaType::String)
            .with_enum(vec!["A".to_string(), "B".to_string()]);
        assert_eq!(schema.enum_values, Some(vec!["A".to_string(), "B".to_string()]));
    }

    #[test]
    fn test_property_schema_with_items() {
        let item_schema = PropertySchema::new(SchemaType::Integer);
        let schema = PropertySchema::new(SchemaType::Array).with_items(item_schema.clone());
        assert!(schema.items.is_some());
        assert_eq!(schema.items.as_ref().unwrap().schema_type, SchemaType::Integer);
    }

    #[test]
    fn test_property_schema_with_properties() {
        let mut props = BTreeMap::new();
        props.insert("foo".to_string(), PropertySchema::new(SchemaType::String));
        let schema = PropertySchema::new(SchemaType::Object).with_properties(props.clone());
        assert!(schema.properties.is_some());
        assert_eq!(schema.properties.as_ref().unwrap().len(), 1);
        assert!(schema.properties.as_ref().unwrap().contains_key("foo"));
    }

    #[test]
    fn test_array_schema_defaults() {
        let schema = ArraySchema::new(PropertySchema::new(SchemaType::String));
        assert!(schema.min_items.is_none());
        assert!(schema.max_items.is_none());
        assert!(!schema.unique_items);
    }

    #[test]
    fn test_object_schema_defaults() {
        let schema = ObjectSchema::new();
        assert!(schema.properties.is_empty());
        assert!(schema.required.is_empty());
        assert!(schema.additional_properties);
    }

    #[test]
    fn test_schema_title_and_description() {
        let schema = Schema::new(PropertySchema::new(SchemaType::Null))
            .with_title("Null type")
            .with_description("A schema for null values");
        assert_eq!(schema.title, Some("Null type".to_string()));
        assert_eq!(schema.description, Some("A schema for null values".to_string()));
    }
}