fast-yaml-core 0.5.2

Core YAML 1.2.2 parser and emitter
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
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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
//! Streaming YAML formatter that bypasses DOM construction.
//!
//! This module provides high-performance formatting for YAML documents
//! by processing parser events directly without building an intermediate
//! representation. This approach achieves O(1) memory complexity for
//! already-formatted files, compared to O(n) for DOM-based formatting.
//!
//! # Performance Characteristics
//!
//! - Small files (<1KB): Use DOM-based formatter (overhead not worth it)
//! - Large files (>1KB): Streaming provides 5-10x speedup
//! - Memory: Constant memory usage regardless of input size
//!
//! # Usage
//!
//! ```
//! # #[cfg(feature = "streaming")]
//! # {
//! use fast_yaml_core::streaming::{format_streaming, is_streaming_suitable};
//! use fast_yaml_core::EmitterConfig;
//!
//! let yaml = "key: value\nlist:\n  - item1\n  - item2\n";
//! let config = EmitterConfig::default();
//!
//! if is_streaming_suitable(yaml) {
//!     let formatted = format_streaming(yaml, &config).unwrap();
//!     println!("{formatted}");
//! }
//! # }
//! ```

mod formatter;
mod std_backend;
mod traits;

#[cfg(feature = "arena")]
mod arena_backend;

// Re-export public API
pub use std_backend::format_streaming;

#[cfg(feature = "arena")]
pub use arena_backend::format_streaming_arena;

/// Maximum allowed anchor ID to prevent memory exhaustion attacks.
/// 4096 anchors is more than sufficient for any legitimate YAML file.
const MAX_ANCHOR_ID: usize = 4096;

/// Maximum nesting depth to prevent stack/memory exhaustion.
/// 256 levels of nesting is far beyond any practical use case.
const MAX_DEPTH: usize = 256;

/// Static 64-space string for fast indent generation via slicing.
/// Avoids allocation for nesting depths up to 32 levels with 2-space indent.
static INDENT_SPACES: &str = "                                                                ";

/// Context for tracking the current position within YAML structure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Context {
    /// At the root level of a document
    Root,
    /// Inside a sequence (array)
    Sequence,
    /// Inside a mapping, expecting a key
    MappingKey,
    /// Inside a mapping, expecting a value
    MappingValue,
}

/// Fix special float value for YAML 1.2 compliance.
///
/// Converts saphyr's output format to YAML 1.2 compliant format:
/// - `inf` -> `.inf`
/// - `-inf` -> `-.inf`
/// - `NaN` -> `.nan`
fn fix_special_float_value(value: &str) -> &str {
    match value {
        "inf" => ".inf",
        "-inf" => "-.inf",
        "NaN" => ".nan",
        other => other,
    }
}

