babbel_yaml 0.1.1

Fast, modular YAML 1.2 parser and emitter with anchors, aliases, and tags
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
//! Performance Utilities for YAML Library
//!
//! This module provides performance measurement and optimization tools for YAML processing.
//! It includes profiling helpers and statistics gathering utilities to analyze and improve
//! the efficiency of YAML operations.
//!
//! # Features
//! - Profiling of YAML operations
//! - Gathering statistics on document structures
//! - Utilities for measuring and optimizing performance
//!
//! # Usage
//! Use these tools to profile, analyze, and optimize YAML processing code.

#[cfg(feature = "std")]
use std::time::{Duration, Instant};

#[cfg(feature = "alloc")]
use alloc::vec::Vec;

#[cfg(feature = "alloc")]
use alloc::string::String;

use crate::nodes::node::Node;
use crate::parser::utils::visit::visit_with_depth;

/// Statistics about a YAML document structure
#[derive(Clone, Debug, Default)]
pub struct DocumentStats {
    /// Total number of nodes in the document
    pub total_nodes: usize,

    /// Maximum nesting depth
    pub max_depth: usize,

    /// Number of string nodes
    pub string_count: usize,

    /// Number of numeric nodes
    pub number_count: usize,

    /// Number of boolean nodes
    pub boolean_count: usize,

    /// Number of array/sequence nodes
    pub array_count: usize,

    /// Number of mapping nodes
    pub mapping_count: usize,

    /// Number of set nodes
    pub set_count: usize,

    /// Number of anchor nodes
    pub anchor_count: usize,

    /// Number of alias nodes
    pub alias_count: usize,

    /// Number of tagged nodes
    pub tagged_count: usize,

    /// Total string length (bytes)
    pub total_string_bytes: usize,

    /// Largest array size
    pub largest_array: usize,

    /// Largest mapping size
    pub largest_mapping: usize,
}

impl DocumentStats {
    /// Create a new empty statistics object
    pub fn new() -> Self {
        Self::default()
    }

    /// Gather statistics from a Node tree
    ///
    /// # Example
    /// ```
    /// # use babbel_yaml::{Node, DocumentStats};
    /// let doc = Node::Array(vec![
    ///     Node::from(1),
    ///     Node::from("text"),
    ///     Node::Array(vec![Node::from(2)])
    /// ]);
    ///
    /// let stats = DocumentStats::from_node(&doc);
    /// assert_eq!(stats.total_nodes, 5);
    /// assert_eq!(stats.max_depth, 2);
    /// assert_eq!(stats.array_count, 2);
    /// ```
    pub fn from_node(node: &Node) -> Self {
        let mut stats = Self::new();
        visit_with_depth(node, 0, &mut |node, depth| {
            stats.total_nodes += 1;

            if depth > stats.max_depth {
                stats.max_depth = depth;
            }

            match node {
                Node::Str(s, _, _) => {
                    stats.string_count += 1;
                    stats.total_string_bytes += s.len();
                }
                Node::Number(_) => {
                    stats.number_count += 1;
                }
                Node::Boolean(_) => {
                    stats.boolean_count += 1;
                }
                Node::Array(items) => {
                    stats.array_count += 1;
                    if items.len() > stats.largest_array {
                        stats.largest_array = items.len();
                    }
                }
                Node::Mapping(pairs) => {
                    stats.mapping_count += 1;
                    if pairs.len() > stats.largest_mapping {
                        stats.largest_mapping = pairs.len();
                    }
                }
                Node::Set(_) => {
                    stats.set_count += 1;
                }
                Node::Document(_) | Node::Documents(_) => {}
                Node::Anchored(_, _) => {
                    stats.anchor_count += 1;
                }
                Node::Tagged(_, _) => {
                    stats.tagged_count += 1;
                }
                Node::Alias(_) => {
                    stats.alias_count += 1;
                }
                Node::Comment(_) | Node::None => {}
            }
        });
        stats
    }

    /// Calculate estimated memory usage in bytes
    pub fn estimated_memory_bytes(&self) -> usize {
        // Rough estimation based on typical sizes
        let node_overhead = self.total_nodes * 64; // ~64 bytes per Node enum
        let string_data = self.total_string_bytes;
        let collection_overhead = (self.array_count + self.mapping_count + self.set_count) * 24; // Vec overhead

        node_overhead + string_data + collection_overhead
    }

