canboat 9.1.0

NMEA 2000 decoding, encoding and live-bus access: the CANboat PGN database as a library, plus the canboat CLI (convert / interface / server / tui).
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
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
// (C) 2009-2026, Kees Verruijt, Harlingen, The Netherlands.

//! JSON format — matches the canboat C analyzer's `-json` output.
//!
//! Output shape:
//!
//! ```json
//! {"timestamp":"...","prio":N,"src":N,"dst":N,"pgn":N,
//!  "description":"...","fields":{"id":Value,"id":Value,...}}
//! ```
//!
//! On Quick PCS ([`JsonOptions::protocol`]) there is no `prio`, `src` or
//! `dst`: the record starts `{"timestamp":"...","pgn":N,`.
//!
//! Compact (no whitespace), keys in canboat order. Field keys are the
//! camelCase `Id` from canboat.json by default ([`CamelCase::Lower`]);
//! [`CamelCase::Off`] switches them to the human-readable `Name`, which
//! is what canboat C prints. The output is written without a trailing
//! newline.
//!
//! JSON is hand-emitted rather than constructed via serde_json so the
//! output bytes match canboat exactly (number formatting, key order,
//! lack of whitespace, escape handling).

use std::fmt::{self, Write as _};

use crate::engine::decode::{DecodedField, DecodedPgn, FieldValue};

use super::{effective_precision, time_precision_for, write_fixed_float};

/// Display name for a field under the current camelCase mode.
/// Off → human-readable `name`; Lower → camelCase `id` (already
/// pre-camelized in canboat.json); Upper → `id` with the first
/// character capitalised.
fn field_display_name(field: &DecodedField, mode: CamelCase) -> std::borrow::Cow<'_, str> {
    use std::borrow::Cow;
    match mode {
        CamelCase::Off => Cow::Borrowed(field.name()),
        CamelCase::Lower => Cow::Borrowed(field.id()),
        CamelCase::Upper => Cow::Owned(upper_camel(field.id())),
    }
}

/// Wrapper-object key for a record under `--wrap`, spelled per
/// [`JsonOptions::camel_case`].
/// canboat uses `id` as the camelized form (e.g. `isoAddressClaim`,
/// C: `pgn->camelDescription`). Only the wrapper key camelizes — the
/// `description` field inside the record stays the human-readable
/// string in every mode (see `analyzer/analyzer.c::printPgn`), and
/// consumers rely on that: n2k-signalk's Seatalk mapper filters on
/// `description === 'Seatalk: Pilot Heading'`.
fn pgn_wrapper_key(pgn: &DecodedPgn, mode: CamelCase) -> std::borrow::Cow<'_, str> {
    use std::borrow::Cow;
    match mode {
        CamelCase::Off => Cow::Borrowed(pgn.description),
        CamelCase::Lower => Cow::Borrowed(pgn.id),
        CamelCase::Upper => Cow::Owned(upper_camel(pgn.id)),
    }
}

/// Convert a lowerCamelCase string to UpperCamelCase by uppercasing
/// the first character. Other characters are left alone.
fn upper_camel(s: &str) -> String {
    let mut chars = s.chars();
    match chars.next() {
        Some(c) => c.to_uppercase().collect::<String>() + chars.as_str(),
        None => String::new(),
    }
}

/// Knobs for JSON output.
#[derive(Debug, Default, Clone)]
pub struct JsonOptions {
    /// Emit `null` for unavailable fields instead of omitting them
    /// (matches canboat's `-empty`).
    pub include_empty: bool,
    /// Emit lookup values as `{"value":N,"name":"..."}` instead of the
    /// bare name string (matches canboat's `-nv`).
    pub name_value: bool,
    /// Wrap every field in a `{"value":...,"bytes":"..."[,"bits":"..."]}`
    /// object with per-field byte/bit-level diagnostics (matches
    /// canboat's `-debug`).
    pub debug: bool,
    /// Emit field keys + PGN descriptions as camelCase or
    /// UpperCamelCase identifiers instead of canboat's human-
    /// readable form. Defaults to [`CamelCase::Lower`] — the shape
    /// JSON consumers want, and what the binaries emit unless
    /// `--id spaces` asks otherwise.
    pub camel_case: CamelCase,
    /// Nest each record in `{"<pgnKey>":{…}}` instead of emitting it
    /// flat (matches canboat C's `-camel` wrapping, here its own
    /// `--wrap` flag). Off by default: the flat record is what
    /// canboatjs and the Signal K stack consume.
    pub wrap: bool,
    /// The bus the records come from. On Quick PCS a record has no
    /// `prio`, `src` or `dst`: an 11-bit identifier is only a message type
    /// (the record's `pgn`), so those keys are left out rather than filled
    /// with placeholders that read like a priority and a device address.
    pub protocol: crate::engine::BusProtocol,
}

/// Identifier style selector for `--id` (canboat C's `-camel` /
/// `-upper-camel`).
///
/// canboat C builds these by stripping spaces/punctuation from
/// `"Unique Number"` → `"uniqueNumber"` (camelCase) or
/// `"UniqueNumber"` (UpperCamelCase). The Rust port reads the
/// pre-camelized `id` field straight from canboat.json — for
/// [`CamelCase::Upper`] we just capitalise the first character.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum CamelCase {
    /// Use human-readable names (`"Unique Number"`, `"ISO Address
    /// Claim"`). `--id spaces`; matches canboat C's default output.
    Off,
    /// lowerCamelCase identifiers (`"uniqueNumber"`). **The default**
    /// (`--id camel`).
    #[default]
    Lower,
    /// UpperCamelCase identifiers (`"UniqueNumber"`). `--id uppercamel`.
    Upper,
}

thread_local! {
    /// Per-thread scratch buffer for the inner `fields` JSON object.
    /// Re-used across calls to amortise the allocation cost — the
    /// profiler showed a fresh `String::new()` per record + a
    /// `raw_vec::finish_grow` chain dominating the JSON writer's
    /// self-time on hot workloads. `RefCell::take()` swaps an empty
    /// String in for the duration of the call so reentrancy panics
    /// rather than corrupts state.
    static FIELDS_BUF: std::cell::RefCell<String> = const { std::cell::RefCell::new(String::new()) };
}

