ktav 0.7.0

Ktav — a plain configuration format. Three rules, zero indentation, zero quoting. Serde-native.
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
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
//! Canonical writer — emits a deterministic byte sequence for any [`Value`]
//! per spec § 5.9.
//!
//! The canonical form is:
//! - LF-only line endings (no `CR`).
//! - 4-space indent per nesting level.
//! - Trailing `LF` at end of document (empty Object root → zero bytes).
//! - No comments.
//! - No inline compounds (except empty `{}` / `[]`).
//! - Numbers in canonical form (Integer: base-10; Float: shortest decimal).
//! - Multi-line strings prefer verbatim `((…))`.
//!
//! A non-representable Value — a scalar root, an empty key name, a
//! non-finite Float, a `CR` byte, or one of the three multi-line
//! collision cases — is rejected per § 5.9.0 with a
//! [`crate::error::ReasonCode`]-coded `Error::Unrepresentable` before
//! any bytes are emitted; partial output followed by failure never
//! happens.
//!
//! Two writer-conforming implementations fed the same Value MUST produce
//! identical output (§ 8.2).

use crate::error::{Error, Result};
use crate::value::{ObjectMap, Value};

// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------

/// Emit a canonical Ktav serialisation of `value` (spec § 5.9).
///
/// The top-level value must be an Object or an Array (§ 5.0.1).
/// Non-representable Values are rejected per § 5.9.0 with an
/// `Error::Unrepresentable` carrying a [`crate::error::ReasonCode`] —
/// scalar roots, empty key names, non-finite floats, `CR` bytes, and
/// the three multi-line collision cases. The check runs before any
/// bytes are emitted, so a rejection produces no partial output.
pub fn emit_canonical(value: &Value) -> Result<String> {
    super::representable::check_representable(value)?;
    let mut out = String::with_capacity(estimate_size(value));
    match value {
        Value::Object(o) => emit_object_pairs(o, 0, true, &mut out)?,
        Value::Array(items) if items.is_empty() => {
            // § 5.9.3: empty Array root → `[]\n`
            out.push_str("[]\n");
        }
        Value::Array(items) => emit_array_root(items, &mut out)?,
        _ => return Err(Error::Unrepresentable(crate::error::ReasonCode::ScalarRoot)),
    }
    Ok(out)
}

// ---------------------------------------------------------------------------
// § 5.9.3 Root-level emission
// ---------------------------------------------------------------------------

/// Emit an Object's pairs at the given indent level (root uses 0).
///
/// `is_root` is true ONLY for the document-root Object; it lets the
/// first pair's key take the § 5.9.10 rule (c) U+FEFF guard (which
/// only applies at byte offset 0, § 5.9.12). Every nested call passes
/// `false` — an interior Object's first key never lands at offset 0.
fn emit_object_pairs(
    obj: &ObjectMap,
    indent: usize,
    is_root: bool,
    out: &mut String,
) -> Result<()> {
    for (index, (k, v)) in obj.iter().enumerate() {
        emit_pair(k, v, indent, is_root && index == 0, out)?;
    }
    Ok(())
}