    /// Get a human-readable summary
    #[cfg(feature = "alloc")]
    pub fn summary(&self) -> String {
        alloc::format!(
            "Document Statistics:\n\
             - Total nodes: {}\n\
             - Max depth: {}\n\
             - Strings: {} ({} bytes)\n\
             - Numbers: {}\n\
             - Booleans: {}\n\
             - Arrays: {} (largest: {})\n\
             - Mappings: {} (largest: {})\n\
             - Sets: {}\n\
             - Anchors: {}\n\
             - Aliases: {}\n\
             - Tagged: {}\n\
             - Est. memory: {} bytes",
            self.total_nodes,
            self.max_depth,
            self.string_count,
            self.total_string_bytes,
            self.number_count,
            self.boolean_count,
            self.array_count,
            self.largest_array,
            self.mapping_count,
            self.largest_mapping,
            self.set_count,
            self.anchor_count,
            self.alias_count,
            self.tagged_count,
            self.estimated_memory_bytes()
        )
    }
}

/// Simple timer for measuring operation duration
#[cfg(feature = "std")]
#[derive(Debug)]
pub struct Timer {
    start: Instant,
    #[allow(dead_code)]
    label: String,
}

#[cfg(feature = "std")]
impl Timer {
    /// Start a new timer with a label
    pub fn new<S: Into<String>>(label: S) -> Self {
        Self {
            start: Instant::now(),
            label: label.into(),
        }
    }

    /// Get elapsed time since timer start
    pub fn elapsed(&self) -> Duration {
        self.start.elapsed()
    }

    /// Stop the timer and return elapsed duration
    pub fn stop(self) -> Duration {
        self.elapsed()
    }

    /// Stop the timer and print elapsed time (debug only)
    pub fn stop_and_print(self) {
        #[cfg(feature = "debug-trace")]
        {
            let elapsed = self.elapsed();
            println!("{}: {:?}", self.label, elapsed);
        }
    }
}

/// Performance profiler for measuring multiple operations
#[cfg(all(feature = "std", feature = "alloc"))]
#[derive(Debug, Default)]
pub struct Profiler {
    measurements: Vec<(String, Duration)>,
}

#[cfg(all(feature = "std", feature = "alloc"))]
impl Profiler {
    /// Create a new profiler
    pub fn new() -> Self {
        Self {
            measurements: Vec::new(),
        }
    }

    /// Time an operation and record it
    pub fn time<F, R>(&mut self, label: &str, f: F) -> R
    where
        F: FnOnce() -> R,
    {
        let start = Instant::now();
        let result = f();
        let elapsed = start.elapsed();
        self.measurements.push((label.to_string(), elapsed));
        result
    }

    /// Get all measurements
    pub fn measurements(&self) -> &[(String, Duration)] {
        &self.measurements
    }

    /// Get total time across all measurements
    pub fn total_time(&self) -> Duration {
        self.measurements.iter().map(|(_, d)| *d).sum()
    }

    /// Print all measurements (debug only)
    pub fn print_results(&self) {
        #[cfg(feature = "debug-trace")]
        {
            println!("Performance Profile:");
            println!("{:-<60}", "");
            for (label, duration) in &self.measurements {
                println!("{:<40} {:>15?}", label, duration);
            }
            println!("{:-<60}", "");
            println!("{:<40} {:>15?}", "Total", self.total_time());
        }
    }

    /// Clear all measurements
    pub fn clear(&mut self) {
        self.measurements.clear();
    }
}

