fast-yaml-core 0.5.3

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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
//! 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;
///
/// // Regular files - use streaming (preserves float types)
/// assert!(is_streaming_suitable("version: 1.0"));
/// assert!(is_streaming_suitable("small: yaml"));
///
/// // Large files - also use streaming
/// let large = "key: value\n".repeat(1000);
/// assert!(is_streaming_suitable(&large));
/// # }
/// ```
pub fn is_streaming_suitable(input: &str) -> bool {
    // Streaming preserves the original scalar text (e.g. "1.0" stays "1.0"),
    // while DOM-based formatting loses type information (float 1.0 → integer 1).
    // Always prefer streaming to maintain YAML 1.2.2 Core Schema type fidelity.

    // Heavy anchor/alias usage: avoid streaming only when anchor density is very
    // high, because the DOM path resolves aliases during parse.
    let len = input.len();
    if len > 0 {
        let anchor_count = input.bytes().filter(|&b| b == b'&').count();
        let alias_count = input.bytes().filter(|&b| b == b'*').count();

        // More than 10 anchors/aliases per 1000 bytes → fall back to DOM
        if (anchor_count + alias_count) * 100 > len {
            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() {
        // Small files now use streaming to preserve float types (issue #66)
        assert!(is_streaming_suitable("small: yaml"));
        assert!(is_streaming_suitable("key: value\nlist:\n  - a\n  - b"));
        assert!(is_streaming_suitable("version: 1.0"));
        assert!(is_streaming_suitable("count: 1.23e10"));
    }

    #[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_format_streaming_float_type_preservation() {
        // Regression tests for issue #66: float values must not be converted to integers
        let config = EmitterConfig::default();

        // 1.0 must remain 1.0, not become 1
        let result = format_streaming("version: 1.0", &config).unwrap();
        assert!(
            result.contains("1.0"),
            "1.0 must stay as float, got: {result}"
        );
        assert!(
            !result.contains(": 1\n"),
            "1.0 must not be emitted as integer 1, got: {result}"
        );

        // Scientific notation must be preserved, not expanded to integer
        let result = format_streaming("count: 1.23e10", &config).unwrap();
        assert!(
            result.contains("1.23e10") || result.contains("1.23e+10"),
            "Scientific notation must be preserved, got: {result}"
        );
        assert!(
            !result.contains("12300000000"),
            "Scientific notation must not expand to integer, got: {result}"
        );

        // Regular float (3.14) must be preserved as-is
        let result = format_streaming("pi: 3.14", &config).unwrap();
        assert!(
            result.contains("3.14"),
            "3.14 must be preserved, got: {result}"
        );
    }

    #[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");
    }

    // ── Issue #76: Block scalar chomp indicator ─────────────────────────────

    #[test]
    fn test_format_streaming_block_scalar_clip_chomp() {
        // Clip (|) — value ends with exactly one newline
        let yaml = "desc: |\n  line one\n  line two\n";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert!(
            result.contains("desc: |\n"),
            "clip chomp '|' must be preserved, got: {result}"
        );
        assert!(
            !result.contains("|-"),
            "clip chomp must not become strip '|-', got: {result}"
        );
    }

    #[test]
    fn test_format_streaming_block_scalar_strip_chomp() {
        // Strip (|-) — value does not end with a newline
        let yaml = "desc: |-\n  line one\n  line two\n";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert!(
            result.contains("|-"),
            "strip chomp '|-' must be preserved, got: {result}"
        );
    }

    #[test]
    fn test_format_streaming_block_scalar_keep_chomp() {
        // Keep (|+) — value ends with two or more newlines
        let yaml = "desc: |+\n  line one\n  line two\n\n";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert!(
            result.contains("|+"),
            "keep chomp '|+' must be preserved, got: {result}"
        );
    }

    #[test]
    fn test_format_streaming_block_scalar_keep_chomp_multiple_trailing() {
        // Keep (|+) with multiple trailing blank lines
        let yaml = "desc: |+\n  line one\n  line two\n\n\n";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert!(
            result.contains("|+"),
            "keep chomp '|+' must be preserved, got: {result}"
        );
        // The formatted output must end with at least two blank lines after content
        assert!(
            result.contains("  line two\n\n"),
            "multiple trailing blank lines must be preserved, got: {result}"
        );
    }

    #[test]
    fn test_format_streaming_block_scalar_empty_line_no_indent() {
        // Empty lines in block scalars must not get trailing whitespace
        let yaml = "desc: |\n  line one\n\n  line two\n";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        // The empty line must be a bare newline, not "  \n"
        assert!(
            !result.contains("  \n"),
            "empty lines in block scalars must not have trailing spaces, got: {result}"
        );
        assert!(
            result.contains("line one\n\n"),
            "empty line between content lines must be preserved as bare newline, got: {result}"
        );
    }

    // ── Issue #83: Sequence-of-sequences ────────────────────────────────────

    #[test]
    fn test_format_streaming_sequence_of_sequences() {
        let yaml = "- - name\n  - hr\n  - avg\n";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert_eq!(
            result, "- - name\n  - hr\n  - avg\n",
            "sequence-of-sequences must not produce extra spaces, got: {result}"
        );
    }

    #[test]
    fn test_format_streaming_sequence_of_sequences_from_flow() {
        // Flow sequence converts to block: inner items must align correctly
        let yaml = "- [name, hr, avg]\n";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert_eq!(
            result, "- - name\n  - hr\n  - avg\n",
            "flow-to-block sequence-of-sequences must produce correct indentation, got: {result}"
        );
    }

    #[test]
    fn test_format_streaming_triple_nested_sequence() {
        let yaml = "- - - deep\n";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert_eq!(
            result, "- - - deep\n",
            "triple-nested sequence must format correctly, got: {result}"
        );
    }

    #[test]
    fn test_format_streaming_sequence_first_item_mapping() {
        // Mapping as first item of a nested sequence
        let yaml = "- - key: val\n";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert_eq!(
            result, "- - key: val\n",
            "mapping as first item after dash must not double-indent, got: {result}"
        );
    }

    // ── Issue #84: Anchors on correct line ───────────────────────────────────

    #[test]
    fn test_format_streaming_anchor_on_mapping_value() {
        // Anchor on mapping value: "key: &anchor1\n  subkey: val"
        let yaml = "defaults: &base\n  adapter: postgres\n";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert!(
            result.contains("defaults: &anchor1\n"),
            "anchor must appear inline on same line as key, got: {result}"
        );
        assert!(
            result.contains("  adapter: postgres\n"),
            "sub-key must be indented on next line, got: {result}"
        );
    }

    #[test]
    fn test_format_streaming_anchor_on_sequence_value() {
        // Anchor on sequence value: "tags: &anchor1\n  - yaml"
        let yaml = "tags: &common\n  - yaml\n  - parser\n";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert!(
            result.contains("tags: &anchor1\n"),
            "anchor must appear inline on same line as key, got: {result}"
        );
    }

    #[test]
    fn test_format_streaming_anchor_mapping_in_sequence() {
        // Anchored mapping inside a sequence: "- &anchor1\n  key: val"
        // The key must be indented (not at column 0).
        let yaml = "- &ref\n  key: val\n";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert_eq!(
            result, "- &anchor1\n  key: val\n",
            "anchored mapping in sequence: anchor inline, key indented, got: {result}"
        );
    }

    #[test]
    fn test_format_streaming_anchor_sequence_in_sequence() {
        // Anchored sequence inside a sequence: "- &anchor1\n  - item"
        let yaml = "- &ref\n  - item\n";
        let config = EmitterConfig::default();
        let result = format_streaming(yaml, &config).unwrap();
        assert_eq!(
            result, "- &anchor1\n  - item\n",
            "anchored sequence in sequence: anchor inline, item indented, got: {result}"
        );
    }

    #[test]
    fn test_format_streaming_anchor_idempotency() {
        // format(format(input)) == format(input) for anchored documents
        let yaml = "defaults: &base\n  adapter: postgres\ndev:\n  <<: *base\n  debug: true\n";
        let config = EmitterConfig::default();
        let first = format_streaming(yaml, &config).unwrap();
        let second = format_streaming(&first, &config).unwrap();
        assert_eq!(
            first, second,
            "formatting must be idempotent for anchored documents"
        );
    }

    #[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"
        );
    }
}