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
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
//! YAML Node Diffing Utilities
//!
//! Provides functions and types for comparing YAML nodes and reporting differences.
//! Includes diff types, result structures, and helpers for formatting and analyzing
//! changes between YAML node trees, supporting both scalars and collections.
//!
//! Copyright (c) 2026 YAML Library Developers

use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;

use crate::nodes::node::Node;

/// Type of difference between nodes
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DiffType {
    /// Node was added
    Added,
    /// Node was removed
    Removed,
    /// Node was modified
    Modified,
    /// Node type changed
    TypeChanged,
    /// Collection size changed
    SizeChanged,
}

/// A difference between two nodes
#[derive(Debug, Clone)]
pub struct Diff {
    pub diff_type: DiffType,
    pub path: String,
    pub old_value: Option<String>,
    pub new_value: Option<String>,
    pub description: String,
}

impl Diff {
    /// Create a new diff
    pub fn new(diff_type: DiffType, path: String, description: String) -> Self {
        Self {
            diff_type,
            path,
            old_value: None,
            new_value: None,
            description,
        }
    }

    /// Create with old and new values
    pub fn with_values(
        diff_type: DiffType,
        path: String,
        old_value: Option<String>,
        new_value: Option<String>,
        description: String,
    ) -> Self {
        Self {
            diff_type,
            path,
            old_value,
            new_value,
            description,
        }
    }

    /// Format as a readable string
    pub fn format(&self) -> String {
        let mut result = format!("[{:?}] {}: {}", self.diff_type, self.path, self.description);

        if let Some(old) = &self.old_value {
            result.push_str(&format!("\n  Old: {}", old));
        }

        if let Some(new) = &self.new_value {
            result.push_str(&format!("\n  New: {}", new));
        }

        result
    }
}

/// Result of a diff operation
#[derive(Debug, Clone)]
pub struct DiffResult {
    pub diffs: Vec<Diff>,
    pub identical: bool,
}

impl DiffResult {
    /// Create a new diff result
    pub fn new() -> Self {
        Self {
            diffs: Vec::new(),
            identical: true,
        }
    }

    /// Add a diff
    pub fn add_diff(&mut self, diff: Diff) {
        self.identical = false;
        self.diffs.push(diff);
    }

    /// Check if nodes are identical
    pub fn is_identical(&self) -> bool {
        self.identical
    }

    /// Get number of differences
    pub fn count(&self) -> usize {
        self.diffs.len()
    }

    /// Format all diffs as a string
    pub fn format(&self) -> String {
        if self.identical {
            "No differences found".to_string()
        } else {
            let mut result = format!("Found {} difference(s):\n", self.count());
            for diff in &self.diffs {
                result.push_str(&diff.format());
                result.push('\n');
            }
            result
        }
    }
}

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

/// Compare two nodes and find differences
pub fn diff_nodes(old: &Node, new: &Node) -> DiffResult {
    let mut result = DiffResult::new();
    diff_nodes_impl(old, new, String::new(), &mut result);
    result
}