pub fn write_json<W: fmt::Write>(w: &mut W, pgn: &DecodedPgn, opts: &JsonOptions) -> fmt::Result {
    // Under [`JsonOptions::wrap`] every record is nested in
    // `{"<pgnKey>":{...}}`, keyed on the PGN's identifier (spelled per
    // [`JsonOptions::camel_case`]); the trailing `}` is balanced after
    // the body closes.
    //
    // canboat C ties this to `-camel`: camelCase output always wraps.
    // (It originally keyed on a pinned `camelDescription`, so PGN
    // 130846 wrapped even in plain `-json`; canboat#746 changed it to
    // the `-camel` flag. See `analyzer/analyzer.c::printPgn`.) The Rust
    // binaries decouple the two — camelCase keys are the default and
    // wrapping is not, which is the flat shape canboatjs emits — so
    // `--id` and `--wrap` are independent here.
    let wrap = opts.wrap;
    if wrap {
        w.write_char('{')?;
        w.write_str("\"")?;
        w.write_str(pgn_wrapper_key(pgn, opts.camel_case).as_ref())?;
        w.write_str("\":")?;
    }
    w.write_char('{')?;
    if let Some(ts) = &pgn.timestamp {
        w.write_str("\"timestamp\":")?;
        write_json_string(w, &crate::engine::format::normalize_timestamp(ts))?;
        w.write_char(',')?;
    }
    if opts.protocol.standard_frames() {
        write!(w, "\"pgn\":{}", pgn.pgn)?;
    } else {
        write!(
            w,
            "\"prio\":{},\"src\":{},\"dst\":{},\"pgn\":{}",
            pgn.prio, pgn.src, pgn.dst, pgn.pgn
        )?;
    }
    w.write_str(",\"description\":")?;
    write_json_string(w, pgn.description)?;

    // Build the body of the `fields` object into a buffer so we can
    // skip the wrapping `,"fields":{ ... }` entirely when no field
    // ends up emitted (canboat's `printPgn` defers the open separator
    // until the first field — when every field is suppressed it just
    // closes the top-level object without ever opening fields).
    //
    // Re-use a thread-local buffer between calls — its capacity
    // grows once and then stays put across millions of records.
    let mut fields_buf = FIELDS_BUF.with(|c| c.take());
    fields_buf.clear();
    let result = write_json_inner(w, pgn, opts, &mut fields_buf);
    FIELDS_BUF.with(|c| *c.borrow_mut() = fields_buf);
    result?;
    if wrap {
        w.write_char('}')?;
    }
    Ok(())
}

fn write_json_inner<W: fmt::Write>(
    w: &mut W,
    pgn: &DecodedPgn,
    opts: &JsonOptions,
    fields_buf: &mut String,
) -> fmt::Result {
    let mut top_sep = "";
    // Active repeating-list state: which set (1 → "list", 2 → "list2")
    // and which iteration index we're inside.
    let mut current_set: u8 = 0;
    let mut current_iter: Option<u32> = None;

    let payload_bits = (pgn.data.len() as u32).saturating_mul(8);
    for f in &pgn.fields {
        // Fields whose first byte sits entirely past the payload are
        // dropped — canboat suppresses them regardless of `-empty` /
        // `-debug` (e.g. PGN 126998's third STRING_LAU when only two
        // descriptions fit in the wire). Same gate the text formatter
        // already applies.
        if let Some(bo) = f.bit_offset
            && bo >= payload_bits
        {
            continue;
        }
        // All three top-of-range sentinels — Unknown, Out Of Range and
        // Reserved — are dropped from JSON. canboat routes every one of
        // them through `printEmpty` (print.c), which in JSON mode emits
        // `null` under `-empty` and otherwise sets `g_skip`. The
        // "Out Of Range" / "Reserved" spellings are text-mode only.
        // `-debug` still keeps them, so the byte/bit diagnostic survives.
        if !opts.include_empty && !opts.debug && f.value.is_sentinel() {
            continue;
        }
        // SPARE fields: canboat C's `fieldPrintSpare` (print.c:900)
        // drops them when zero but renders the bytes as BINARY when
        // non-zero — the comment there calls a non-zero SPARE "an
        // incorrect PGN definition". The field will then be emitted
        // by the value writer's `Spare { bytes, .. }` arm.
        if let FieldValue::Spare { value, .. } = &f.value
            && *value == 0
        {
            continue;
        }
        // Reserved fields whose value is all-ones (the "unused"
        // default) are skipped entirely — even under -debug, matching
        // canboat's `fieldPrintReserved`. Other Reserved values flow
        // through and emit their hex string.
        //
        // The decoder makes that call and signals it by returning no
        // bytes; do not re-derive it from `bit_length` here. On a short
        // frame the extractor truncates the field, so "all ones" means
        // all ones of the *truncated* width — PGN 129039's trailing
        // 15-bit Reserved on a 26-byte AIS Class B report reads 7 bits
        // of 0xFF, which is not 0x7FFF, and the two computations
        // disagreed.
        if matches!(&f.value, FieldValue::Reserved { bytes, .. } if bytes.is_empty()) {
            continue;
        }
        // Empty BITLOOKUPs (no bits set) are dropped in JSON output —
        // canboat doesn't emit them either. The text formatter, by
        // contrast, prints "None" for these (see write_field_value
        // in output/text.rs).
        if !opts.include_empty
            && !opts.debug
            && let FieldValue::BitField { bits, .. } = &f.value
            && bits.is_empty()
        {
            continue;
        }

        // Determine "where is this field going":
        // - non-repeating (repeat_set == 0): top-level field.
        // - repeat_set == 1: under "list".
        // - repeat_set == 2: under "list2".
        // Crossing set boundaries closes the previous list and opens the
        // next; crossing iterations within the same set inserts "},{".
        if f.repeat_set == 0 {
            if current_set != 0 {
                fields_buf.write_str("}]")?;
                current_set = 0;
                current_iter = None;
            }
            fields_buf.write_str(top_sep)?;
            write_json_string(fields_buf, field_display_name(f, opts.camel_case).as_ref())?;
            fields_buf.write_char(':')?;
            write_field_value(fields_buf, f, opts, &pgn.data)?;
            top_sep = ",";
        } else {
            let iter = f.repeat_index.unwrap_or(0);
            if current_set != f.repeat_set {
                if current_set != 0 {
                    fields_buf.write_str("}]")?;
                }
                fields_buf.write_str(top_sep)?;
                let key = if f.repeat_set == 1 {
                    "\"list\":[{"
                } else {
                    "\"list2\":[{"
                };
                fields_buf.write_str(key)?;
                current_set = f.repeat_set;
                current_iter = Some(iter);
                top_sep = ",";
                write_json_string(fields_buf, field_display_name(f, opts.camel_case).as_ref())?;
                fields_buf.write_char(':')?;
                write_field_value(fields_buf, f, opts, &pgn.data)?;
            } else if Some(iter) != current_iter {
                fields_buf.write_str("},{")?;
                current_iter = Some(iter);
                write_json_string(fields_buf, field_display_name(f, opts.camel_case).as_ref())?;
                fields_buf.write_char(':')?;
                write_field_value(fields_buf, f, opts, &pgn.data)?;
            } else {
                fields_buf.write_char(',')?;
                write_json_string(fields_buf, field_display_name(f, opts.camel_case).as_ref())?;
                fields_buf.write_char(':')?;
                write_field_value(fields_buf, f, opts, &pgn.data)?;
            }
        }
    }
    if current_set != 0 {
        fields_buf.write_str("}]")?;
    }
    // Empty-list placeholder: canboat C unconditionally emits
    // `"list":[{` the moment it sees the repeating set's start field,
    // regardless of how many iterations the count produces. When the
    // count is 0 the result is `"list":[{}]`. Mirror that here so
    // `Reference Stations: 0` style records line up byte-for-byte.
    // "Did we actually emit any list fields?" — match the same
    // filtering the JSON walker applies (NotAvailable / Spare are
    // dropped in default mode). pgn.fields.iter().any(...) by itself
    // would over-count, because the count=0 + truncated case still
    // pushes NotAvailable fields onto the decoded set but the JSON
    // emits none of them.
    let renderable = |f: &DecodedField| {
        if let FieldValue::Spare { value, .. } = &f.value
            && *value == 0
        {
            return false;
        }
        if matches!(f.value, FieldValue::NotAvailable) && !opts.include_empty && !opts.debug {
            return false;
        }
        true
    };
    let saw_set1 = pgn
        .fields
        .iter()
        .any(|f| f.repeat_set == 1 && renderable(f));
    let saw_set2 = pgn
        .fields
        .iter()
        .any(|f| f.repeat_set == 2 && renderable(f));
    if pgn.has_repeating_set[0] && !saw_set1 {
        if !fields_buf.is_empty() && current_set == 0 {
            fields_buf.push_str(top_sep);
        }
        fields_buf.push_str("\"list\":[{}]");
    }
    if pgn.has_repeating_set[1] && !saw_set2 {
        if !fields_buf.is_empty() {
            fields_buf.push(',');
        }
        fields_buf.push_str("\"list2\":[{}]");
    }
    if !fields_buf.is_empty() {
        w.write_str(",\"fields\":{")?;
        w.write_str(fields_buf)?;
        w.write_char('}')?;
    }
    w.write_char('}')?; // close top
    Ok(())
}

