rust-yaml 0.0.5

A fast, safe YAML 1.2 library for Rust
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
//! YAML constructor for building Rust objects

use crate::{
    BasicComposer, CommentPreservingComposer, CommentedValue, Composer, Error, Limits, Position,
    Result, Value,
};

/// Trait for YAML constructors that convert document nodes to Rust objects
pub trait Constructor {
    /// Construct a single value
    fn construct(&mut self) -> Result<Option<Value>>;

    /// Check if there are more values to construct
    fn check_data(&self) -> bool;

    /// Reset the constructor state
    fn reset(&mut self);
}

/// Trait for comment-preserving constructors
pub trait CommentPreservingConstructor {
    /// Construct a single value with comments
    fn construct_commented(&mut self) -> Result<Option<CommentedValue>>;

    /// Check if there are more values to construct
    fn check_data(&self) -> bool;

    /// Reset the constructor state
    fn reset(&mut self);
}

/// Safe constructor that only constructs basic YAML types
#[derive(Debug)]
pub struct SafeConstructor {
    composer: BasicComposer,
    position: Position,
    limits: Limits,
}

impl SafeConstructor {
    /// Create a new safe constructor with input text
    pub fn new(input: String) -> Self {
        Self::with_limits(input, Limits::default())
    }

    /// Create a new safe constructor with custom limits
    pub fn with_limits(input: String, limits: Limits) -> Self {
        // Use eager composer for better anchor/alias support
        let composer = BasicComposer::new_eager_with_limits(input, limits.clone());
        let position = Position::start();

        Self {
            composer,
            position,
            limits,
        }
    }

    /// Create constructor from existing composer
    pub fn from_composer(composer: BasicComposer) -> Self {
        let position = Position::start();
        let limits = Limits::default();

        Self {
            composer,
            position,
            limits,
        }
    }

    /// Create constructor from existing composer with custom limits
    pub fn from_composer_with_limits(composer: BasicComposer, limits: Limits) -> Self {
        let position = Position::start();

        Self {
            composer,
            position,
            limits,
        }
    }

    /// Validate and potentially transform a value for safety
    fn validate_value(&self, value: Value) -> Result<Value> {
        match value {
            // Basic scalar types are always safe
            Value::Null | Value::Bool(_) | Value::Int(_) | Value::Float(_) | Value::String(_) => {
                Ok(value)
            }

            // Sequences are safe if all elements are safe
            Value::Sequence(seq) => {
                // Check collection size limit
                if seq.len() > self.limits.max_collection_size {
                    return Err(Error::limit_exceeded(format!(
                        "Sequence size {} exceeds max_collection_size limit of {}",
                        seq.len(),
                        self.limits.max_collection_size
                    )));
                }
                let mut safe_seq = Vec::with_capacity(seq.len());
                for item in seq {
                    safe_seq.push(self.validate_value(item)?);
                }
                Ok(Value::Sequence(safe_seq))
            }

            // Mappings are safe if all keys and values are safe
            Value::Mapping(map) => {
                // Check collection size limit
                if map.len() > self.limits.max_collection_size {
                    return Err(Error::limit_exceeded(format!(
                        "Mapping size {} exceeds max_collection_size limit of {}",
                        map.len(),
                        self.limits.max_collection_size
                    )));
                }
                let mut safe_map = indexmap::IndexMap::new();
                for (key, val) in map {
                    let safe_key = self.validate_value(key)?;
                    let safe_val = self.validate_value(val)?;
                    safe_map.insert(safe_key, safe_val);
                }
                Ok(Value::Mapping(safe_map))
            }
        }
    }