/// Check if input is suitable for streaming formatter.
///
/// Returns `true` for inputs that benefit from streaming:
/// - Large files (>1KB)
/// - Files without heavy anchor/alias usage
///
/// Returns `false` for:
/// - Small files (streaming overhead not worth it)
/// - Files with heavy anchor/alias usage (DOM better for resolution)
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "streaming")]
/// # {
/// use fast_yaml_core::streaming::is_streaming_suitable;
///
/// // Small files - use DOM
/// assert!(!is_streaming_suitable("small: yaml"));
///
/// // Large files - use streaming
/// let large = "key: value\n".repeat(1000);
/// assert!(is_streaming_suitable(&large));
/// # }
/// ```
pub fn is_streaming_suitable(input: &str) -> bool {
    // Small files are fast enough with DOM-based formatting
    if input.len() < 1024 {
        return false;
    }

    // Count indicators of complexity that benefit from DOM
    let anchor_count = input.bytes().filter(|&b| b == b'&').count();
    let alias_count = input.bytes().filter(|&b| b == b'*').count();

    // Heavy anchor/alias usage benefits from DOM for resolution
    // Threshold: more than 1 anchor/alias per 1000 bytes
    if anchor_count + alias_count > input.len() / 1000 {
        return false;
    }

    true
}

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

    #[test]
    fn test_format_streaming_simple_scalar() {
        let yaml = "test";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert!(result.contains("test"));
    }

    #[test]
    fn test_format_streaming_simple_mapping() {
        let yaml = "key: value";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert!(result.contains("key:"));
        assert!(result.contains("value"));
    }

    #[test]
    fn test_format_streaming_simple_sequence() {
        let yaml = "- item1\n- item2\n- item3";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert!(result.contains("- item1"));
        assert!(result.contains("- item2"));
        assert!(result.contains("- item3"));
    }

    #[test]
    fn test_format_streaming_nested_mapping() {
        let yaml = "outer:\n  inner: value";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert!(result.contains("outer:"));
        assert!(result.contains("inner:"));
        assert!(result.contains("value"));
    }

    #[test]
    fn test_format_streaming_mapping_with_sequence() {
        let yaml = "key:\n  - item1\n  - item2";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert!(result.contains("key:"));
        assert!(result.contains("item1"));
        assert!(result.contains("item2"));
    }

    #[test]
    fn test_format_streaming_with_explicit_start() {
        let yaml = "---\nkey: value";
        let config = EmitterConfig::new().with_explicit_start(true);
        let result = format_streaming(yaml, &config).unwrap();
        assert!(result.starts_with("---"));
    }

    #[test]
    fn test_format_streaming_quoted_strings() {
        let yaml = r#"single: 'quoted'
double: "quoted""#;
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert!(result.contains("single:"));
        assert!(result.contains("double:"));
    }

    #[test]
    fn test_format_streaming_special_floats() {
        let yaml = "pos_inf: inf\nneg_inf: -inf\nnan: NaN";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert!(result.contains(".inf"));
        assert!(result.contains("-.inf"));
        assert!(result.contains(".nan"));
    }

    #[test]
    fn test_format_streaming_with_anchor() {
        let yaml = "defaults: &defaults\n  key: value";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert!(result.contains('&'), "Should contain anchor marker");
    }

    #[test]
    fn test_format_streaming_with_alias() {
        let yaml = "defaults: &anchor1\n  key: value\nref: *anchor1";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert!(result.contains('&'), "Should contain anchor");
        assert!(result.contains('*'), "Should contain alias");
    }

    #[test]
    fn test_is_streaming_suitable_small() {
        assert!(!is_streaming_suitable("small: yaml"));
        assert!(!is_streaming_suitable("key: value\nlist:\n  - a\n  - b"));
    }

    #[test]
    fn test_is_streaming_suitable_large() {
        let large = "key: value\n".repeat(200); // ~2.2KB
        assert!(is_streaming_suitable(&large));
    }

    #[test]
    fn test_is_streaming_suitable_heavy_anchors() {
        use std::fmt::Write;
        let mut heavy_anchors = String::new();
        for i in 0..100 {
            writeln!(heavy_anchors, "key{i}: &anchor{i} value{i}").unwrap();
        }
        assert!(
            !is_streaming_suitable(&heavy_anchors),
            "Heavy anchor usage should not be suitable for streaming"
        );
    }

    #[test]
    fn test_fix_special_float_value() {
        assert_eq!(fix_special_float_value("inf"), ".inf");
        assert_eq!(fix_special_float_value("-inf"), "-.inf");
        assert_eq!(fix_special_float_value("NaN"), ".nan");
        assert_eq!(fix_special_float_value("123"), "123");
        assert_eq!(fix_special_float_value("normal"), "normal");
    }

    #[test]
    fn test_format_streaming_multiline_literal() {
        let yaml = "text: |\n  line1\n  line2";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert!(result.contains("text:"));
        assert!(result.contains("line1") && result.contains("line2"));
    }

    #[test]
    fn test_format_streaming_sequence_of_mappings() {
        let yaml = "- name: first\n  value: 1\n- name: second\n  value: 2";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert!(result.contains("name:"));
        assert!(result.contains("first"));
        assert!(result.contains("second"));
    }

    #[test]
    fn test_format_streaming_empty_input() {
        let yaml = "";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert!(result.is_empty() || result == "\n");
    }

    #[test]
    fn test_format_streaming_null_value() {
        let yaml = "key: null";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert!(result.contains("null") || result.contains('~'));
    }

    #[test]
    fn test_format_streaming_boolean_values() {
        let yaml = "yes: true\nno: false";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert!(result.contains("true"));
        assert!(result.contains("false"));
    }

    #[test]
    fn test_format_streaming_integer_values() {
        let yaml = "decimal: 123\nhex: 0x1A\noctal: 0o17";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert!(result.contains("123") || result.contains("0x") || result.contains("0o"));
    }

    #[test]
    fn test_format_streaming_double_quoted_escapes() {
        let yaml = r#"text: "line1\nline2""#;
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert!(result.contains("text:"));
    }

    #[test]
    fn test_format_streaming_large_input_preallocation() {
        let large_yaml = (0..100)
            .map(|i| format!("key{i}: value{i}"))
            .collect::<Vec<_>>()
            .join("\n");

        let config = EmitterConfig::default();
        let result = format_streaming(&large_yaml, &config).unwrap();

        assert!(result.contains("key0:"));
        assert!(result.contains("key99:"));
        assert!(result.contains("value50:") || result.contains("value50\n"));
    }

    #[test]
    fn test_format_streaming_deeply_nested() {
        let yaml = r"level1:
  level2:
    level3:
      level4:
        level5:
          key: deeply_nested_value";

        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();

        assert!(result.contains("deeply_nested_value"));
        assert!(result.contains("level5:"));
    }

    #[test]
    fn test_format_streaming_folded_style() {
        let yaml = "text: >-\n  folded\n  block\n  scalar";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert!(result.contains("text:"));
    }

    #[test]
    fn test_format_streaming_many_anchors() {
        let yaml = r"anchor1: &a1 value1
anchor2: &a2 value2
anchor3: &a3 value3
ref1: *a1
ref2: *a2
ref3: *a3";

        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();

        assert!(result.contains('&'), "Should preserve anchors");
        assert!(result.contains('*'), "Should preserve aliases");
    }

    #[test]
    fn test_streaming_context_stack_depth() {
        use std::fmt::Write;

        let mut yaml = String::new();
        for i in 0..20 {
            let indent = "  ".repeat(i);
            writeln!(yaml, "{indent}level{i}:").unwrap();
        }
        let indent = "  ".repeat(20);
        writeln!(yaml, "{indent}value: deep").unwrap();

        let config = EmitterConfig::default();
        let result = format_streaming(&yaml, &config).unwrap();

        assert!(result.contains("value:"));
        assert!(result.contains("level19:"));
    }
}