/// Emit a `bytes` / `bits` suffix for `-debug` output. Caller must
/// have already opened the wrapping object and written the value (and
/// any `name`); this appends the diagnostic keys and nothing else.
///
/// canboat's `bytes` is the field's *raw value bits placed in their
/// byte slot* — not the underlying payload bytes. So a 3-bit field at
/// bit offset 13 with value `4` shows up as `"80"` (4 shifted left by
/// 5 to land at bits 5–7 of one byte), not `"9F"` (the underlying
/// payload byte). For whole-byte-aligned fields the two are the same.
fn write_debug_suffix<W: fmt::Write>(w: &mut W, f: &DecodedField, payload: &[u8]) -> fmt::Result {
    let (Some(bo), Some(bl)) = (f.bit_offset, f.bit_length) else {
        return Ok(());
    };
    if bl == 0 {
        return Ok(());
    }
    // Whole-byte-aligned fields (STRING_LAU, BINARY, fixed strings)
    // emit their underlying payload bytes directly — matching the
    // text formatter's same-named branch. extract_bits below tops out
    // at 64 bits, so without this fall-through wide string/binary
    // fields would render no `bytes` annotation at all.
    if bo % 8 == 0 && bl % 8 == 0 {
        let start = (bo / 8) as usize;
        let end = ((bo + bl) / 8) as usize;
        let end_clamped = end.min(payload.len());
        if start < end_clamped {
            w.write_str(",\"bytes\":\"")?;
            for (i, b) in payload[start..end_clamped].iter().enumerate() {
                if i > 0 {
                    w.write_char(' ')?;
                }
                write!(w, "{:02X}", b)?;
            }
            w.write_char('"')?;
        }
        return Ok(());
    }
    use crate::engine::bits::extract_bits;
    let signed = matches!(
        f.value,
        FieldValue::Number(_) if f.unit().is_some()
    );
    let Some(ex) = extract_bits(payload, bo as usize, bl as usize, signed, 0) else {
        return Ok(());
    };
    let raw_unsigned = ex.value as u64;
    let shift = bo % 8;
    let byte_span = ((shift + bl).div_ceil(8)) as usize;
    let shifted: u128 = (raw_unsigned as u128) << shift;
    w.write_str(",\"bytes\":\"")?;
    for i in 0..byte_span {
        if i > 0 {
            w.write_char(' ')?;
        }
        let byte = ((shifted >> (i * 8)) & 0xff) as u8;
        write!(w, "{:02X}", byte)?;
    }
    w.write_char('"')?;
    // `bits`: only emitted when the field width isn't a whole number
    // of bytes — diagnostic for sub-byte fields.
    if bl % 8 != 0 {
        w.write_str(",\"bits\":\"")?;
        // Reproduce canboat's `showBytesOrBits` bit-emission verbatim:
        //   for i in bits-1 .. 0:
        //       byte = (value >> (i / 8)) & 0xff   // shift by BYTE INDEX, not *8
        //       emit (byte >> (i % 8)) & 1
        // The single-bit shifts per byte-index produce a peculiar
        // ordering that doesn't quite represent the value MSB-first,
        // but matches canboat's golden output exactly.
        for i in (0..bl).rev() {
            let byte = (raw_unsigned >> (i / 8)) & 0xff;
            let bit = (byte >> (i % 8)) & 1;
            w.write_char(if bit == 1 { '1' } else { '0' })?;
        }
        w.write_char('"')?;
    }
    Ok(())
}