fn diff_nodes_impl(old: &Node, new: &Node, path: String, result: &mut DiffResult) {
    use crate::devtools::inspect::{node_summary, node_type};

    let old_type = node_type(old);
    let new_type = node_type(new);

    // Check type difference
    if old_type != new_type {
        result.add_diff(Diff::with_values(
            DiffType::TypeChanged,
            path.clone(),
            Some(old_type.as_str().to_string()),
            Some(new_type.as_str().to_string()),
            format!("Type changed from {:?} to {:?}", old_type, new_type),
        ));
        return;
    }

    // Check value differences based on type
    match (old, new) {
        (Node::None, Node::None) => {}
        (Node::Boolean(o), Node::Boolean(n)) if o == n => {}
        (Node::Number(o), Node::Number(n)) if o == n => {}
        (Node::Str(o, _, _), Node::Str(n, _, _)) if o == n => {}

        (Node::Boolean(o), Node::Boolean(n)) => {
            result.add_diff(Diff::with_values(
                DiffType::Modified,
                path,
                Some(o.to_string()),
                Some(n.to_string()),
                "Boolean value changed".to_string(),
            ));
        }

        (Node::Number(o), Node::Number(n)) => {
            result.add_diff(Diff::with_values(
                DiffType::Modified,
                path,
                Some(format!("{:?}", o)),
                Some(format!("{:?}", n)),
                "Number value changed".to_string(),
            ));
        }

        (Node::Str(o, _, _), Node::Str(n, _, _)) => {
            result.add_diff(Diff::with_values(
                DiffType::Modified,
                path,
                Some(o.clone()),
                Some(n.clone()),
                "String value changed".to_string(),
            ));
        }

        (Node::Array(old_items), Node::Array(new_items)) => {
            if old_items.len() != new_items.len() {
                result.add_diff(Diff::with_values(
                    DiffType::SizeChanged,
                    path.clone(),
                    Some(old_items.len().to_string()),
                    Some(new_items.len().to_string()),
                    "Array size changed".to_string(),
                ));
            }

            let min_len = old_items.len().min(new_items.len());
            for i in 0..min_len {
                let item_path = format!("{}[{}]", path, i);
                diff_nodes_impl(&old_items[i], &new_items[i], item_path, result);
            }

            // Handle extra items
            for i in min_len..old_items.len() {
                let item_path = format!("{}[{}]", path, i);
                result.add_diff(Diff::with_values(
                    DiffType::Removed,
                    item_path,
                    Some(node_summary(&old_items[i])),
                    None,
                    "Array item removed".to_string(),
                ));
            }

            for i in min_len..new_items.len() {
                let item_path = format!("{}[{}]", path, i);
                result.add_diff(Diff::with_values(
                    DiffType::Added,
                    item_path,
                    None,
                    Some(node_summary(&new_items[i])),
                    "Array item added".to_string(),
                ));
            }
        }

        (Node::Mapping(old_pairs), Node::Mapping(new_pairs)) => {
            if old_pairs.len() != new_pairs.len() {
                result.add_diff(Diff::with_values(
                    DiffType::SizeChanged,
                    path.clone(),
                    Some(old_pairs.len().to_string()),
                    Some(new_pairs.len().to_string()),
                    "Mapping size changed".to_string(),
                ));
            }

            // Compare common keys
            for (old_key, old_val) in old_pairs {
                let key_str = match old_key {
                    Node::Str(s, _, _) => s.clone(),
                    _ => format!("{:?}", old_key),
                };

                let new_val = new_pairs.iter().find(|(k, _)| k == old_key).map(|(_, v)| v);

                let item_path = if path.is_empty() {
                    key_str.clone()
                } else {
                    format!("{}.{}", path, key_str)
                };

                match new_val {
                    Some(nv) => diff_nodes_impl(old_val, nv, item_path, result),
                    None => {
                        result.add_diff(Diff::with_values(
                            DiffType::Removed,
                            item_path,
                            Some(node_summary(old_val)),
                            None,
                            "Mapping key removed".to_string(),
                        ));
                    }
                }
            }

            // Check for added keys
            for (new_key, new_val) in new_pairs {
                let exists = old_pairs.iter().any(|(k, _)| k == new_key);
                if !exists {
                    let key_str = match new_key {
                        Node::Str(s, _, _) => s.clone(),
                        _ => format!("{:?}", new_key),
                    };

                    let item_path = if path.is_empty() {
                        key_str.clone()
                    } else {
                        format!("{}.{}", path, key_str)
                    };

                    result.add_diff(Diff::with_values(
                        DiffType::Added,
                        item_path,
                        None,
                        Some(node_summary(new_val)),
                        "Mapping key added".to_string(),
                    ));
                }
            }
        }

        _ => {
            // Fallback for other types
            if node_summary(old) != node_summary(new) {
                result.add_diff(Diff::with_values(
                    DiffType::Modified,
                    path,
                    Some(node_summary(old)),
                    Some(node_summary(new)),
                    "Value changed".to_string(),
                ));
            }
        }
    }
}

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

    #[test]
    fn test_identical_nodes() {
        let node1 = Node::from("test");
        let node2 = Node::from("test");

        let result = diff_nodes(&node1, &node2);
        assert!(result.is_identical());
        assert_eq!(result.count(), 0);
    }

    #[test]
    fn test_different_strings() {
        let node1 = Node::from("old");
        let node2 = Node::from("new");

        let result = diff_nodes(&node1, &node2);
        assert!(!result.is_identical());
        assert_eq!(result.count(), 1);
        assert_eq!(result.diffs[0].diff_type, DiffType::Modified);
    }

    #[test]
    fn test_type_change() {
        let node1 = Node::from("test");
        let node2 = Node::from(42);

        let result = diff_nodes(&node1, &node2);
        assert!(!result.is_identical());
        assert_eq!(result.diffs[0].diff_type, DiffType::TypeChanged);
    }

    #[test]
    fn test_array_size_change() {
        let node1 = Node::Array(vec![Node::from(1), Node::from(2)]);
        let node2 = Node::Array(vec![Node::from(1), Node::from(2), Node::from(3)]);

        let result = diff_nodes(&node1, &node2);
        assert!(!result.is_identical());
        assert!(
            result
                .diffs
                .iter()
                .any(|d| d.diff_type == DiffType::SizeChanged)
        );
        assert!(result.diffs.iter().any(|d| d.diff_type == DiffType::Added));
    }

    #[test]
    fn test_mapping_key_added() {
        let node1 = Node::Mapping(vec![(Node::from("name"), Node::from("Alice"))]);
        let node2 = Node::Mapping(vec![
            (Node::from("name"), Node::from("Alice")),
            (Node::from("age"), Node::from(30)),
        ]);

        let result = diff_nodes(&node1, &node2);
        assert!(!result.is_identical());
        assert!(result.diffs.iter().any(|d| d.diff_type == DiffType::Added));
    }

    #[test]
    fn test_mapping_key_removed() {
        let node1 = Node::Mapping(vec![
            (Node::from("name"), Node::from("Alice")),
            (Node::from("age"), Node::from(30)),
        ]);
        let node2 = Node::Mapping(vec![(Node::from("name"), Node::from("Alice"))]);

        let result = diff_nodes(&node1, &node2);
        assert!(!result.is_identical());
        assert!(
            result
                .diffs
                .iter()
                .any(|d| d.diff_type == DiffType::Removed)
        );
    }

    #[test]
    fn test_diff_format() {
        let diff = Diff::with_values(
            DiffType::Modified,
            "test.value".to_string(),
            Some("old".to_string()),
            Some("new".to_string()),
            "Value changed".to_string(),
        );

        let formatted = diff.format();
        assert!(formatted.contains("Modified"));
        assert!(formatted.contains("test.value"));
        assert!(formatted.contains("old"));
        assert!(formatted.contains("new"));
    }

    #[test]
    fn test_diff_added_node() {
        let node1 = Node::Array(vec![Node::from(1)]);
        let node2 = Node::Array(vec![Node::from(1), Node::from(2)]);
        let result = diff_nodes(&node1, &node2);
        assert!(result.diffs.iter().any(|d| d.diff_type == DiffType::Added));
        assert!(
            result
                .diffs
                .iter()
                .any(|d| d.diff_type == DiffType::SizeChanged)
        );
    }

    #[test]
    fn test_diff_removed_node() {
        let node1 = Node::Array(vec![Node::from(1), Node::from(2)]);
        let node2 = Node::Array(vec![Node::from(1)]);
        let result = diff_nodes(&node1, &node2);
        assert!(
            result
                .diffs
                .iter()
                .any(|d| d.diff_type == DiffType::Removed)
        );
        assert!(
            result
                .diffs
                .iter()
                .any(|d| d.diff_type == DiffType::SizeChanged)
        );
    }

    #[test]
    fn test_diff_modified_number() {
        let node1 = Node::from(10);
        let node2 = Node::from(20);
        let result = diff_nodes(&node1, &node2);
        assert!(
            result
                .diffs
                .iter()
                .any(|d| d.diff_type == DiffType::Modified)
        );
        assert!(result.diffs[0].description.contains("Number value changed"));
    }

    #[test]
    fn test_diff_type_changed_between_array_and_mapping() {
        let node1 = Node::Array(vec![Node::from(1)]);
        let node2 = Node::Mapping(vec![(Node::from("a"), Node::from(1))]);
        let result = diff_nodes(&node1, &node2);
        assert!(
            result
                .diffs
                .iter()
                .any(|d| d.diff_type == DiffType::TypeChanged)
        );
    }

    #[test]
    fn test_diff_result_format_no_differences() {
        let node1 = Node::from("same");
        let node2 = Node::from("same");
        let result = diff_nodes(&node1, &node2);
        let formatted = result.format();
        assert!(formatted.contains("No differences found"));
    }
}