#[cfg(all(test, feature = "arena"))]
mod arena_tests {
    use super::*;
    use crate::EmitterConfig;

    #[test]
    fn test_arena_vs_standard_output_equivalence() {
        let test_cases = vec![
            "key: value",
            "- item1\n- item2",
            "outer:\n  inner: value",
            "defaults: &anchor1\n  key: value\nref: *anchor1",
            "pos_inf: inf\nneg_inf: -inf\nnan: NaN",
        ];

        let config = EmitterConfig::default();

        for yaml in test_cases {
            let standard = format_streaming(yaml, &config).unwrap();
            let arena = format_streaming_arena(yaml, &config).unwrap();
            assert_eq!(
                standard, arena,
                "Arena and standard should produce identical output for: {yaml}"
            );
        }
    }

    #[test]
    fn test_arena_deeply_nested_32_levels() {
        use std::fmt::Write;

        let mut yaml = String::new();
        for i in 0..32 {
            let indent = "  ".repeat(i);
            writeln!(yaml, "{indent}level{i}:").unwrap();
        }
        let indent = "  ".repeat(32);
        writeln!(yaml, "{indent}value: at_depth_32").unwrap();

        let config = EmitterConfig::default();
        let standard = format_streaming(&yaml, &config).unwrap();
        let arena = format_streaming_arena(&yaml, &config).unwrap();

        assert_eq!(
            standard, arena,
            "32-level nesting: arena and standard must match"
        );
        assert!(arena.contains("at_depth_32"));
    }

    #[test]
    fn test_arena_deeply_nested_64_levels() {
        use std::fmt::Write;

        let mut yaml = String::new();
        for i in 0..64 {
            let indent = "  ".repeat(i);
            writeln!(yaml, "{indent}level{i}:").unwrap();
        }
        let indent = "  ".repeat(64);
        writeln!(yaml, "{indent}value: at_depth_64").unwrap();

        let config = EmitterConfig::default();
        let standard = format_streaming(&yaml, &config).unwrap();
        let arena = format_streaming_arena(&yaml, &config).unwrap();

        assert_eq!(
            standard, arena,
            "64-level nesting: arena and standard must match"
        );
        assert!(arena.contains("at_depth_64"));
    }

    #[test]
    fn test_arena_many_anchors_100() {
        use std::fmt::Write;

        let mut yaml = String::new();
        for i in 1..=100 {
            writeln!(yaml, "key{i}: &anchor{i} value{i}").unwrap();
        }
        for i in 1..=100 {
            writeln!(yaml, "ref{i}: *anchor{i}").unwrap();
        }

        let config = EmitterConfig::default();
        let standard = format_streaming(&yaml, &config).unwrap();
        let arena = format_streaming_arena(&yaml, &config).unwrap();

        assert_eq!(
            standard, arena,
            "100 anchors: arena and standard must match"
        );
        assert!(arena.contains("anchor100"));
    }

    #[test]
    fn test_arena_many_anchors_500() {
        use std::fmt::Write;

        let mut yaml = String::new();
        for i in 1..=500 {
            writeln!(yaml, "key{i}: &anchor{i} value{i}").unwrap();
        }
        for i in 1..=500 {
            writeln!(yaml, "ref{i}: *anchor{i}").unwrap();
        }

        let config = EmitterConfig::default();
        let standard = format_streaming(&yaml, &config).unwrap();
        let arena = format_streaming_arena(&yaml, &config).unwrap();

        assert_eq!(
            standard, arena,
            "500 anchors: arena and standard must match"
        );
        assert!(arena.contains("anchor500"));
    }