/// Under `-debug`, every field is wrapped in
/// `{"value":<bare>,"name":"..."?,"bytes":"...","bits":"..."?,"key":true?}`.
///
/// This is canboat's `-debug` JSON form: even Number / String / Float
/// fields that are normally emitted bare get wrapped so the
/// per-field byte/bit annotation is attached.
fn write_field_value_debug<W: fmt::Write>(
    w: &mut W,
    f: &DecodedField,
    opts: &JsonOptions,
    payload: &[u8],
) -> fmt::Result {
    w.write_char('{')?;
    w.write_str("\"value\":")?;
    // The "bare value" emission for the inner `value` key.
    match &f.value {
        FieldValue::Decimal(d) => write_json_string(w, d)?,
        FieldValue::Number(v) => {
            let p = effective_precision(f.precision(), f.resolution());
            let min_w = if p == 7 && f.unit() == Some("deg") {
                10
            } else {
                0
            };
            write_fixed_float(w, *v, p, min_w)?;
        }
        FieldValue::Integer(v) => write!(w, "{}", v)?,
        FieldValue::Float(v) => write!(w, "{}", v)?,
        FieldValue::Binary(bytes) => {
            w.write_char('"')?;
            for (i, b) in bytes.iter().enumerate() {
                if i > 0 {
                    w.write_char(' ')?;
                }
                write!(w, "{:02X}", b)?;
            }
            w.write_char('"')?;
        }
        FieldValue::Lookup { value, name } => {
            // Without -nv, -debug puts the lookup *string* directly as
            // `value` (matches canboat's `fieldPrintLookup` JSON path
            // when `showJsonValue` is false). With -nv, the full
            // {value, name} object form is kept, and the `name` key is
            // present even when the lookup didn't resolve (so
            // out-of-range values still emit `"name":null`).
            if opts.name_value {
                write!(w, "{},\"name\":", value)?;
                match name {
                    Some(n) => write_json_string(w, n)?,
                    None => w.write_str("null")?,
                }
            } else {
                match name {
                    Some(n) => write_json_string(w, n)?,
                    None => write!(w, "{}", value)?,
                }
            }
        }
        FieldValue::BitField { value, bits } => {
            if bits.is_empty() {
                // Empty BITLOOKUP → null in JSON. Matches canboat's
                // `printEmpty` path for `value == 0` in
                // `fieldPrintBitLookup` (print.c:940-945).
                let _ = value;
                w.write_str("null")?;
            } else if opts.name_value {
                // -nv: array of `{value, name}` objects.
                w.write_char('[')?;
                for (i, (bv, n)) in bits.iter().enumerate() {
                    if i > 0 {
                        w.write_char(',')?;
                    }
                    write!(w, "{{\"value\":{},\"name\":", bv)?;
                    match n {
                        Some(n) => write_json_string(w, n)?,
                        // A set bit the enumeration does not name.
                        None => w.write_str("null")?,
                    }
                    w.write_char('}')?;
                }
                w.write_char(']')?;
            } else {
                // Plain JSON: array of bare strings.
                w.write_char('[')?;
                for (i, (bv, n)) in bits.iter().enumerate() {
                    if i > 0 {
                        w.write_char(',')?;
                    }
                    match n {
                        Some(n) => write_json_string(w, n)?,
                        // Unnamed: canboat prints the bit value bare,
                        // so the array mixes strings and numbers.
                        None => write!(w, "{}", bv)?,
                    }
                }
                w.write_char(']')?;
            }
        }
        FieldValue::String(s) => write_field_json_string(w, s)?,
        FieldValue::Date(d) => {
            let mut buf = String::with_capacity(10);
            super::format_date(*d, &mut buf)?;
            // -nv keeps the numeric raw + textual name; without -nv the
            // textual name is emitted directly as `value`.
            if opts.name_value {
                write!(w, "{}", d)?;
                w.write_str(",\"name\":")?;
                write_json_string(w, &buf)?;
            } else {
                write_json_string(w, &buf)?;
            }
        }
        FieldValue::Time { seconds, .. } => {
            let p = time_precision_for(f.resolution());
            let mut buf = String::with_capacity(12);
            super::format_time(*seconds, p, false, &mut buf)?;
            // Seconds, as the non-debug `Time` arm.
            write_fixed_float(w, *seconds, p, 0)?;
            if opts.name_value {
                w.write_str(",\"name\":")?;
                write_json_string(w, &buf)?;
            }
        }
        FieldValue::Mmsi(v) => write!(w, "\"{:09}\"", v)?,
        FieldValue::Pgn { value, description } => {
            // -debug emits the numeric PGN as `value`. The `name` key
            // is only present with -nv — canboat omits it entirely in
            // non-nv even when the PGN is known (and emits `"name":null`
            // for unknown PGNs *only* with -nv).
            write!(w, "{}", value)?;
            if opts.name_value {
                w.write_str(",\"name\":")?;
                match description {
                    Some(desc) => write_json_string(w, desc)?,
                    None => w.write_str("null")?,
                }
            }
        }
        FieldValue::IsoName { value, subfields } => {
            write!(w, "{}", value)?;
            if opts.name_value {
                // -nv + -debug expands the embedded PGN 60928 field
                // set like the non-debug path, but each subfield
                // carries bytes/bits relative to the 8-byte NAME
                // payload; the outer wrapper still gets the whole
                // NAME's `bytes` suffix after the match.
                let name_payload: &[u8] = match f.bit_offset {
                    Some(bo) if bo % 8 == 0 && (bo / 8) as usize + 8 <= payload.len() => {
                        let s = (bo / 8) as usize;
                        &payload[s..s + 8]
                    }
                    _ => &[],
                };
                w.write_str(",\"name\":{")?;
                let mut sep = "";
                for sf in subfields {
                    // Same filtering as the non-debug IsoName arm.
                    if !opts.include_empty && matches!(sf.value, FieldValue::NotAvailable) {
                        continue;
                    }
                    // A SPARE is dropped only when it is zero, the same
                    // rule the top level applies: the C recurses into the
                    // embedded 60928 through the very same `printFields`,
                    // so `fieldPrintSpare` decides here too. Navico's
                    // 130822/130840 carry a NAME whose Spare bit is set,
                    // and canboat renders it as "01".
                    if matches!(&sf.value, FieldValue::Spare { value, .. } if *value == 0) {
                        continue;
                    }
                    w.write_str(sep)?;
                    write_json_string(w, field_display_name(sf, opts.camel_case).as_ref())?;
                    w.write_char(':')?;
                    write_field_value_debug(w, sf, opts, name_payload)?;
                    sep = ",";
                }
                w.write_char('}')?;
            }
        }
        FieldValue::Reserved { bytes, .. } => {
            // Same shape as canboat's Binary: uppercase hex, space-
            // separated.
            w.write_char('"')?;
            for (i, b) in bytes.iter().enumerate() {
                if i > 0 {
                    w.write_char(' ')?;
                }
                write!(w, "{:02X}", b)?;
            }
            w.write_char('"')?;
        }
        FieldValue::Spare { .. } | FieldValue::NotAvailable => {
            w.write_str("null")?;
        }
        FieldValue::OutOfRange { .. } | FieldValue::ReservedValue { .. } => {
            // Reached only under `-empty` / `-debug`, the filter above
            // having dropped these otherwise. canboat's `printEmpty`
            // spells every sentinel `null` in JSON; the "Out Of Range"
            // and "Reserved" labels belong to text output.
            w.write_str("null")?;
        }
        FieldValue::Unsupported { field_type } => {
            let mut buf = String::with_capacity(field_type.len() + 16);
            buf.push_str("<unsupported:");
            buf.push_str(field_type);
            buf.push('>');
            write_json_string(w, &buf)?;
        }
    }
    write_debug_suffix(w, f, payload)?;
    if opts.name_value && f.part_of_primary_key() {
        w.write_str(",\"key\":true")?;
    }
    w.write_char('}')
}