/// Emit a root-level Array. Items are bare at indent 0 unless the first
/// item is itself a non-empty compound (§ 5.9.3 lone-`{`/`[` wrap).
fn emit_array_root(items: &[Value], out: &mut String) -> Result<()> {
    let needs_wrap = !items.is_empty() && crate::render::helpers::first_item_needs_wrap(&items[0]);
    if needs_wrap {
        // The wrapped branch's first content line is `[` itself, so no
        // item line is ever read as the root's first line — no item is
        // exposed to root-kind detection here (§ 5.9.6 / § 5.9.3).
        out.push_str("[\n");
        for item in items {
            emit_array_item(item, 1, false, out)?;
        }
        out.push_str("]\n");
    } else {
        for (index, item) in items.iter().enumerate() {
            // § 5.9.6 / § 5.9.12: only index 0 of the unwrapped root
            // Array is exposed to root-kind detection.
            emit_array_item(item, 0, index == 0, out)?;
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// § 5.9.5 Pair emission
// ---------------------------------------------------------------------------

/// Emit a single `key: value` / `key:: value` / compound pair.
///
/// `root_first_key` forwards the § 5.9.10 rule (c) guard for the
/// root Object's first-serialized key.
fn emit_pair(
    key: &str,
    value: &Value,
    indent: usize,
    root_first_key: bool,
    out: &mut String,
) -> Result<()> {
    push_indent(out, indent);
    // Spec 0.7 § 5.9.10 — bare/quoted form selection + re-escape.
    crate::render::helpers::push_escaped_key_segment(key, root_first_key, out);
    match value {
        Value::Null => {
            // § 5.9.9
            out.push_str(": null\n");
        }
        Value::Bool(b) => {
            out.push_str(": ");
            out.push_str(if *b { "true" } else { "false" });
            out.push('\n');
        }
        Value::Integer(s) => {
            // § 5.9.8: canonical base-10 decimal. Always a valid integer
            // literal — no raw marker needed.
            out.push_str(": ");
            out.push_str(s);
            out.push('\n');
        }
        Value::Float(s) => {
            // § 5.9.8: canonical float form — scientific for large/small abs.
            out.push_str(": ");
            out.push_str(&canonical_float(s));
            out.push('\n');
        }
        Value::String(s) => {
            emit_string_in_pair(s, indent, out)?;
        }
        Value::Array(items) => {
            if items.is_empty() {
                out.push_str(": []\n");
            } else {
                out.push_str(": [\n");
                for item in items {
                    emit_array_item(item, indent + 1, false, out)?;
                }
                push_indent(out, indent);
                out.push_str("]\n");
            }
        }
        Value::Object(obj) => {
            if obj.is_empty() {
                out.push_str(": {}\n");
            } else {
                out.push_str(": {\n");
                emit_object_pairs(obj, indent + 1, false, out)?;
                push_indent(out, indent);
                out.push_str("}\n");
            }
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// § 5.9.6 Array-item emission
// ---------------------------------------------------------------------------

/// Emit one array item at the given indent level.
///
/// `is_root_array_first` is TRUE only for index 0 of an unwrapped
/// Array root — the sole item position whose body is exposed to
/// § 5.0.1's root-kind detection, and therefore the sole position to
/// which § 5.9.6's first-item safeguard applies.
fn emit_array_item(
    value: &Value,
    indent: usize,
    is_root_array_first: bool,
    out: &mut String,
) -> Result<()> {
    push_indent(out, indent);
    match value {
        Value::Null => {
            out.push_str("null\n");
        }
        Value::Bool(b) => {
            out.push_str(if *b { "true" } else { "false" });
            out.push('\n');
        }
        Value::Integer(s) => {
            out.push_str(s);
            out.push('\n');
        }
        Value::Float(s) => {
            out.push_str(&canonical_float(s));
            out.push('\n');
        }
        Value::String(s) => {
            emit_string_as_item(s, indent, is_root_array_first, out)?;
        }
        Value::Array(items) => {
            if items.is_empty() {
                out.push_str("[]\n");
            } else {
                out.push_str("[\n");
                for item in items {
                    // Nested items are never root-detected (§ 5.9.6).
                    emit_array_item(item, indent + 1, false, out)?;
                }
                push_indent(out, indent);
                out.push_str("]\n");
            }
        }
        Value::Object(obj) => {
            if obj.is_empty() {
                out.push_str("{}\n");
            } else {
                out.push_str("{\n");
                emit_object_pairs(obj, indent + 1, false, out)?;
                push_indent(out, indent);
                out.push_str("}\n");
            }
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// § 5.9.7 String form selection — pair context
// ---------------------------------------------------------------------------

/// Emit a String value inside a pair. Chooses between:
/// - `key:` (empty string, no body)
/// - `key: body` (one-line plain)
/// - `key:: body` (one-line raw — would reclassify)
/// - `key: ((\n...\n))` (verbatim multi-line)
/// - `key: (\n...\n)` (stripped multi-line, fallback)
fn emit_string_in_pair(s: &str, indent: usize, out: &mut String) -> Result<()> {
    if s.is_empty() {
        // § 5.9.7: empty String → `key:` with no body.
        out.push_str(":\n");
        return Ok(());
    }

    if s.contains('\r') {
        // § 5.9.7: CR byte not representable in canonical form.
        return Err(crate::render::helpers::cr_error());
    }

    if crate::render::helpers::string_needs_multiline(s) {
        // Multi-line string — also the § 5.9.7 form for bodies with
        // leading/trailing whitespace or control bytes, which the
        // parser would trim (or the spec routes to verbatim) on a
        // one-line value.
        return emit_multiline_string(s, indent, true, out);
    }

    // One-line string. Check if it needs the raw marker.
    if needs_raw_marker(s) {
        out.push_str(":: ");
        out.push_str(s);
        out.push('\n');
    } else {
        out.push_str(": ");
        out.push_str(s);
        out.push('\n');
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// § 5.9.7 String form selection — array-item context
// ---------------------------------------------------------------------------

/// Emit a String value as an array item. Chooses between:
/// - `::` (empty string, no body)
/// - bare `body` (one-line plain)
/// - `:: body` (one-line raw — would reclassify)
/// - `((\n...\n))` (verbatim multi-line)
/// - `(\n...\n)` (stripped multi-line, fallback)
fn emit_string_as_item(
    s: &str,
    indent: usize,
    is_root_array_first: bool,
    out: &mut String,
) -> Result<()> {
    if s.is_empty() {
        // § 5.9.7: empty String item → `::` with no body.
        // Wait — looking at fixtures, canonical `empty_stripped.canonical.ktav`
        // shows `note:\n` for an empty string in a pair, and for array items
        // the canonical form is `::`. But actually let's re-check § 5.9.6:
        // "Bare scalar item: <bytes> on its own line" — empty string can't be
        // a bare scalar (it would be a blank line). Use `::`.
        out.push_str("::\n");
        return Ok(());
    }

    if s.contains('\r') {
        return Err(crate::render::helpers::cr_error());
    }

    if crate::render::helpers::string_needs_multiline(s) {
        return emit_multiline_string(s, indent, false, out);
    }

    // One-line string. Check if it needs the raw marker — the item
    // form has extra collisions (`##`, `::`, sole `]` / `}`).
    //
    // § 5.9.6 / § 5.9.12: when this is the FIRST item of an Array
    // root, the bare form is additionally not used if the body
    // satisfies § 5.0.1 rule 6's phase-1 pair-candidate test (it
    // would otherwise be re-read as the root Object's first pair), OR
    // — independently of the pair-candidate test — the body begins
    // with U+FEFF (bare form would place it at byte offset 0, where
    // § 3.1 makes readers strip it as a metadata BOM). Both exclusions
    // sit after the empty (`::`) and multi-line branches: § 5.9.12
    // scopes them to bodies whose canonical form would otherwise be
    // the bare one-line form (multi-line bodies put `((` at byte 0;
    // empty bodies emit `::`).
    if crate::render::helpers::item_needs_raw_marker(s)
        || (is_root_array_first
            && (crate::render::helpers::bare_item_is_pair_candidate(s)
                || s.starts_with('\u{FEFF}')))
    {
        out.push_str(":: ");
        out.push_str(s);
        out.push('\n');
    } else {
        out.push_str(s);
        out.push('\n');
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// § 5.9.7 Multi-line string emission (shared for pair + item)
// ---------------------------------------------------------------------------

/// Emit a multi-line string in canonical form.
///
/// Prefers verbatim `((…))` (§ 5.9.7). Falls back to stripped `(…)` when
/// a content line is exactly `))`, and errors when neither form can
/// hold the body losslessly (§ 5.6.1) — see `choose_multiline_form`.
///
/// `is_pair`: if true, we need `key: ((` prefix; if false, just `((`.
/// For the item case, `indent` is where `((` goes, and body is at indent 0.
fn emit_multiline_string(s: &str, indent: usize, is_pair: bool, out: &mut String) -> Result<()> {
    // § 5.9.7: prefer verbatim; fall back to stripped only when a `))`
    // content line makes verbatim impossible, and error when neither
    // form can hold the body losslessly.
    match crate::render::helpers::choose_multiline_form(s, false)? {
        crate::render::helpers::MultilineForm::Verbatim => {
            emit_multiline_verbatim(s, indent, is_pair, out);
        }
        crate::render::helpers::MultilineForm::Stripped => {
            emit_multiline_stripped(s, indent, is_pair, out);
        }
    }
    Ok(())
}

/// Verbatim multi-line `((…))`. Body lines at indent 0 (§ 5.9.6).
fn emit_multiline_verbatim(s: &str, indent: usize, is_pair: bool, out: &mut String) {
    if is_pair {
        out.push_str(": ((\n");
    } else {
        out.push_str("((\n");
    }
    // Body at indent 0 (verbatim preserves bytes exactly).
    out.push_str(s);
    out.push('\n');
    push_indent(out, indent);
    out.push_str("))\n");
}

/// Stripped multi-line `(…)` fallback. Body lines at indent 0
/// so the common-indent computation yields 0.
fn emit_multiline_stripped(s: &str, indent: usize, is_pair: bool, out: &mut String) {
    if is_pair {
        out.push_str(": (\n");
    } else {
        out.push_str("(\n");
    }
    // Body at indent 0, lines kept byte-for-byte: an unindented
    // line pins the parser's common-indent dedent to zero (the
    // form chooser guarantees one exists), so per-line leading
    // whitespace survives the round-trip.
    out.push_str(s);
    out.push('\n');
    push_indent(out, indent);
    out.push_str(")\n");
}

// ---------------------------------------------------------------------------
// § 5.9.8 Float canonical form
// ---------------------------------------------------------------------------

/// Convert a stored float scalar (ryu shortest-decimal) to the spec § 5.9.8
/// canonical form:
/// - Use scientific notation when `abs(value) >= 1e7` or
///   `0 < abs(value) < 1e-2`.
/// - Otherwise keep the ryu decimal form unchanged.
/// - Scientific: lowercase `e`, no `+` in exponent, strip trailing `.0`
///   in mantissa (so `1.0e9` → `1e9`).
///
/// Returns [`std::borrow::Cow::Borrowed`] whenever the stored form is already canonical
/// text (zero / decimal region / passthrough); only the scientific branch
/// allocates. Thresholds, sign of zero, the shortest-roundtrip guarantee,
/// and the LossyScalar payload are unchanged.
pub(crate) fn canonical_float(s: &str) -> std::borrow::Cow<'_, str> {
    // Parse the stored ryu string back to f64.
    let val: f64 = match s.parse() {
        Ok(v) => v,
        Err(_) => return std::borrow::Cow::Borrowed(s), // shouldn't happen; pass through
    };

    if val == 0.0 {
        // Positive/negative zero in ryu is "0.0" or "-0.0"; keep as-is.
        return std::borrow::Cow::Borrowed(s);
    }

    let abs = val.abs();

    if !(1e-2..1e7).contains(&abs) {
        // Build scientific form.
        // Use Rust's {:e} formatter then normalise.
        let raw = format!("{:e}", val); // e.g. "1e9", "1.5e9", "-2.5e-10"
        std::borrow::Cow::Owned(normalise_scientific(&raw))
    } else {
        // Decimal region: ryu's output is already correct.
        std::borrow::Cow::Borrowed(s)
    }
}

/// Normalise Rust's `{:e}` scientific output to the spec form:
/// - lowercase `e` (already lowercase from `{:e}`)
/// - no `+` sign in the exponent
/// - strip trailing `.0` in the mantissa  (`1.0e9` → `1e9`)
/// - strip trailing zeros after decimal point in mantissa (`1.50e9` → `1.5e9`)
fn normalise_scientific(raw: &str) -> String {
    // Rust {:e} format: "<mantissa>e<exp>" where exp may be negative.
    // Example: "1e9", "1.5e9", "-2.5e-10", "1.5e-3".
    let e_pos = raw.find('e').unwrap_or(raw.len());
    let mantissa = &raw[..e_pos];
    let exp_part = &raw[e_pos + 1..]; // e.g. "9", "-10", "3"

    // Strip trailing zeros and unnecessary decimal point from mantissa.
    let mantissa = if mantissa.contains('.') {
        let trimmed = mantissa.trim_end_matches('0');
        trimmed.trim_end_matches('.')
    } else {
        mantissa
    };

    // Remove leading '+' from exponent (Rust never emits one, but be safe).
    let exp_str = exp_part.trim_start_matches('+');

    format!("{}e{}", mantissa, exp_str)
}

// ---------------------------------------------------------------------------
// § 5.9.5 / 5.9.6 / 5.9.7 — Would the parser re-classify this body?
// ---------------------------------------------------------------------------

/// Returns `true` if `body` would be classified by § 5.2 as something
/// other than a String (number, keyword, compound opener, or multi-line
/// opener). In that case the canonical writer must use the `::` raw
/// marker so the parser reads it back as a String.
///
/// Delegates to the shared `render::helpers` implementation, which
/// also covers a body starting with `(` (§ 5.2 would open a
/// multi-line block or reject it as an inline paren compound).
fn needs_raw_marker(body: &str) -> bool {
    crate::render::helpers::needs_raw_marker(body)
}

// Number grammar matching now delegated to crate::parser::classify
// (matches_integer_grammar / matches_float_grammar).

// ---------------------------------------------------------------------------
// Indent helper
// ---------------------------------------------------------------------------

const INDENT: &str = "    ";

/// Push `level * 4` spaces into `out`.
fn push_indent(out: &mut String, level: usize) {
    const SPACES: &str = "                                                                "; // 64
    let mut remaining = level * INDENT.len();
    if remaining == 0 {
        return;
    }
    out.reserve(remaining);
    while remaining > 0 {
        let chunk = remaining.min(SPACES.len());
        out.push_str(&SPACES[..chunk]);
        remaining -= chunk;
    }
}

// ---------------------------------------------------------------------------
// Size estimate
// ---------------------------------------------------------------------------

fn estimate_size(value: &Value) -> usize {
    match value {
        Value::Null => 5,
        Value::Bool(_) => 6,
        Value::Integer(s) | Value::Float(s) | Value::String(s) => s.len() + 8,
        Value::Array(items) => 4 + items.iter().map(estimate_size).sum::<usize>(),
        Value::Object(obj) => obj
            .iter()
            .map(|(k, v)| k.len() + 4 + estimate_size(v))
            .sum::<usize>()
            .saturating_add(4),
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::value::ObjectMap;
    use compact_str::CompactString;
    use indexmap::IndexMap;
    use rustc_hash::FxBuildHasher;

    fn obj(pairs: Vec<(&str, Value)>) -> Value {
        let mut map: ObjectMap = IndexMap::with_capacity_and_hasher(pairs.len(), FxBuildHasher);
        for (k, v) in pairs {
            map.insert(CompactString::new(k), v);
        }
        Value::Object(map)
    }

    fn arr(items: Vec<Value>) -> Value {
        Value::Array(items)
    }

    fn int(n: i64) -> Value {
        let mut buf = itoa::Buffer::new();
        Value::Integer(CompactString::new(buf.format(n)))
    }

    fn float(f: f64) -> Value {
        let mut buf = ryu::Buffer::new();
        Value::Float(CompactString::new(buf.format(f)))
    }

    fn s(text: &str) -> Value {
        Value::String(CompactString::new(text))
    }

    #[test]
    fn empty_object_root_produces_zero_bytes() {
        let v = obj(vec![]);
        assert_eq!(emit_canonical(&v).unwrap(), "");
    }

    #[test]
    fn empty_array_root_produces_brackets() {
        let v = arr(vec![]);
        assert_eq!(emit_canonical(&v).unwrap(), "[]\n");
    }

    #[test]
    fn simple_pairs() {
        let v = obj(vec![
            ("host", s("localhost")),
            ("port", int(8080)),
            ("debug", Value::Bool(true)),
        ]);
        let out = emit_canonical(&v).unwrap();
        assert_eq!(out, "host: localhost\nport: 8080\ndebug: true\n");
    }

    #[test]
    fn null_and_false_keywords() {
        let v = obj(vec![
            ("maintenance", Value::Null),
            ("enabled", Value::Bool(false)),
        ]);
        let out = emit_canonical(&v).unwrap();
        assert_eq!(out, "maintenance: null\nenabled: false\n");
    }

    #[test]
    fn float_values() {
        let v = obj(vec![("ratio", float(0.5)), ("sci", float(1.5e-3))]);
        let out = emit_canonical(&v).unwrap();
        // ryu shortest: 0.5 → "0.5", 1.5e-3 → "0.0015"
        assert!(out.contains("ratio: 0.5\n"), "got: {out}");
        // ryu may produce "0.0015" or "1.5e-3" — accept both canonical forms
        assert!(
            out.contains("sci: 1.5e-3\n") || out.contains("sci: 0.0015\n"),
            "got: {out}"
        );
    }

    // --- 0.7 § 5.2 rule 14 / § 5.9.8: zero canonicalisation and
    // domain-floor scale magnitudes ---------------------------------------

    #[test]
    fn canonical_float_zero_forms_pass_through() {
        assert_eq!(canonical_float("0.0"), "0.0");
        assert_eq!(canonical_float("-0.0"), "-0.0");
    }

    #[test]
    fn canonical_zero_emits_decimal_with_sign() {
        let v = obj(vec![("z", float(0.0)), ("nz", float(-0.0))]);
        assert_eq!(emit_canonical(&v).unwrap(), "z: 0.0\nnz: -0.0\n");
    }

    #[test]
    fn canonical_min_positive_scale_magnitudes() {
        let v = obj(vec![
            ("k", float(f64::MIN_POSITIVE)),
            ("mn", float(f64::from_bits(1))),
            ("mnn", float(-f64::from_bits(1))),
        ]);
        assert_eq!(
            emit_canonical(&v).unwrap(),
            "k: 2.2250738585072014e-308\nmn: 5e-324\nmnn: -5e-324\n"
        );
    }

    #[test]
    fn empty_string_pair() {
        let v = obj(vec![("note", s(""))]);
        let out = emit_canonical(&v).unwrap();
        assert_eq!(out, "note:\n");
    }

    #[test]
    fn raw_marker_for_keywords() {
        let v = obj(vec![("a", s("true")), ("b", s("null")), ("c", s("false"))]);
        let out = emit_canonical(&v).unwrap();
        assert_eq!(out, "a:: true\nb:: null\nc:: false\n");
    }

    #[test]
    fn raw_marker_for_numbers() {
        let v = obj(vec![("a", s("42")), ("b", s("0.5")), ("c", s("0xFF"))]);
        let out = emit_canonical(&v).unwrap();
        assert!(out.contains("a:: 42\n"));
        assert!(out.contains("b:: 0.5\n"));
        assert!(out.contains("c:: 0xFF\n"));
    }

    #[test]
    fn raw_marker_for_inline_opener() {
        let v = obj(vec![("a", s("{hello}"))]);
        let out = emit_canonical(&v).unwrap();
        assert!(out.contains("a:: {hello}\n"));
    }

    #[test]
    fn nested_object() {
        let v = obj(vec![(
            "server",
            obj(vec![("host", s("localhost")), ("port", int(8080))]),
        )]);
        let out = emit_canonical(&v).unwrap();
        let expected = "server: {\n    host: localhost\n    port: 8080\n}\n";
        assert_eq!(out, expected);
    }

    #[test]
    fn nested_array() {
        let v = obj(vec![("tags", arr(vec![s("a"), s("b")]))]);
        let out = emit_canonical(&v).unwrap();
        let expected = "tags: [\n    a\n    b\n]\n";
        assert_eq!(out, expected);
    }

    #[test]
    fn array_root_bare_items() {
        let v = arr(vec![s("foo"), s("bar"), s("baz")]);
        let out = emit_canonical(&v).unwrap();
        assert_eq!(out, "foo\nbar\nbaz\n");
    }

    #[test]
    fn array_root_wraps_when_first_item_is_compound() {
        let v = arr(vec![arr(vec![s("a"), s("b")]), arr(vec![s("c"), s("d")])]);
        let out = emit_canonical(&v).unwrap();
        let expected =
            "[\n    [\n        a\n        b\n    ]\n    [\n        c\n        d\n    ]\n]\n";
        assert_eq!(out, expected);
    }

    #[test]
    fn array_root_does_not_wrap_for_scalars() {
        let v = arr(vec![int(1), int(2), int(3)]);
        let out = emit_canonical(&v).unwrap();
        assert_eq!(out, "1\n2\n3\n");
    }

    #[test]
    fn cr_in_string_is_error() {
        let v = obj(vec![("x", s("hello\rworld"))]);
        assert!(emit_canonical(&v).is_err());
    }

    #[test]
    fn verbatim_multiline_string() {
        let v = obj(vec![("msg", s("line one\nline two"))]);
        let out = emit_canonical(&v).unwrap();
        assert_eq!(
            out,
            "msg: ((\n\
             line one\n\
             line two\n\
             ))\n"
        );
    }

    #[test]
    fn verbatim_multiline_in_array_item() {
        let v = arr(vec![s("line one\nline two"), s("end")]);
        let out = emit_canonical(&v).unwrap();
        assert_eq!(
            out,
            "((\n\
             line one\n\
             line two\n\
             ))\n\
             end\n"
        );
    }

    #[test]
    fn empty_string_array_item() {
        let v = arr(vec![s(""), s("ok")]);
        let out = emit_canonical(&v).unwrap();
        assert_eq!(out, "::\nok\n");
    }

    #[test]
    fn raw_marker_for_paren_tokens() {
        let v = obj(vec![
            ("a", s("(")),
            ("b", s("((")),
            ("c", s("()")),
            ("d", s("(())")),
        ]);
        let out = emit_canonical(&v).unwrap();
        // Spec 0.7: bare `(` / `((` (multi-line openers) and `()` / `(())`
        // (rule 5, → empty String) need `::`; other `(`-prefixed strings
        // round-trip plain (fixture `inline/paren_scalar_is_string`).
        assert!(out.contains("a:: (\n"));
        assert!(out.contains("b:: ((\n"));
        assert!(out.contains("c:: ()\n"));
        assert!(out.contains("d:: (())\n"));
    }

    #[test]
    fn mixed_heterogeneous_array() {
        let v = obj(vec![(
            "mixed",
            arr(vec![
                s("plain_string"),
                int(42),
                Value::Bool(true),
                Value::Null,
                s("true"), // keyword collision → raw marker
                obj(vec![("nested_obj", s("inside"))]),
                arr(vec![s("nested_array")]),
            ]),
        )]);
        let out = emit_canonical(&v).unwrap();
        let expected = "\
mixed: [
    plain_string
    42
    true
    null
    :: true
    {
        nested_obj: inside
    }
    [
        nested_array
    ]
]
";
        assert_eq!(out, expected);
    }

    #[test]
    fn integer_canonical_negative() {
        let v = obj(vec![("x", int(-1)), ("y", int(-42))]);
        let out = emit_canonical(&v).unwrap();
        assert!(out.contains("x: -1\n"));
        assert!(out.contains("y: -42\n"));
    }

    #[test]
    fn integer_canonical_zero() {
        // `-0` should normalise to `0` — but since we use itoa, -0i64
        // would be `0` anyway (no negative zero in i64). The canonical
        // form from the parser would store "0".
        let v = obj(vec![("z", int(0))]);
        let out = emit_canonical(&v).unwrap();
        assert!(out.contains("z: 0\n"));
    }

    #[test]
    fn needs_raw_marker_integer_forms() {
        assert!(needs_raw_marker("42"));
        assert!(needs_raw_marker("-1"));
        assert!(needs_raw_marker("+7"));
        assert!(needs_raw_marker("0xFF"));
        assert!(needs_raw_marker("0o755"));
        assert!(needs_raw_marker("0b1111_0000"));
        assert!(needs_raw_marker("1_000_000"));
        assert!(!needs_raw_marker("hello"));
        assert!(!needs_raw_marker("42abc"));
    }

    #[test]
    fn needs_raw_marker_float_forms() {
        assert!(needs_raw_marker("0.5"));
        assert!(needs_raw_marker("1.5e-3"));
        assert!(needs_raw_marker("1e9"));
        assert!(!needs_raw_marker("1."));
        assert!(!needs_raw_marker(".5"));
    }

    // --- 0.7 § 5.9.10: key form selection + re-escape -------------------
    // Exact-oracle expectations verified against the 0.7 corpus
    // fixtures (spec/versions/0.7/tests/valid/{key_escaping,quoted_keys}).

    /// Structural bytes (`.` `:` `,` `{` `}` `[` `]` `(` `)`) route the
    /// key to quoted form (§ 5.9.10 rule (a)) — bare `\.` is the old
    /// 0.6 spelling, never the 0.7 canonical output.
    #[test]
    fn structural_bytes_force_quoted() {
        for key in ["a.b", "a:b", "a,b", "a{b", "a}b", "a[b", "a]b", "a(b"] {
            let v = obj(vec![(key, s("v"))]);
            let expected = format!("\"{}\": v\n", key);
            assert_eq!(emit_canonical(&v).unwrap(), expected, "key: {key}");
        }
    }

    /// A literal backslash alone stays BARE — quoted form needs the
    /// identical `\\` escape, so quoting buys nothing (§ 5.9.10).
    #[test]
    fn literal_backslash_stays_bare() {
        let v = obj(vec![("path\\to", s("v"))]);
        assert_eq!(emit_canonical(&v).unwrap(), "path\\\\to: v\n");
    }

    /// A leading `"` forces quoted form (rule (b)); the interior
    /// delimiter occurrences need only `\"` (§ 5.9.10 `port` example).
    #[test]
    fn leading_quote_forces_quoted() {
        let v = obj(vec![("\"port\"", s("v"))]);
        assert_eq!(emit_canonical(&v).unwrap(), "\"\\\"port\\\"\": v\n");
    }

    /// A leading `##` forces quoted form (rule (d)) — no bare escape
    /// changes the raw first two bytes § 5.1 rule 2 inspects.
    #[test]
    fn leading_double_hash_forces_quoted() {
        let v = obj(vec![("##a:b", s("v"))]);
        assert_eq!(emit_canonical(&v).unwrap(), "\"##a:b\": v\n");
        let v = obj(vec![("##tag", s("v"))]);
        assert_eq!(emit_canonical(&v).unwrap(), "\"##tag\": v\n");
    }

    /// LF/CR inside a key stay BARE with the named escapes `\n`/`\r` —
    /// a quoted segment never admits them raw, so quoting buys nothing.
    #[test]
    fn interior_newline_and_cr_stay_bare() {
        let v = obj(vec![("a\nb", s("v"))]);
        assert_eq!(emit_canonical(&v).unwrap(), "a\\nb: v\n");
        let v = obj(vec![("a\rb", s("v"))]);
        assert_eq!(emit_canonical(&v).unwrap(), "a\\rb: v\n");
    }

    /// Edge LF/CR stay BARE too (edge-whitespace exemption, same
    /// quoted-excludes-them-anyway argument) — corpus
    /// `key_escaping/edge_newline_in_key`.
    #[test]
    fn edge_newline_and_cr_stay_bare() {
        for key in ["\nlf", "lf\n", "\rcr", "cr\r"] {
            let v = obj(vec![(key, s("v"))]);
            let expected = format!("{}: v\n", key.replace('\n', "\\n").replace('\r', "\\r"));
            assert_eq!(emit_canonical(&v).unwrap(), expected, "key: {key:?}");
        }
    }

    /// Interior tab (and any interior § 3.3 whitespace) stays raw.
    #[test]
    fn interior_tab_stays_bare_raw() {
        let v = obj(vec![("a\tb", s("v"))]);
        assert_eq!(emit_canonical(&v).unwrap(), "a\tb: v\n");
    }

    /// Control bytes and DEL use `\uXXXX` with four UPPERCASE hex
    /// digits, bare form (corpus `unicode_escape_nul_in_key`).
    #[test]
    fn control_bytes_use_uppercase_unicode_escape() {
        let v = obj(vec![("a\u{1}b", s("v"))]);
        assert_eq!(emit_canonical(&v).unwrap(), "a\\u0001b: v\n");
        let v = obj(vec![("a\u{0}b", s("v"))]);
        assert_eq!(emit_canonical(&v).unwrap(), "a\\u0000b: v\n");
        let v = obj(vec![("a\u{7F}b", s("v"))]);
        assert_eq!(emit_canonical(&v).unwrap(), "a\\u007Fb: v\n");
    }

    /// Edge § 3.3 whitespace (other than LF/CR) forces quoted form —
    /// quoted content is never trimmed (§ 5.3.3), and the whitespace
    /// is emitted raw inside the quotes (corpus
    /// `quoted_keys/edge_whitespace_preserved`).
    #[test]
    fn edge_whitespace_forces_quoted() {
        for key in ["a ", " a", " "] {
            let v = obj(vec![(key, s("v"))]);
            let expected = format!("\"{}\": v\n", key);
            assert_eq!(emit_canonical(&v).unwrap(), expected, "key: {key:?}");
        }
        let v = obj(vec![("\tx", s("v"))]);
        assert_eq!(emit_canonical(&v).unwrap(), "\"\tx\": v\n");
    }

    /// U+FEFF at the start of the ROOT Object's FIRST key forces
    /// quoted form (rule (c) — byte-offset-0 BOM collision, § 5.9.12),
    /// with the U+FEFF raw inside the quotes. The same key at any
    /// other pair position is emitted bare.
    #[test]
    fn bom_root_first_key_quoted_elsewhere_bare() {
        // Root, first pair → quoted.
        let v = obj(vec![("\u{FEFF}host", s("v"))]);
        assert_eq!(emit_canonical(&v).unwrap(), "\"\u{FEFF}host\": v\n");
        // Root, SECOND pair → bare.
        let v = obj(vec![("ok", s("v")), ("\u{FEFF}host", s("v"))]);
        assert_eq!(emit_canonical(&v).unwrap(), "ok: v\n\u{FEFF}host: v\n");
        // First pair of a NESTED object → bare.
        let v = obj(vec![("outer", obj(vec![("\u{FEFF}host", s("v"))]))]);
        assert_eq!(
            emit_canonical(&v).unwrap(),
            "outer: {\n    \u{FEFF}host: v\n}\n"
        );
        // U+FEFF not the first code point → bare always.
        let v = obj(vec![("a\u{FEFF}host", s("v"))]);
        assert_eq!(emit_canonical(&v).unwrap(), "a\u{FEFF}host: v\n");
    }

    /// The root_first flag is keyed on PAIR POSITION, not content: a
    /// root object's first key still takes form selection (quoting for
    /// a structural byte) even when followed by more pairs.
    #[test]
    fn root_first_key_with_structural_byte_still_quoted_among_pairs() {
        let v = obj(vec![("a.b", s("v")), ("c", s("w"))]);
        assert_eq!(emit_canonical(&v).unwrap(), "\"a.b\": v\nc: w\n");
    }

    // -----------------------------------------------------------------------
    // § 5.9.6 / § 5.9.12 — Array root, first item safeguards
    // -----------------------------------------------------------------------

    /// A first item whose body is a pair candidate is read by § 5.0.1
    /// rule 6 as the root Object's first pair, so the raw-marker form
    /// must be used instead. Fixture oracle:
    /// `quoted_keys/array_item_raw_marker_needed.canonical.ktav`.
    #[test]
    fn array_root_first_item_pair_candidate_takes_raw_marker() {
        let v = arr(vec![s("\"tis the season\": fa")]);
        let text = emit_canonical(&v).unwrap();
        assert_eq!(text, ":: \"tis the season\": fa\n");
        let back = crate::parse(&text).unwrap();
        assert_eq!(back, v);
    }

    /// An unterminated leading quote swallows the colon
    /// (`find_unescaped_colon` returns no separator), so the body is
    /// NOT a pair candidate and stays bare. Fixture oracles:
    /// `quoted_keys/unterminated_double_quote_first_line_falls_back` /
    /// `unterminated_leading_quote_falls_back_to_array_item`.
    #[test]
    fn array_root_first_item_unterminated_quote_stays_bare() {
        let v = arr(vec![s("\"tis the season: fa")]);
        assert_eq!(emit_canonical(&v).unwrap(), "\"tis the season: fa\n");
        let v = arr(vec![s("'tis the season: fa")]);
        assert_eq!(emit_canonical(&v).unwrap(), "'tis the season: fa\n");
    }

    /// Plain glued `:` fails `<sep-end>` — not a pair candidate. Glued
    /// `::` (raw marker) and `: ` (whitespace-terminated) ARE.
    #[test]
    fn array_root_first_item_glued_colon_stays_bare() {
        assert_eq!(emit_canonical(&arr(vec![s("a:b")])).unwrap(), "a:b\n");
        assert_eq!(emit_canonical(&arr(vec![s("a::b")])).unwrap(), ":: a::b\n");
        assert_eq!(emit_canonical(&arr(vec![s("a: b")])).unwrap(), ":: a: b\n");
    }

    /// Only the FIRST item of an Array root is exposed to root-kind
    /// detection — later items are dispatched directly as array-item
    /// lines (§ 5.0.1 rules 7–8).
    #[test]
    fn array_root_second_item_not_guarded() {
        let v = arr(vec![s("head"), s("a: b")]);
        assert_eq!(emit_canonical(&v).unwrap(), "head\na: b\n");
    }

    /// Nested array items are never root-detected.
    #[test]
    fn nested_array_first_item_not_guarded() {
        let v = obj(vec![("arr", arr(vec![s("a: b")]))]);
        assert_eq!(emit_canonical(&v).unwrap(), "arr: [\n    a: b\n]\n");
    }

    /// § 5.9.12: a first item beginning with U+FEFF takes the
    /// raw-marker form independently of the pair-candidate test —
    /// bare form would place the BOM at byte offset 0, where readers
    /// strip it per § 3.1. Every other position stays bare.
    #[test]
    fn array_root_first_item_bom_takes_raw_marker() {
        assert_eq!(
            emit_canonical(&arr(vec![s("\u{FEFF}host")])).unwrap(),
            ":: \u{FEFF}host\n"
        );
        // Second position → bare.
        let v = arr(vec![s("x"), s("\u{FEFF}host")]);
        assert_eq!(emit_canonical(&v).unwrap(), "x\n\u{FEFF}host\n");
        // Nested array → bare.
        let v = obj(vec![("arr", arr(vec![s("\u{FEFF}host")]))]);
        assert_eq!(emit_canonical(&v).unwrap(), "arr: [\n    \u{FEFF}host\n]\n");
    }

    /// A plain scalar first item is unaffected by the safeguards.
    #[test]
    fn array_root_first_item_plain_scalar_unaffected() {
        let v = arr(vec![s("plain"), s("a: b")]);
        assert_eq!(emit_canonical(&v).unwrap(), "plain\na: b\n");
    }

    /// The wrapped form is untouched: when the first item is a
    /// compound, the root wraps in `[...]` and the first content line
    /// is `[` itself — no item is root-detected, so no string guard
    /// applies (§ 5.9.3 / § 5.9.6).
    #[test]
    fn array_root_wrapped_form_untouched_by_first_item_guard() {
        let v = arr(vec![obj(vec![("k", s("v"))])]);
        assert_eq!(
            emit_canonical(&v).unwrap(),
            "[\n    {\n        k: v\n    }\n]\n"
        );
    }
}