    /// Apply additional safety checks and transformations
    fn apply_safety_rules(&self, value: Value) -> Result<Value> {
        match value {
            // Limit string length to prevent memory exhaustion
            Value::String(ref s) if s.len() > self.limits.max_string_length => {
                Err(Error::limit_exceeded(format!(
                    "String too long: {} bytes (max: {})",
                    s.len(),
                    self.limits.max_string_length
                )))
            }

            // Limit sequence length
            Value::Sequence(ref seq) if seq.len() > self.limits.max_collection_size => {
                Err(Error::limit_exceeded(format!(
                    "Sequence too long: {} elements (max: {})",
                    seq.len(),
                    self.limits.max_collection_size
                )))
            }

            // Limit mapping size
            Value::Mapping(ref map) if map.len() > self.limits.max_collection_size => {
                Err(Error::limit_exceeded(format!(
                    "Mapping too large: {} entries (max: {})",
                    map.len(),
                    self.limits.max_collection_size
                )))
            }

            // Recursively apply rules
            Value::Sequence(seq) => {
                let mut safe_seq = Vec::with_capacity(seq.len());
                for item in seq {
                    safe_seq.push(self.apply_safety_rules(item)?);
                }
                Ok(Value::Sequence(safe_seq))
            }

            Value::Mapping(map) => {
                let mut safe_map = indexmap::IndexMap::new();
                for (key, val) in map {
                    let safe_key = self.apply_safety_rules(key)?;
                    let safe_val = self.apply_safety_rules(val)?;
                    safe_map.insert(safe_key, safe_val);
                }
                Ok(Value::Mapping(safe_map))
            }

            // Other types are fine as-is
            _ => Ok(value),
        }
    }
}

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

impl Constructor for SafeConstructor {
    fn construct(&mut self) -> Result<Option<Value>> {
        // Get a document from the composer
        let document = match self.composer.compose_document()? {
            Some(doc) => doc,
            None => return Ok(None),
        };

        // Validate and apply safety rules
        let validated = self.validate_value(document)?;
        let safe_value = self.apply_safety_rules(validated)?;

        Ok(Some(safe_value))
    }

    fn check_data(&self) -> bool {
        self.composer.check_document()
    }

    fn reset(&mut self) {
        self.composer.reset();
        self.position = Position::start();
    }
}

/// Comment-preserving constructor that maintains comments during parsing
#[derive(Debug)]
pub struct RoundTripConstructor {
    composer: CommentPreservingComposer,
    position: Position,
    limits: Limits,
}

impl RoundTripConstructor {
    /// Create a new round-trip constructor with comment preservation
    pub fn new(input: String) -> Self {
        Self::with_limits(input, Limits::default())
    }

    /// Create a new round-trip constructor with custom limits
    pub fn with_limits(input: String, limits: Limits) -> Self {
        // Use comment-preserving composer
        let composer = CommentPreservingComposer::with_limits(input, limits.clone());
        let position = Position::start();

        Self {
            composer,
            position,
            limits,
        }
    }

    /// Parse the input and build CommentedValue tree
    fn parse_with_comments(&mut self) -> Result<Option<CommentedValue>> {
        // Use the comment-preserving composer directly
        self.composer.compose_document()
    }
}

impl CommentPreservingConstructor for RoundTripConstructor {
    fn construct_commented(&mut self) -> Result<Option<CommentedValue>> {
        self.parse_with_comments()
    }

    fn check_data(&self) -> bool {
        // Check if there are more documents to parse
        // For now, simple implementation
        true
    }