fn write_field_value<W: fmt::Write>(
    w: &mut W,
    f: &DecodedField,
    opts: &JsonOptions,
    payload: &[u8],
) -> fmt::Result {
    if opts.debug {
        return write_field_value_debug(w, f, opts, payload);
    }
    match &f.value {
        FieldValue::Number(v) => {
            let p = effective_precision(f.precision(), f.resolution());
            // canboat's fieldPrintLatLon uses `%10.7f` — width 10
            // + precision 7 — which left-pads short longitudes
            // (`5.1815566` → ` 5.1815566`). We detect that field type
            // by the load-time precision=7 + unit=deg signal set in
            // db.rs.
            let min_w = if p == 7 && f.unit() == Some("deg") {
                10
            } else {
                0
            };
            write_fixed_float(w, *v, p, min_w)
        }
        FieldValue::Integer(v) => {
            // Under -nv, primary-key fields wear an annotation matching
            // canboat's JSON: {"value":N,"key":true}.
            if opts.name_value && f.part_of_primary_key() {
                write!(w, "{{\"value\":{},\"key\":true}}", v)
            } else {
                write!(w, "{}", v)
            }
        }
        FieldValue::Float(v) => super::write_c_g(w, *v),
        FieldValue::Binary(bytes) => {
            // canboat emits binary as uppercase hex with space-separated
            // bytes (matches fieldPrintBinary's `%s%2.02X` w/ " " sep).
            w.write_char('"')?;
            for (i, b) in bytes.iter().enumerate() {
                if i > 0 {
                    w.write_char(' ')?;
                }
                write!(w, "{:02X}", b)?;
            }
            w.write_char('"')
        }
        FieldValue::Lookup { value, name } => {
            if opts.name_value {
                w.write_char('{')?;
                write!(w, "\"value\":{}", value)?;
                match (name, opts.include_empty) {
                    // Resolved → always emit the name.
                    (Some(n), _) => {
                        w.write_str(",\"name\":")?;
                        write_json_string(w, n)?;
                    }
                    // Unresolved + -empty: emit null. Matches canboat's
                    // print.c:725-728 path.
                    (None, true) => w.write_str(",\"name\":null")?,
                    // Unresolved + default: omit "name" entirely.
                    // Matches print.c when showJsonEmpty is false.
                    (None, false) => {}
                }
                // Same primary-key annotation rule as Integer.
                if f.part_of_primary_key() {
                    w.write_str(",\"key\":true")?;
                }
                w.write_char('}')
            } else {
                match name {
                    Some(n) => write_json_string(w, n),
                    None => write!(w, "{}", value),
                }
            }
        }
        FieldValue::BitField { bits, value } => {
            if bits.is_empty() {
                // Empty BITLOOKUP → null (canboat's `printEmpty`).
                let _ = value;
                w.write_str("null")
            } else if opts.name_value {
                // -nv: [{"value":bit_value,"name":"..."},...]
                w.write_char('[')?;
                for (i, (bv, n)) in bits.iter().enumerate() {
                    if i > 0 {
                        w.write_char(',')?;
                    }
                    write!(w, "{{\"value\":{},\"name\":", bv)?;
                    match n {
                        Some(n) => write_json_string(w, n)?,
                        // A set bit the enumeration does not name.
                        None => w.write_str("null")?,
                    }
                    w.write_char('}')?;
                }
                w.write_char(']')
            } else {
                // Plain JSON: bare-string array.
                w.write_char('[')?;
                for (i, (bv, n)) in bits.iter().enumerate() {
                    if i > 0 {
                        w.write_char(',')?;
                    }
                    match n {
                        Some(n) => write_json_string(w, n)?,
                        // Unnamed: canboat prints the bit value bare,
                        // so the array mixes strings and numbers.
                        None => write!(w, "{}", bv)?,
                    }
                }
                w.write_char(']')
            }
        }
        // A DECIMAL's digit pairs are text, not a number: a DSC address
        // such as 060173 keeps its leading zero, and bare it would not even
        // be valid JSON. Quoted, as an MMSI is.
        FieldValue::Decimal(d) => write_json_string(w, d),
        FieldValue::String(s) => write_field_json_string(w, s),
        FieldValue::Date(d) => {
            let mut buf = String::with_capacity(10);
            super::format_date(*d, &mut buf)?;
            if opts.name_value {
                // canboat -nv: {"value":<days>,"name":"YYYY.MM.DD"}
                w.write_str("{\"value\":")?;
                write!(w, "{}", d)?;
                w.write_str(",\"name\":")?;
                write_json_string(w, &buf)?;
                w.write_char('}')
            } else {
                write_json_string(w, &buf)
            }
        }
        FieldValue::Time { seconds, .. } => {
            let p = time_precision_for(f.resolution());
            let mut buf = String::with_capacity(12);
            super::format_time(*seconds, p, false, &mut buf)?;
            // A time of day or a duration is a number of seconds, like
            // every other quantity, in SI and Metric alike; -nv keeps the
            // clock form as the name (canboat C's fieldPrintTime).
            if opts.name_value {
                w.write_str("{\"value\":")?;
                write_fixed_float(w, *seconds, p, 0)?;
                w.write_str(",\"name\":")?;
                write_json_string(w, &buf)?;
                w.write_char('}')
            } else {
                write_fixed_float(w, *seconds, p, 0)
            }
        }
        FieldValue::Mmsi(v) => {
            // canboat emits MMSI as a 9-digit zero-padded string. Under
            // -nv, primary-key MMSI fields wear the same {"value":...,
            // "key":true} annotation as primary-key integers.
            if opts.name_value && f.part_of_primary_key() {
                write!(w, "{{\"value\":\"{:09}\",\"key\":true}}", v)
            } else {
                write!(w, "\"{:09}\"", v)
            }
        }
        FieldValue::Pgn { value, description } => {
            if opts.name_value {
                w.write_char('{')?;
                write!(w, "\"value\":{}", value)?;
                if let Some(desc) = description {
                    w.write_str(",\"name\":")?;
                    write_json_string(w, desc)?;
                }
                w.write_char('}')
            } else {
                write!(w, "{}", value)
            }
        }
        FieldValue::Reserved { bytes, .. } => {
            // canboat emits Reserved as the field's bytes hex-
            // stringified, uppercase, space-separated (same shape as
            // Binary).
            w.write_char('"')?;
            for (i, b) in bytes.iter().enumerate() {
                if i > 0 {
                    w.write_char(' ')?;
                }
                write!(w, "{:02X}", b)?;
            }
            w.write_char('"')
        }
        FieldValue::Spare { bytes, .. } => {
            // canboat C falls into `fieldPrintBinary` for non-zero
            // SPARE fields (print.c:920), emitting them as the same
            // space-separated uppercase hex string used for Reserved.
            w.write_char('"')?;
            for (i, b) in bytes.iter().enumerate() {
                if i > 0 {
                    w.write_char(' ')?;
                }
                write!(w, "{:02X}", b)?;
            }
            w.write_char('"')
        }
        FieldValue::IsoName { value, subfields } => {
            // -nv: {"value":N,"name":{<recursive>}}
            // default: bare N
            if opts.name_value {
                w.write_char('{')?;
                write!(w, "\"value\":{}", value)?;
                w.write_str(",\"name\":{")?;
                let mut sep = "";
                for sf in subfields {
                    // The recursive sub-decode runs the full field set;
                    // drop unavailable subfields (unless -empty) and
                    // collapse Reserved per the parent rules.
                    if !opts.include_empty && matches!(sf.value, FieldValue::NotAvailable) {
                        continue;
                    }
                    // A SPARE is dropped only when it is zero, the same
                    // rule the top level applies: the C recurses into the
                    // embedded 60928 through the very same `printFields`,
                    // so `fieldPrintSpare` decides here too. Navico's
                    // 130822/130840 carry a NAME whose Spare bit is set,
                    // and canboat renders it as "01".
                    if matches!(&sf.value, FieldValue::Spare { value, .. } if *value == 0) {
                        continue;
                    }
                    w.write_str(sep)?;
                    write_json_string(w, field_display_name(sf, opts.camel_case).as_ref())?;
                    w.write_char(':')?;
                    write_field_value(w, sf, opts, payload)?;
                    sep = ",";
                }
                w.write_char('}')?;
                w.write_char('}')
            } else {
                write!(w, "{}", value)
            }
        }
        FieldValue::NotAvailable
        | FieldValue::OutOfRange { .. }
        | FieldValue::ReservedValue { .. } => w.write_str("null"),
        FieldValue::Unsupported { field_type } => {
            // Encode as a string so the JSON stays valid; consumers can
            // detect by leading "<".
            let mut buf = String::with_capacity(field_type.len() + 16);
            buf.push_str("<unsupported:");
            buf.push_str(field_type);
            buf.push('>');
            write_json_string(w, &buf)
        }
    }
}