    #[test]
    fn test_arena_large_document_1mb() {
        use std::fmt::Write;

        let mut yaml = String::new();
        let entry = "key: a_moderately_long_value_that_pads_out_the_line\n";
        let entries_needed = (1024 * 1024) / entry.len() + 1;

        for i in 0..entries_needed {
            writeln!(
                yaml,
                "key{i}: a_moderately_long_value_that_pads_out_the_line"
            )
            .unwrap();
        }

        assert!(yaml.len() >= 1024 * 1024, "Test YAML should be >= 1MB");

        let config = EmitterConfig::default();
        let standard = format_streaming(&yaml, &config).unwrap();
        let arena = format_streaming_arena(&yaml, &config).unwrap();

        assert_eq!(
            standard, arena,
            "1MB document: arena and standard must match"
        );
    }

    #[test]
    fn test_arena_large_document_2mb() {
        use std::fmt::Write;

        let mut yaml = String::new();
        let entry = "key0: a_moderately_long_value_that_pads_out_the_line\n";
        let entries_needed = (2 * 1024 * 1024) / entry.len() + 1;

        for i in 0..entries_needed {
            writeln!(
                yaml,
                "key{i}: a_moderately_long_value_that_pads_out_the_line"
            )
            .unwrap();
        }

        assert!(
            yaml.len() >= 2 * 1024 * 1024,
            "Test YAML should be >= 2MB, got {} bytes",
            yaml.len()
        );

        let config = EmitterConfig::default();
        let standard = format_streaming(&yaml, &config).unwrap();
        let arena = format_streaming_arena(&yaml, &config).unwrap();

        assert_eq!(
            standard, arena,
            "2MB document: arena and standard must match"
        );
    }

    #[test]
    fn test_arena_output_equivalence_comprehensive() {
        let test_cases = vec![
            ("empty", ""),
            ("simple_scalar", "test"),
            ("simple_mapping", "key: value"),
            ("simple_sequence", "- item1\n- item2\n- item3"),
            ("nested_mapping", "outer:\n  inner:\n    deep: value"),
            ("mapping_with_sequence", "key:\n  - item1\n  - item2"),
            (
                "sequence_of_mappings",
                "- name: first\n  value: 1\n- name: second\n  value: 2",
            ),
            ("with_anchor", "defaults: &defaults\n  key: value"),
            (
                "with_anchor_alias",
                "defaults: &anchor1\n  key: value\nref: *anchor1",
            ),
            ("special_floats", "pos_inf: inf\nneg_inf: -inf\nnan: NaN"),
            ("single_quoted", "key: 'single quoted'"),
            ("double_quoted", "key: \"double quoted\""),
            ("literal_block", "text: |\n  line1\n  line2"),
            ("folded_block", "text: >-\n  folded\n  block"),
            ("explicit_start", "---\nkey: value"),
            ("null_value", "key: null"),
            ("boolean_values", "yes: true\nno: false"),
            ("integer_values", "decimal: 123\nhex: 0x1A"),
        ];

        let config = EmitterConfig::default();

        for (name, yaml) in test_cases {
            let standard = format_streaming(yaml, &config).unwrap();
            let arena = format_streaming_arena(yaml, &config).unwrap();
            assert_eq!(
                standard, arena,
                "Output equivalence failed for test case: {name}"
            );
        }
    }

    #[test]
    fn test_arena_repeated_processing_memory_stability() {
        let yaml = "key: value\nlist:\n  - item1\n  - item2\n  - item3";
        let config = EmitterConfig::default();

        for i in 0..1000 {
            let result = format_streaming_arena(yaml, &config).unwrap();
            assert!(
                result.contains("key:"),
                "Iteration {i}: output should contain key"
            );
        }
    }

    #[test]
    fn test_arena_complex_mixed_structure() {
        let yaml = r"
metadata:
  name: complex
  version: 1.0
  tags:
    - production
    - stable
config:
  database:
    host: localhost
    port: 5432
    credentials: &db_creds
      user: admin
      pass: secret
  cache:
    host: redis
    port: 6379
    credentials: *db_creds
items:
  - id: 1
    name: first
    data:
      nested:
        deep:
          value: found
  - id: 2
    name: second
    data:
      nested:
        deep:
          value: also_found
";

        let config = EmitterConfig::default();
        let standard = format_streaming(yaml, &config).unwrap();
        let arena = format_streaming_arena(yaml, &config).unwrap();

        assert_eq!(
            standard, arena,
            "Complex mixed structure: arena and standard must match"
        );
    }
}