/// Utility to compare performance of different approaches
#[cfg(feature = "std")]
pub fn compare_performance<F1, F2>(label1: &str, f1: F1, label2: &str, f2: F2)
where
    F1: FnOnce(),
    F2: FnOnce(),
{
    let timer1 = Timer::new(label1);
    f1();
    let time1 = timer1.stop();

    let timer2 = Timer::new(label2);
    f2();
    let time2 = timer2.stop();

    #[cfg(feature = "debug-trace")]
    println!("Performance Comparison:");
    #[cfg(feature = "debug-trace")]
    println!("  {}: {:?}", label1, time1);
    #[cfg(feature = "debug-trace")]
    println!("  {}: {:?}", label2, time2);

    if time1 < time2 {
        let _ratio = time2.as_secs_f64() / time1.as_secs_f64();
        #[cfg(feature = "debug-trace")]
        println!("  {} is {:.2}x faster", label1, _ratio);
    } else if time2 < time1 {
        let _ratio = time1.as_secs_f64() / time2.as_secs_f64();
        #[cfg(feature = "debug-trace")]
        println!("  {} is {:.2}x faster", label2, _ratio);
    } else {
        #[cfg(feature = "debug-trace")]
        println!("  Both approaches have similar performance");
    }
}

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

    #[test]
    fn test_document_stats_estimated_memory_bytes() {
        let mut stats = DocumentStats::new();
        stats.total_nodes = 3;
        stats.total_string_bytes = 10;
        stats.array_count = 1;
        stats.mapping_count = 1;
        stats.set_count = 1;
        let mem = stats.estimated_memory_bytes();
        assert!(mem >= 3 * 64 + 10 + 3 * 24);
    }

    #[test]
    #[cfg(feature = "alloc")]
    fn test_document_stats_summary() {
        let stats = DocumentStats {
            total_nodes: 2,
            max_depth: 1,
            string_count: 1,
            number_count: 1,
            boolean_count: 0,
            array_count: 0,
            mapping_count: 0,
            set_count: 0,
            anchor_count: 0,
            alias_count: 0,
            tagged_count: 0,
            total_string_bytes: 5,
            largest_array: 0,
            largest_mapping: 0,
        };
        let summary = stats.summary();
        assert!(summary.contains("Total nodes: 2"));
        assert!(summary.contains("Strings: 1 (5 bytes)"));
    }

    #[test]
    fn test_document_stats_from_node_edge_cases() {
        use crate::nodes::node::Node;
        let node = Node::None;
        let stats = DocumentStats::from_node(&node);
        assert_eq!(stats.total_nodes, 1);
        let node = Node::Array(vec![]);
        let stats = DocumentStats::from_node(&node);
        assert_eq!(stats.array_count, 1);
        let node = Node::Mapping(vec![]);
        let stats = DocumentStats::from_node(&node);
        assert_eq!(stats.mapping_count, 1);
    }

    #[test]
    #[cfg(feature = "std")]
    fn test_compare_performance_runs() {
        // Just check that it runs and doesn't panic
        compare_performance("a", || {}, "b", || {});
    }

    #[test]
    fn test_document_stats_empty() {
        let stats = DocumentStats::new();
        assert_eq!(stats.total_nodes, 0);
        assert_eq!(stats.max_depth, 0);
    }

    #[test]
    fn test_document_stats_simple() {
        let node = Node::from(42);
        let stats = DocumentStats::from_node(&node);

        assert_eq!(stats.total_nodes, 1);
        assert_eq!(stats.number_count, 1);
        assert_eq!(stats.max_depth, 0);
    }

    #[test]
    fn test_document_stats_array() {
        let node = Node::Array(vec![Node::from(1), Node::from(2), Node::from(3)]);
        let stats = DocumentStats::from_node(&node);

        assert_eq!(stats.total_nodes, 4); // array + 3 numbers
        assert_eq!(stats.array_count, 1);
        assert_eq!(stats.number_count, 3);
        assert_eq!(stats.largest_array, 3);
        assert_eq!(stats.max_depth, 1);
    }

    #[test]
    fn test_document_stats_nested() {
        let node = Node::Array(vec![
            Node::from(1),
            Node::Array(vec![Node::from(2), Node::from(3)]),
        ]);
        let stats = DocumentStats::from_node(&node);

        assert_eq!(stats.total_nodes, 5);
        assert_eq!(stats.array_count, 2);
        assert_eq!(stats.number_count, 3);
        assert_eq!(stats.max_depth, 2);
    }

    #[test]
    fn test_document_stats_mapping() {
        let node = Node::Mapping(vec![
            (Node::from("key1"), Node::from("value1")),
            (Node::from("key2"), Node::from("value2")),
        ]);
        let stats = DocumentStats::from_node(&node);

        assert_eq!(stats.total_nodes, 5); // mapping + 2 keys + 2 values
        assert_eq!(stats.mapping_count, 1);
        assert_eq!(stats.string_count, 4);
        assert_eq!(stats.largest_mapping, 2);
        assert_eq!(stats.total_string_bytes, 20); // "key1" + "value1" + "key2" + "value2"
    }

    #[test]
    fn test_document_stats_mixed() {
        let node = Node::Mapping(vec![
            (
                Node::from("numbers"),
                Node::Array(vec![Node::from(1), Node::from(2)]),
            ),
            (Node::from("text"), Node::from("hello")),
            (Node::from("flag"), Node::from(true)),
        ]);
        let stats = DocumentStats::from_node(&node);

        assert_eq!(stats.mapping_count, 1);
        assert_eq!(stats.array_count, 1);
        assert_eq!(stats.string_count, 4); // 3 keys + 1 value
        assert_eq!(stats.number_count, 2);
        assert_eq!(stats.boolean_count, 1);
    }

    #[test]
    fn test_document_stats_anchors() {
        use alloc::boxed::Box;

        let node = Node::Anchored(Box::new(Node::from(42)), "anchor".to_string());
        let stats = DocumentStats::from_node(&node);

        assert_eq!(stats.anchor_count, 1);
        assert_eq!(stats.number_count, 1);
    }

    #[test]
    fn test_document_stats_alias() {
        let node = Node::Alias("ref".to_string());
        let stats = DocumentStats::from_node(&node);

        assert_eq!(stats.alias_count, 1);
        assert_eq!(stats.total_nodes, 1);
    }

    #[test]
    fn test_document_stats_tagged() {
        use alloc::boxed::Box;

        let node = Node::Tagged(Box::new(Node::from("value")), "!custom".to_string());
        let stats = DocumentStats::from_node(&node);

        assert_eq!(stats.tagged_count, 1);
        assert_eq!(stats.string_count, 1);
    }

    #[test]
    fn test_estimated_memory() {
        let node = Node::Array(vec![Node::from(1), Node::from(2)]);
        let stats = DocumentStats::from_node(&node);

        let mem = stats.estimated_memory_bytes();
        assert!(mem > 0);
        // Should account for nodes and collection overhead
        assert!(mem >= stats.total_nodes * 64);
    }

    #[cfg(feature = "alloc")]
    #[test]
    fn test_summary_format() {
        let node = Node::Array(vec![Node::from(1), Node::from(2)]);
        let stats = DocumentStats::from_node(&node);

        let summary = stats.summary();
        assert!(summary.contains("Total nodes: 3"));
        assert!(summary.contains("Arrays: 1"));
        assert!(summary.contains("Numbers: 2"));
    }

    #[cfg(feature = "std")]
    #[test]
    fn test_timer_creation() {
        let timer = Timer::new("test");
        assert_eq!(timer.label, "test");
    }

    #[cfg(feature = "std")]
    #[test]
    fn test_timer_elapsed() {
        let timer = Timer::new("test");
        std::thread::sleep(std::time::Duration::from_millis(10));
        let elapsed = timer.elapsed();
        assert!(elapsed.as_millis() >= 10);
    }

    #[cfg(feature = "std")]
    #[test]
    fn test_timer_stop() {
        let timer = Timer::new("test");
        std::thread::sleep(std::time::Duration::from_millis(10));
        let duration = timer.stop();
        assert!(duration.as_millis() >= 10);
    }

    #[cfg(all(feature = "std", feature = "alloc"))]
    #[test]
    fn test_profiler_creation() {
        let profiler = Profiler::new();
        assert_eq!(profiler.measurements.len(), 0);
    }

    #[cfg(all(feature = "std", feature = "alloc"))]
    #[test]
    fn test_profiler_time() {
        let mut profiler = Profiler::new();

        let result = profiler.time("test_op", || {
            std::thread::sleep(std::time::Duration::from_millis(10));
            42
        });

        assert_eq!(result, 42);
        assert_eq!(profiler.measurements().len(), 1);
        assert_eq!(profiler.measurements()[0].0, "test_op");
        assert!(profiler.measurements()[0].1.as_millis() >= 10);
    }

    #[cfg(all(feature = "std", feature = "alloc"))]
    #[test]
    fn test_profiler_multiple_measurements() {
        let mut profiler = Profiler::new();

        profiler.time("op1", || {
            std::thread::sleep(std::time::Duration::from_millis(10))
        });
        profiler.time("op2", || {
            std::thread::sleep(std::time::Duration::from_millis(20))
        });

        assert_eq!(profiler.measurements().len(), 2);
        let total = profiler.total_time();
        assert!(total.as_millis() >= 30);
    }

    #[cfg(all(feature = "std", feature = "alloc"))]
    #[test]
    fn test_profiler_clear() {
        let mut profiler = Profiler::new();

        profiler.time("op", || {});
        assert_eq!(profiler.measurements().len(), 1);

        profiler.clear();
        assert_eq!(profiler.measurements().len(), 0);
    }
}