    fn reset(&mut self) {
        self.position = Position::start();
    }
}

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

    #[test]
    fn test_safe_scalar_construction() {
        let mut constructor = SafeConstructor::new("42".to_string());
        let result = constructor.construct().unwrap().unwrap();
        assert_eq!(result, Value::Int(42));
    }

    #[test]
    fn test_safe_sequence_construction() {
        let mut constructor = SafeConstructor::new("[1, 2, 3]".to_string());
        let result = constructor.construct().unwrap().unwrap();

        let expected = Value::Sequence(vec![Value::Int(1), Value::Int(2), Value::Int(3)]);
        assert_eq!(result, expected);
    }

    #[test]
    fn test_safe_mapping_construction() {
        let mut constructor = SafeConstructor::new("{'key': 'value'}".to_string());
        let result = constructor.construct().unwrap().unwrap();

        let mut expected_map = indexmap::IndexMap::new();
        expected_map.insert(
            Value::String("key".to_string()),
            Value::String("value".to_string()),
        );
        let expected = Value::Mapping(expected_map);

        assert_eq!(result, expected);
    }

    #[test]
    fn test_nested_construction() {
        let yaml_content = "{'users': [{'name': 'Alice', 'age': 30}]}";
        let mut constructor = SafeConstructor::new(yaml_content.to_string());
        let result = constructor.construct().unwrap().unwrap();

        if let Value::Mapping(map) = result {
            if let Some(Value::Sequence(users)) = map.get(&Value::String("users".to_string())) {
                assert_eq!(users.len(), 1);
                if let Value::Mapping(ref user) = users[0] {
                    assert_eq!(
                        user.get(&Value::String("name".to_string())),
                        Some(&Value::String("Alice".to_string()))
                    );
                    assert_eq!(
                        user.get(&Value::String("age".to_string())),
                        Some(&Value::Int(30))
                    );
                }
            }
        } else {
            panic!("Expected mapping");
        }
    }

    #[test]
    fn test_check_data() {
        let constructor = SafeConstructor::new("42".to_string());
        assert!(constructor.check_data());
    }

    #[test]
    fn test_multiple_types() {
        let yaml_content = "{'string': 'hello', 'int': 42, 'bool': true, 'null_key': null}";
        let mut constructor = SafeConstructor::new(yaml_content.to_string());
        let result = constructor.construct().unwrap().unwrap();

        if let Value::Mapping(map) = result {
            assert_eq!(
                map.get(&Value::String("string".to_string())),
                Some(&Value::String("hello".to_string()))
            );
            assert_eq!(
                map.get(&Value::String("int".to_string())),
                Some(&Value::Int(42))
            );
            assert_eq!(
                map.get(&Value::String("bool".to_string())),
                Some(&Value::Bool(true))
            );
            // The key is "null_key" (string) and the value should be null (Null type)
            assert_eq!(
                map.get(&Value::String("null_key".to_string())),
                Some(&Value::Null)
            );
        } else {
            panic!("Expected mapping");
        }
    }

    #[test]
    fn test_safety_limits() {
        // Test with a reasonable size that shouldn't cause timeouts
        let large_string = "a".repeat(1000); // Much smaller size for testing
        let yaml_content = format!("value: '{}'", large_string);
        let mut constructor = SafeConstructor::new(yaml_content);

        let result = constructor.construct();
        // This should succeed with a reasonable size
        match result {
            Ok(Some(value)) => {
                // Should get a mapping with a string value
                if let Value::Mapping(map) = value {
                    if let Some(Value::String(s)) = map.get(&Value::String("value".to_string())) {
                        assert_eq!(s.len(), 1000);
                    }
                }
            }
            Ok(None) => {
                // Empty document is also acceptable
            }
            Err(error) => {
                // If it fails, just ensure we have a meaningful error
                assert!(!error.to_string().is_empty());
            }
        }
    }

    #[test]
    fn test_boolean_values() {
        let test_cases = vec![
            ("true", true),
            ("false", false),
            ("yes", true),
            ("no", false),
            ("on", true),
            ("off", false),
        ];

        for (input, expected) in test_cases {
            let mut constructor = SafeConstructor::new(input.to_string());
            let result = constructor.construct().unwrap().unwrap();
            assert_eq!(result, Value::Bool(expected), "Failed for input: {}", input);
        }
    }

    #[test]
    fn test_null_values() {
        let test_cases = vec!["null", "~"];

        for input in test_cases {
            let mut constructor = SafeConstructor::new(input.to_string());
            let result = constructor.construct().unwrap().unwrap();
            assert_eq!(result, Value::Null, "Failed for input: {}", input);
        }
    }
}