/// Per-byte escape table. Each entry is `Some(replacement)` for
/// bytes that need quoting in a JSON string; `None` for bytes that
/// pass through unchanged. UTF-8 continuation bytes (>= 0x80) all
/// pass through since the escapes are ASCII-only.
const ESCAPE_TABLE: [Option<&str>; 256] = build_escape_table(false);
const ESCAPE_TABLE_WITH_SLASH: [Option<&str>; 256] = build_escape_table(true);

const fn build_escape_table(slash: bool) -> [Option<&'static str>; 256] {
    let mut t: [Option<&'static str>; 256] = [None; 256];
    t[b'"' as usize] = Some("\\\"");
    t[b'\\' as usize] = Some("\\\\");
    t[0x08] = Some("\\b");
    t[0x09] = Some("\\t");
    t[0x0a] = Some("\\n");
    t[0x0c] = Some("\\f");
    t[0x0d] = Some("\\r");
    // Other control characters (< 0x20) use \u00XX form — handled by
    // the slow path. Mark them with a single-char sentinel "*" that
    // the caller treats as "use \uXXXX".
    let mut i = 0u8;
    while i < 0x20 {
        if t[i as usize].is_none() {
            t[i as usize] = Some("*"); // sentinel for "\u00XX"
        }
        i += 1;
    }
    if slash {
        t[b'/' as usize] = Some("\\/");
    }
    t
}

/// Write `s` as a JSON-quoted string, escaping per RFC 8259.
fn write_json_string<W: fmt::Write>(w: &mut W, s: &str) -> fmt::Result {
    write_json_string_with_table(w, s, &ESCAPE_TABLE)
}

/// canboat C's `print_ascii_json_escaped` (analyzer/print.c:1255)
/// is only used for decoded STRING field values, and it escapes `/`
/// as `\/` alongside the usual JSON escapes. Descriptions / field
/// names come from `pgn.h` C-string literals and skip that function,
/// so their `/` characters stay bare. We keep the same split: the
/// standard [`write_json_string`] is unchanged, and this variant —
/// used only by `FieldValue::String` formatters — adds the `/`
/// escape for byte-for-byte parity.
fn write_field_json_string<W: fmt::Write>(w: &mut W, s: &str) -> fmt::Result {
    write_json_string_with_table(w, s, &ESCAPE_TABLE_WITH_SLASH)
}

/// Body of both `write_json_string` flavours. Walks `s` as bytes and
/// emits the longest unescaped run via a single `write_str` call,
/// inserting escape sequences only at the boundaries — replaces a
/// per-char `match` + virtual `write_char` dispatch + UTF-8 decode
/// with a tight ASCII byte loop. Multibyte UTF-8 sequences pass
/// through because every byte of every escape-needing character is
/// in the ASCII range (< 0x80) and continuation bytes are >= 0x80,
/// so they never match an escape table entry.
#[inline]
fn write_json_string_with_table<W: fmt::Write>(
    w: &mut W,
    s: &str,
    table: &[Option<&str>; 256],
) -> fmt::Result {
    w.write_char('"')?;
    let bytes = s.as_bytes();
    let mut start = 0usize;
    for (i, &b) in bytes.iter().enumerate() {
        if let Some(esc) = table[b as usize] {
            // Flush any pending unescaped run.
            if i > start {
                // SAFETY: `start..i` is a valid char boundary because
                // we never escape continuation bytes (escapes are all
                // < 0x80, continuations are >= 0x80).
                w.write_str(unsafe { std::str::from_utf8_unchecked(&bytes[start..i]) })?;
            }
            if esc.as_bytes() == b"*" {
                // \u00XX form for non-special control codes.
                write!(w, "\\u{:04x}", b as u32)?;
            } else {
                w.write_str(esc)?;
            }
            start = i + 1;
        }
    }
    if start < bytes.len() {
        w.write_str(unsafe { std::str::from_utf8_unchecked(&bytes[start..]) })?;
    }
    w.write_char('"')?;
    Ok(())
}

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

    /// A Quick record leaves out the ISO 11783 header keys; every other
    /// protocol keeps them.
    #[test]
    fn a_quick_record_has_no_prio_src_or_dst() {
        let db = crate::engine::PgnDatabase::embedded_quick(crate::engine::Units::Si);
        let frame =
            crate::engine::RawFrame::new(None, 0, 0x6c1, 0, 255, [0xc1, 0x18, 0x6a, 0, 0, 0, 2, 0]);
        let pgn = db.decode(&frame).unwrap();
        let json = |protocol| {
            let mut out = String::new();
            let opts = JsonOptions {
                protocol,
                ..Default::default()
            };
            write_json(&mut out, &pgn, &opts).unwrap();
            out
        };
        let quick = json(crate::engine::BusProtocol::Quick);
        assert!(
            quick.starts_with(r#"{"pgn":1729,"description":"Quick: Chain Count""#),
            "{quick}"
        );
        let n2k = json(crate::engine::BusProtocol::Nmea2000);
        assert!(
            n2k.starts_with(r#"{"prio":0,"src":0,"dst":255,"pgn":1729,"#),
            "{n2k}"
        );
    }
    /// A DECIMAL's digit pairs are written as a JSON string. The DSC call
    /// from samples/pgn129808.raw addresses coast station 002241024 (sent
    /// as 0022410240): written bare, the leading zero made the whole record
    /// invalid JSON.
    #[test]
    fn a_decimal_is_a_json_string() {
        let data: Vec<u8> =
            "74,6c,00,16,29,02,28,64,7e,39,30,30,30,31,36,ff,ff,ff,ff,ff,ff,02,01,ff,ff,ff,\
             7f,ff,ff,ff,7f,ff,ff,ff,ff,ff,ff,ff,ff,ff,7f,fc,ff,ff,ff,ff,ff,ff,ff,ff,ff,ff,\
             ff,ff,40,f2,b5,17,d4,34,00,00"
                .split(',')
                .map(|h| u8::from_str_radix(h.trim(), 16).unwrap())
                .collect();
        let frame = crate::engine::RawFrame::new(None, 4, 129808, 4, 255, data);
        let pgn = crate::engine::PgnDatabase::embedded(crate::engine::Units::Si)
            .decode(&frame)
            .unwrap();
        for opts in [
            JsonOptions::default(),
            JsonOptions {
                debug: true,
                ..Default::default()
            },
        ] {
            let mut out = String::new();
            write_json(&mut out, &pgn, &opts).unwrap();
            assert!(out.contains("\"002241024\""), "{out}");
            assert!(!out.contains(":002241024"), "bare DECIMAL in {out}");
        }
    }

    use crate::engine::decode::{DecodedField, FieldValue};

    fn sample_pgn() -> DecodedPgn {
        // PGN 128267 (Water Depth) field 3 is `Offset` — m, res 0.001 —
        // which matches the legacy hand-rolled fixture this test used
        // before Phase 5 (when DecodedField duplicated id/name/unit
        // inline). Use a real &'static FieldInfo so the new shape
        // compiles without us standing up a parallel test schema.
        let info = crate::engine::PgnDatabase::embedded(crate::engine::Units::Metric)
            .first_pgn(128267)
            .expect("PGN 128267 present");
        let offset_field = &info.fields[2];
        DecodedPgn {
            timestamp: Some("2018-10-16T22:25:25.166".into()),
            prio: 3,
            pgn: 128267,
            src: 35,
            dst: 255,
            description: "Water Depth",
            id: "waterDepth",
            id_is_pinned: false,
            data: Vec::new(),
            fields: vec![DecodedField {
                info: offset_field,
                value: FieldValue::Number(0.0),
                bit_offset: None,
                bit_length: None,
                repeat_index: None,
                repeat_set: 0,
                overrides: None,
            }],
            has_repeating_set: [false, false],
            index_by_order: [i8::MIN; 32],
        }
    }

    #[test]
    fn default_shape_is_flat_camel_case() {
        // The default: camelCase field keys, no record wrapper — the
        // shape canboatjs emits and the Signal K stack consumes.
        let pgn = sample_pgn();
        let mut out = String::new();
        write_json(&mut out, &pgn, &JsonOptions::default()).unwrap();
        // The sample timestamp lacks a trailing `Z`; the formatter
        // canonicalises it to ISO-8601 UTC on emit.
        assert_eq!(
            out,
            r#"{"timestamp":"2018-10-16T22:25:25.166Z","prio":3,"src":35,"dst":255,"pgn":128267,"description":"Water Depth","fields":{"offset":0.000}}"#
        );
    }

    #[test]
    fn matches_canboat_json_shape() {
        // `--id spaces`: canboat C's own output, spaced field names and
        // no wrapper.
        let pgn = sample_pgn();
        let mut out = String::new();
        let opts = JsonOptions {
            camel_case: CamelCase::Off,
            ..JsonOptions::default()
        };
        write_json(&mut out, &pgn, &opts).unwrap();
        assert_eq!(
            out,
            r#"{"timestamp":"2018-10-16T22:25:25.166Z","prio":3,"src":35,"dst":255,"pgn":128267,"description":"Water Depth","fields":{"Offset":0.000}}"#
        );
    }

    #[test]
    fn camel_mode_keeps_the_human_description() {
        // canboat C camelizes only the wrapper key and the field names;
        // the description field stays human-readable in every mode
        // (analyzer.c uses pgn->camelDescription for the key and
        // pgn->description for the field). n2k-signalk's Seatalk
        // mapper matches on the human string, so this is contract,
        // not cosmetics.
        let pgn = sample_pgn();
        let mut out = String::new();
        let opts = JsonOptions {
            camel_case: CamelCase::Lower,
            wrap: true,
            ..JsonOptions::default()
        };
        write_json(&mut out, &pgn, &opts).unwrap();
        assert_eq!(
            out,
            r#"{"waterDepth":{"timestamp":"2018-10-16T22:25:25.166Z","prio":3,"src":35,"dst":255,"pgn":128267,"description":"Water Depth","fields":{"offset":0.000}}}"#
        );
    }

    #[test]
    fn wrapping_is_independent_of_identifier_style() {
        // canboat C ties the wrapper to `-camel`; here `--wrap` and
        // `--id` are orthogonal, so a wrapped record can carry spaced
        // names — and then the wrapper key is the human description,
        // exactly as `pgn_wrapper_key` spells it.
        let pgn = sample_pgn();
        let mut out = String::new();
        let opts = JsonOptions {
            camel_case: CamelCase::Off,
            wrap: true,
            ..JsonOptions::default()
        };
        write_json(&mut out, &pgn, &opts).unwrap();
        assert!(out.starts_with(r#"{"Water Depth":{"#), "got: {out}");
        assert!(
            out.ends_with(r#""fields":{"Offset":0.000}}}"#),
            "got: {out}"
        );
    }

    #[test]
    fn fields_object_omitted_when_all_unavailable() {
        // Canboat suppresses the `,"fields":{...}` wrapper entirely
        // when no field actually prints — matches `printPgn`'s lazy
        // open of the fields object. We do the same.
        let mut pgn = sample_pgn();
        pgn.fields[0].value = FieldValue::NotAvailable;
        let mut out = String::new();
        write_json(&mut out, &pgn, &JsonOptions::default()).unwrap();
        assert!(
            !out.contains("\"fields\""),
            "fields wrapper leaked through: {out}"
        );
        assert!(out.ends_with("}"), "got: {out}");
    }

    #[test]
    fn include_empty_emits_null() {
        let mut pgn = sample_pgn();
        pgn.fields[0].value = FieldValue::NotAvailable;
        let mut out = String::new();
        write_json(
            &mut out,
            &pgn,
            &JsonOptions {
                include_empty: true,
                ..Default::default()
            },
        )
        .unwrap();
        assert!(out.contains(r#""offset":null"#), "got: {}", out);
    }

    #[test]
    fn out_of_range_and_reserved_are_dropped_from_json() {
        // canboat funnels all three top-of-range sentinels through
        // `printEmpty`, which in JSON mode sets `g_skip` — the field
        // simply isn't there. "Out Of Range" and "Reserved" are the
        // text formatter's spellings and must never reach JSON.
        for sentinel in [
            FieldValue::OutOfRange { value: 254 },
            FieldValue::ReservedValue { value: 253 },
        ] {
            let mut pgn = sample_pgn();
            pgn.fields[0].value = sentinel;
            let mut out = String::new();
            write_json(&mut out, &pgn, &JsonOptions::default()).unwrap();
            assert!(!out.contains("\"fields\""), "sentinel leaked: {out}");
        }
    }

    #[test]
    fn include_empty_spells_every_sentinel_null() {
        // Under `-empty` canboat prints `null` for all of them, not the
        // text labels.
        for sentinel in [
            FieldValue::OutOfRange { value: 254 },
            FieldValue::ReservedValue { value: 253 },
        ] {
            let mut pgn = sample_pgn();
            pgn.fields[0].value = sentinel;
            let mut out = String::new();
            write_json(
                &mut out,
                &pgn,
                &JsonOptions {
                    include_empty: true,
                    ..Default::default()
                },
            )
            .unwrap();
            assert!(out.contains(r#""offset":null"#), "got: {out}");
        }
    }

    #[test]
    fn name_value_emits_object_for_lookup() {
        let mut pgn = sample_pgn();
        pgn.fields[0].value = FieldValue::Lookup {
            value: 275,
            name: Some("Navico"),
        };
        // Suppress the sample fixture's resolution / unit so the
        // formatter renders a plain lookup pair without numeric
        // formatting. (Old test set the fields directly; with Phase 5
        // those go through `overrides`.)
        pgn.fields[0].overrides = Some(Box::new(crate::engine::decode::FieldOverrides {
            unit: None,
            resolution: Some(1.0),
            precision: 0,
        }));
        let mut out = String::new();
        write_json(
            &mut out,
            &pgn,
            &JsonOptions {
                name_value: true,
                ..Default::default()
            },
        )
        .unwrap();
        assert!(
            out.contains(r#""offset":{"value":275,"name":"Navico"}"#),
            "got: {}",
            out
        );
    }

    #[test]
    fn escapes_quotes_in_strings() {
        let mut pgn = sample_pgn();
        pgn.description = r#"He said "hi""#;
        let mut out = String::new();
        write_json(&mut out, &pgn, &JsonOptions::default()).unwrap();
        assert!(
            out.contains(r#""description":"He said \"hi\"""#),
            "got: {}",
            out
        );
    }
}