mf4-rs 4.2.0

mf4-rs is a Rust library for working with ASAM MDF 4 (Measurement Data Format) files.
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
//! Guards the cross-language API contract (`docs/api-contract.json`).
//!
//! Two halves:
//!
//! * **Names** — the public methods of `Mdf`, `MdfIndex` and `MdfWriter`, the
//!   fields of the contract types and the crate-root re-exports are read from
//!   the source and compared with the contract. Adding, renaming or removing a
//!   public method fails this test until the contract (and with it the Python
//!   and TypeScript bindings, which have the same test) is updated.
//! * **Behaviour** — `Mdf`, `MdfIndex` and `MdfReader` must answer every
//!   contract call identically for the same file.

use std::collections::BTreeSet;
use std::path::Path;

use mf4_rs::{
    ChannelInfo, ConversionInfo, DataType, DecodedValue, GroupInfo, Mdf, MdfError, MdfIndex, MdfWriter,
    ReadOptions, Signal, TimeRange,
};
use serde_json::Value;

fn root() -> &'static Path {
    Path::new(env!("CARGO_MANIFEST_DIR"))
}

fn contract() -> Value {
    let text = std::fs::read_to_string(root().join("docs/api-contract.json")).unwrap();
    serde_json::from_str(&text).unwrap()
}

fn strings(value: &Value) -> BTreeSet<String> {
    value
        .as_array()
        .map(|a| a.iter().map(|v| v.as_str().unwrap().to_string()).collect())
        .unwrap_or_default()
}

/// Names of the `pub fn`s in the inherent `impl` blocks of `type_name`.
fn public_methods(files: &[&str], type_name: &str) -> BTreeSet<String> {
    let mut out = BTreeSet::new();
    for file in files {
        let text = std::fs::read_to_string(root().join(file)).unwrap();
        let mut inside = false;
        for line in text.lines() {
            if line.starts_with("impl") && !line.contains(" for ") {
                let rest = line.split_once(' ').map(|(_, r)| r).unwrap_or("");
                // `impl Name {`, `impl Name<'a> {`, `impl<'a, R: ..> Name<'a, R> {`
                let subject = rest.rsplit(' ').nth(1).unwrap_or("");
                inside = subject.split('<').next() == Some(type_name)
                    || rest.contains(&format!("> {type_name}<"))
                    || rest.starts_with(&format!("{type_name} "))
                    || rest.starts_with(&format!("{type_name}<"));
                continue;
            }
            if line == "}" {
                inside = false;
            }
            if inside {
                if let Some(rest) = line.strip_prefix("    pub fn ") {
                    let name: String = rest.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
                    out.insert(name);
                }
            }
        }
    }
    out
}

/// Names of the `pub` fields of `pub struct type_name` in `file`.
fn public_fields(file: &str, type_name: &str) -> BTreeSet<String> {
    let text = std::fs::read_to_string(root().join(file)).unwrap();
    let mut out = BTreeSet::new();
    let mut inside = false;
    for line in text.lines() {
        if line.starts_with(&format!("pub struct {type_name} {{")) {
            inside = true;
            continue;
        }
        if line == "}" {
            inside = false;
        }
        if inside {
            if let Some(rest) = line.strip_prefix("    pub ") {
                out.insert(rest.split(':').next().unwrap().to_string());
            }
        }
    }
    out
}

/// What the contract says Rust exposes on a class: every contract name not
/// restricted to other languages, plus the Rust extras.
fn expected_class(spec: &Value) -> BTreeSet<String> {
    let mut names = BTreeSet::new();
    for section in ["constructors", "accessors", "methods"] {
        for name in strings(&spec[section]) {
            let only = &spec["only"][&name];
            if only.is_null() || strings(only).contains("rust") {
                names.insert(name);
            }
        }
    }
    names.extend(strings(&spec["extra"]["rust"]));
    names
}

#[test]
fn class_methods_match_the_contract() {
    let contract = contract();
    let writer_files = [
        "src/writer/mdf_writer/init.rs",
        "src/writer/mdf_writer/data.rs",
        "src/writer/mdf_writer/io.rs",
        "src/writer/mdf_writer/vlsd.rs",
        "src/writer/mdf_writer/simple.rs",
    ];
    let cases: [(&str, &[&str]); 3] = [
        ("Mdf", &["src/api/mdf.rs"]),
        ("MdfIndex", &["src/index.rs"]),
        ("MdfWriter", &writer_files),
    ];
    for (class, files) in cases {
        let actual = public_methods(files, class);
        let expected = expected_class(&contract["classes"][class]);
        assert_eq!(
            actual, expected,
            "public methods of `{class}` differ from docs/api-contract.json \
             (left: source, right: contract). Update the contract and every binding together."
        );
    }
}

#[test]
fn reader_mirrors_the_index_read_api() {
    // `MdfReader` (an index bound to a custom byte source) must offer the
    // same data methods as `MdfIndex`.
    let reader = public_methods(&["src/index.rs"], "MdfReader");
    for name in ["read", "read_many", "values", "time_range"] {
        assert!(reader.contains(name), "MdfReader is missing `{name}`");
    }
}

#[test]
fn type_fields_match_the_contract() {
    let contract = contract();
    let files = [
        ("Signal", "src/signal.rs"),
        ("GroupInfo", "src/types.rs"),
        ("ChannelInfo", "src/types.rs"),
        ("ConversionInfo", "src/types.rs"),
        ("ReadOptions", "src/types.rs"),
        ("TimeRange", "src/types.rs"),
    ];
    for (name, file) in files {
        let mut actual = public_fields(file, name);
        // `type` is a keyword in Rust; the field is serialized as `type`.
        if actual.remove("conversion_type") {
            actual.insert("type".to_string());
        }
        assert_eq!(
            actual,
            strings(&contract["types"][name]["fields"]),
            "fields of `{name}` differ from docs/api-contract.json"
        );
    }
}

#[test]
fn crate_root_exports_match_the_contract() {
    let lib = std::fs::read_to_string(root().join("src/lib.rs")).unwrap();
    let mut actual = BTreeSet::new();
    for line in lib.lines() {
        let Some(rest) = line.strip_prefix("pub use ") else { continue };
        let rest = rest.trim_end_matches(';');
        let items = match rest.split_once("::{") {
            Some((_, list)) => list.trim_end_matches('}').to_string(),
            None => rest.rsplit("::").next().unwrap().to_string(),
        };
        actual.extend(items.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()));
    }
    assert_eq!(actual, strings(&contract()["module_exports"]["rust"]));
}

// ---------------------------------------------------------------------------
// Behaviour: the three Rust readers agree
// ---------------------------------------------------------------------------

fn write_fixture(path: &Path) -> Result<(), MdfError> {
    let mut w = MdfWriter::new(path.to_str().unwrap())?;
    w.init_mdf_file()?;
    w.set_start_time(1_700_000_000_000_000_000)?;
    for (group, base) in [("Engine", 0.0), ("Body", 100.0)] {
        let g = w.add_channel_group(Some(group))?;
        w.set_channel_group_comment(&g, "a comment")?;
        w.add_time_channel(&g, "Time")?;
        let speed = w.add_float_channel(&g, "Speed")?;
        let gear = w.add_int_channel(&g, "Gear")?;
        w.add_string_channel(&g, "Label")?;
        w.add_channel(&g, "Raw", DataType::SignedIntegerLE)?;
        w.add_linear_conversion(&speed, 1.0, 2.0)?;
        w.add_value_to_text_conversion(&gear, &[(0, "N"), (1, "D")], "?")?;
        w.start_data_block(&g)?;
        for i in 0..20u64 {
            w.write_record(
                &g,
                &[
                    DecodedValue::Float(i as f64 * 0.5),
                    DecodedValue::Float(base + i as f64),
                    DecodedValue::UnsignedInteger(i % 3),
                    DecodedValue::String(format!("L{i}")),
                    DecodedValue::SignedInteger(-(i as i64)),
                ],
            )?;
        }
        w.finish_data_block(&g)?;
    }
    w.finalize()
}

/// The contract's read surface, so the three readers can be driven alike.
trait Reader {
    fn groups(&mut self) -> Vec<GroupInfo>;
    fn group(&mut self, name: &str) -> Option<GroupInfo>;
    fn channel(&mut self, name: &str, group: Option<&str>) -> Option<ChannelInfo>;
    fn channel_names(&mut self) -> Vec<String>;
    fn start_time_ns(&mut self) -> Option<u64>;
    fn read(&mut self, name: &str, options: &ReadOptions) -> Result<Signal, MdfError>;
    fn read_many(&mut self, names: &[&str], options: &ReadOptions) -> Result<Vec<Signal>, MdfError>;
    fn values(&mut self, name: &str, options: &ReadOptions) -> Result<Vec<f64>, MdfError>;
    fn time_range(&mut self, name: &str, group: Option<&str>) -> Result<Option<TimeRange>, MdfError>;
    fn conversion(&mut self, name: &str, group: Option<&str>) -> Result<Option<ConversionInfo>, MdfError>;
}

macro_rules! impl_reader {
    ($ty:ty, $meta:ident) => {
        impl Reader for $ty {
            fn groups(&mut self) -> Vec<GroupInfo> {
                self.$meta().groups().unwrap()
            }
            fn group(&mut self, name: &str) -> Option<GroupInfo> {
                self.$meta().group(name).unwrap()
            }
            fn channel(&mut self, name: &str, group: Option<&str>) -> Option<ChannelInfo> {
                self.$meta().channel(name, group).unwrap()
            }
            fn channel_names(&mut self) -> Vec<String> {
                self.$meta().channel_names().unwrap()
            }
            fn start_time_ns(&mut self) -> Option<u64> {
                self.$meta().start_time_ns()
            }
            fn read(&mut self, name: &str, options: &ReadOptions) -> Result<Signal, MdfError> {
                <$ty>::read(self, name, options)
            }
            fn read_many(&mut self, names: &[&str], options: &ReadOptions) -> Result<Vec<Signal>, MdfError> {
                <$ty>::read_many(self, names, options)
            }
            fn values(&mut self, name: &str, options: &ReadOptions) -> Result<Vec<f64>, MdfError> {
                <$ty>::values(self, name, options)
            }
            fn time_range(&mut self, name: &str, group: Option<&str>) -> Result<Option<TimeRange>, MdfError> {
                <$ty>::time_range(self, name, group)
            }
            fn conversion(&mut self, name: &str, group: Option<&str>) -> Result<Option<ConversionInfo>, MdfError> {
                self.$meta().conversion(name, group)
            }
        }
    };
}

trait Itself {
    fn itself(&self) -> &Self {
        self
    }
}
impl Itself for Mdf {}
impl Itself for MdfIndex {}

impl_reader!(Mdf, itself);
impl_reader!(MdfIndex, itself);
impl_reader!(mf4_rs::MdfReader<'_, mf4_rs::index::MmapRangeReader>, index);

fn same_floats(a: &[f64], b: &[f64]) -> bool {
    a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.to_bits() == y.to_bits())
}

#[test]
fn every_reader_gives_the_same_answers() -> Result<(), MdfError> {
    let dir = tempfile::tempdir().map_err(MdfError::IOError)?;
    let path = dir.path().join("contract.mf4");
    write_fixture(&path)?;
    let path = path.to_str().unwrap();

    let mut mdf = Mdf::from_file(path)?;
    let mut index = MdfIndex::from_file(path)?;
    // A JSON round trip must not change anything either.
    let mut reloaded = MdfIndex::from_json(&index.to_json()?)?;
    reloaded.validate()?;
    assert!(reloaded.source().is_none());
    reloaded.set_source(path);
    let bound_index = MdfIndex::from_bytes(std::fs::read(path).map_err(MdfError::IOError)?)?;
    let mut bound = bound_index.open_file(path)?;

    let option_sets = [
        ReadOptions::new(),
        ReadOptions::new().group("Body"),
        ReadOptions::new().time(Some(2.0), Some(4.5)),
        ReadOptions::new().group("Body").time(None, Some(1.0)),
        ReadOptions::new().time(Some(100.0), None),
        ReadOptions::new().records(3, 5),
        ReadOptions::new().group("Body").records(19, 1),
    ];

    let expected_groups = mdf.groups()?;
    assert_eq!(expected_groups.len(), 2);
    assert_eq!(expected_groups[0].master_channel.as_deref(), Some("Time"));
    assert_eq!(expected_groups[0].channel_names, ["Time", "Speed", "Gear", "Label", "Raw"]);
    assert_eq!(expected_groups[0].comment.as_deref(), Some("a comment"));
    let speed = mdf.channel("Speed", Some("Body"))?.expect("Speed");
    assert_eq!((speed.data_type.as_str(), speed.bit_count), ("FloatLE", 64));
    assert!(speed.has_conversion && !speed.is_master && !speed.is_vlsd);
    assert!(mdf.channel("Label", None)?.expect("Label").is_vlsd);

    let readers: [(&str, &mut dyn Reader); 3] =
        [("MdfIndex", &mut index), ("MdfIndex (from JSON)", &mut reloaded), ("MdfReader", &mut bound)];
    for (label, reader) in readers {
        assert_eq!(reader.groups(), expected_groups, "{label}: groups");
        assert_eq!(reader.group("Body"), Reader::group(&mut mdf, "Body"), "{label}: group");
        assert_eq!(reader.group("Nope"), None, "{label}: missing group");
        assert_eq!(reader.channel_names(), Reader::channel_names(&mut mdf), "{label}: channel_names");
        assert_eq!(reader.start_time_ns(), Some(1_700_000_000_000_000_000), "{label}: start time");
        assert_eq!(reader.channel("Nope", None), None, "{label}: missing channel");

        for name in ["Time", "Speed", "Gear", "Label", "Raw"] {
            for group in [None, Some("Body")] {
                assert_eq!(
                    reader.channel(name, group),
                    Reader::channel(&mut mdf, name, group),
                    "{label}: channel {name}"
                );
                assert_eq!(
                    reader.time_range(name, group)?,
                    Reader::time_range(&mut mdf, name, group)?,
                    "{label}: time_range {name}"
                );
                assert_eq!(
                    reader.conversion(name, group)?,
                    Reader::conversion(&mut mdf, name, group)?,
                    "{label}: conversion {name}"
                );
            }
            for options in &option_sets {
                let want = Reader::read(&mut mdf, name, options)?;
                let got = reader.read(name, options)?;
                assert_eq!((&got.name, &got.unit), (&want.name, &want.unit), "{label}: {name} {options:?}");
                assert_eq!(got.values, want.values, "{label}: values of {name} {options:?}");
                assert!(same_floats(&got.timestamps, &want.timestamps), "{label}: timestamps of {name} {options:?}");
                assert!(
                    same_floats(&reader.values(name, options)?, &Reader::values(&mut mdf, name, options)?),
                    "{label}: values() of {name} {options:?}"
                );
            }
        }

        // read_many = one read per name, for every option set.
        let names = ["Speed", "Time", "Label", "Gear", "Speed"];
        for options in &option_sets {
            let many = reader.read_many(&names, options)?;
            let one_by_one = names.iter().map(|n| Reader::read(&mut mdf, n, options)).collect::<Result<Vec<_>, _>>()?;
            assert_eq!(many.len(), names.len(), "{label}: read_many {options:?}");
            for (got, want) in many.iter().zip(&one_by_one) {
                assert_eq!((&got.name, &got.values), (&want.name, &want.values), "{label}: read_many {options:?}");
                assert!(same_floats(&got.timestamps, &want.timestamps), "{label}: read_many {options:?}");
            }
            assert_eq!(Reader::read_many(&mut mdf, &names, options)?.len(), names.len());
        }
        assert!(reader.read_many(&[], &ReadOptions::new())?.is_empty(), "{label}");

        // The one error rule: data operations on a missing channel fail with
        // ChannelNotFound; invalid windows with InvalidArgument.
        assert!(
            matches!(reader.read_many(&["Speed", "Nope"], &ReadOptions::new()), Err(MdfError::ChannelNotFound { .. })),
            "{label}"
        );
        let missing = ReadOptions::new().group("Engine");
        assert!(matches!(reader.read("Nope", &missing), Err(MdfError::ChannelNotFound { .. })), "{label}");
        assert!(matches!(reader.values("Nope", &missing), Err(MdfError::ChannelNotFound { .. })), "{label}");
        assert!(matches!(reader.time_range("Nope", None), Err(MdfError::ChannelNotFound { .. })), "{label}");
        assert!(matches!(reader.conversion("Nope", None), Err(MdfError::ChannelNotFound { .. })), "{label}");
        let both = ReadOptions { start_time: Some(0.0), start_record: Some(0), ..ReadOptions::default() };
        assert!(matches!(reader.read("Speed", &both), Err(MdfError::InvalidArgument(_))), "{label}");
        let past_end = ReadOptions::new().records(15, 10);
        assert!(matches!(reader.read("Speed", &past_end), Err(MdfError::InvalidArgument(_))), "{label}");
    }

    // Spot-check the actual numbers once, against the reference reader.
    let window = mdf.read("Speed", &ReadOptions::new().time(Some(2.0), Some(3.0)))?;
    assert_eq!(window.timestamps, [2.0, 2.5, 3.0]);
    assert_eq!(window.values_f64(), [9.0, 11.0, 13.0]); // 1 + 2 * raw
    assert_eq!(mdf.read("Time", None)?.timestamps, Vec::<f64>::new(), "a master has no separate time axis");
    assert_eq!(mdf.time_range("Speed", None)?, Some(TimeRange { start: 0.0, end: 9.5 }));
    let gear = mdf.conversion("Gear", None)?.expect("Gear conversion");
    assert_eq!(gear.conversion_type, "ValueToText");
    assert_eq!(gear.texts.get(&2).map(String::as_str), Some("?"));
    assert_eq!(mdf.conversion("Time", None)?, None);
    assert_eq!(index.byte_ranges("Speed", None)?.len(), 1);
    assert_eq!(index.byte_ranges_for_records("Speed", 2, 3, Some("Body"))?.len(), 1);
    Ok(())
}

// ---------------------------------------------------------------------------
// Cross-language golden test
// ---------------------------------------------------------------------------
//
// Every language builds the same file with its own writer, answers the calls
// listed in tests/contract/scenario.json with both readers, and must
// reproduce tests/contract/golden.json. Regenerate the golden file with
// `UPDATE_GOLDEN=1 cargo test --test api_contract` after an intended change.

fn build_scenario_file(path: &Path) -> Result<(), MdfError> {
    let mut w = MdfWriter::new(path.to_str().unwrap())?;
    w.init_mdf_file()?;
    w.set_start_time(1_700_000_000_123_456_789)?;

    let g = w.add_channel_group(Some("Engine"))?;
    w.set_channel_group_comment(&g, "engine data")?;
    w.add_time_channel(&g, "Time")?;
    let speed = w.add_float_channel(&g, "Speed")?;
    let gear = w.add_int_channel(&g, "Gear")?;
    w.add_sint_channel(&g, "Raw")?;
    w.add_float32_channel(&g, "Small")?;
    w.add_string_channel(&g, "Label")?;
    w.add_channel(&g, "Latin", DataType::StringLatin1)?;
    w.add_channel(&g, "Wide", DataType::StringUtf16LE)?;
    w.add_channel(&g, "Blob", DataType::ByteArray)?;
    w.add_linear_conversion(&speed, 1.0, 2.0)?;
    w.add_value_to_text_conversion(&gear, &[(0, "N"), (1, "D")], "?")?;
    w.start_data_block(&g)?;
    for i in 0..6u8 {
        w.write_record(
            &g,
            &[
                DecodedValue::Float(i as f64 * 0.5),
                DecodedValue::Float(i as f64),
                DecodedValue::UnsignedInteger((i % 3) as u64),
                DecodedValue::SignedInteger(-(i as i64)),
                DecodedValue::Float(i as f64 + 0.25),
                DecodedValue::String(format!("L{i}")),
                DecodedValue::String(format!("\u{e9}{i}")),
                DecodedValue::String(format!("\u{fc}\u{20ac}{i}")),
                DecodedValue::ByteArray(vec![i, i + 1]),
            ],
        )?;
    }
    w.finish_data_block(&g)?;

    let g = w.add_channel_group(Some("NoMaster"))?;
    w.add_int_channel(&g, "Count")?;
    w.start_data_block(&g)?;
    for i in 0..3u64 {
        w.write_record(&g, &[DecodedValue::UnsignedInteger(10 + i)])?;
    }
    w.finish_data_block(&g)?;

    let g = w.add_channel_group(Some("Empty"))?;
    w.add_time_channel(&g, "Time")?;
    w.add_float_channel(&g, "Value")?;
    w.start_data_block(&g)?;
    w.finish_data_block(&g)?;

    w.finalize()
}

fn case_options(case: &Value) -> ReadOptions {
    ReadOptions {
        group: case["group"].as_str().map(str::to_string),
        start_time: case["start_time"].as_f64(),
        end_time: case["end_time"].as_f64(),
        start_record: case["start_record"].as_u64(),
        record_count: case["record_count"].as_u64(),
        raw: case["raw"].as_bool().unwrap_or(false),
    }
}

fn error_kind(error: &MdfError) -> Value {
    Value::from(match error {
        MdfError::ChannelNotFound { .. } => "error: channel not found",
        _ => "error",
    })
}

fn floats(values: &[f64]) -> Value {
    Value::from(values.iter().map(|v| if v.is_nan() { Value::Null } else { Value::from(*v) }).collect::<Vec<_>>())
}

fn signal_json(signal: &Signal) -> Value {
    let values: Vec<Value> = signal
        .values
        .iter()
        .map(|v| match v {
            None => Value::Null,
            Some(DecodedValue::Float(f)) => Value::from(*f),
            Some(DecodedValue::UnsignedInteger(u)) => Value::from(*u as f64),
            Some(DecodedValue::SignedInteger(i)) => Value::from(*i as f64),
            Some(DecodedValue::String(s)) => Value::from(s.as_str()),
            Some(DecodedValue::ByteArray(b)) => serde_json::json!({ "bytes": b }),
            other => panic!("unexpected value {other:?}"),
        })
        .collect();
    serde_json::json!({
        "name": signal.name,
        "unit": signal.unit,
        "timestamps": floats(&signal.timestamps),
        "values": values,
    })
}

/// Canonical form shared by the three languages: snake_case keys, no
/// null-valued object fields, every number a float.
fn canonical(value: Value) -> Value {
    match value {
        Value::Object(map) => Value::Object(
            map.into_iter()
                .filter(|(_, v)| !v.is_null())
                .map(|(k, v)| {
                    // camelCase field names only; case labels (which start
                    // with a channel name) are kept as they are.
                    if !k.starts_with(|c: char| c.is_ascii_lowercase()) {
                        return (k, canonical(v));
                    }
                    let mut key = String::new();
                    for ch in k.chars() {
                        if ch.is_ascii_uppercase() {
                            key.push('_');
                            key.push(ch.to_ascii_lowercase());
                        } else {
                            key.push(ch);
                        }
                    }
                    (key, canonical(v))
                })
                .collect(),
        ),
        Value::Array(items) => Value::Array(items.into_iter().map(canonical).collect()),
        Value::Number(n) => Value::from(n.as_f64().unwrap()),
        other => other,
    }
}

fn case_label(case: &Value) -> String {
    let base = match case["names"].as_array() {
        // read_many cases: the names joined by commas.
        Some(names) => names.iter().map(|n| n.as_str().unwrap()).collect::<Vec<_>>().join(","),
        None => case["name"].as_str().unwrap().to_string(),
    };
    let mut parts = vec![base];
    for key in ["group", "start_time", "end_time", "start_record", "record_count", "raw"] {
        match &case[key] {
            Value::Null | Value::Bool(false) => {}
            Value::Bool(true) => parts.push(key.to_string()),
            Value::String(text) => parts.push(format!("{key}={text}")),
            // `1.0` prints as `1`, in every language.
            number => parts.push(format!("{key}={}", number.as_f64().unwrap())),
        }
    }
    parts.join(" ")
}

fn dump(reader: &mut dyn Reader, scenario: &Value) -> Value {
    let mut reads = serde_json::Map::new();
    for case in scenario["read_cases"].as_array().unwrap() {
        let options = case_options(case);
        let name = case["name"].as_str().unwrap();
        let read = match reader.read(name, &options) {
            Ok(signal) => signal_json(&signal),
            Err(e) => error_kind(&e),
        };
        let values = match reader.values(name, &options) {
            Ok(values) => floats(&values),
            Err(e) => error_kind(&e),
        };
        reads.insert(case_label(case), serde_json::json!({ "read": read, "values": values }));
    }
    let mut many = serde_json::Map::new();
    for case in scenario["read_many_cases"].as_array().unwrap() {
        let names: Vec<&str> = case["names"].as_array().unwrap().iter().map(|n| n.as_str().unwrap()).collect();
        let result = match reader.read_many(&names, &case_options(case)) {
            Ok(signals) => Value::from(signals.iter().map(signal_json).collect::<Vec<_>>()),
            Err(e) => error_kind(&e),
        };
        many.insert(case_label(case), result);
    }
    let mut channels = serde_json::Map::new();
    for case in scenario["channel_cases"].as_array().unwrap() {
        let (name, group) = (case["name"].as_str().unwrap(), case["group"].as_str());
        let time_range = match reader.time_range(name, group) {
            Ok(range) => serde_json::to_value(range.map(|r| [r.start, r.end])).unwrap(),
            Err(e) => error_kind(&e),
        };
        let conversion = match reader.conversion(name, group) {
            Ok(info) => serde_json::to_value(info).unwrap(),
            Err(e) => error_kind(&e),
        };
        channels.insert(
            case_label(case),
            serde_json::json!({
                "channel": serde_json::to_value(reader.channel(name, group)).unwrap(),
                "time_range": time_range,
                "conversion": conversion,
            }),
        );
    }
    canonical(serde_json::json!({
        "start_time_ns": reader.start_time_ns().map(|ns| ns.to_string()),
        "channel_names": reader.channel_names(),
        "groups": serde_json::to_value(reader.groups()).unwrap(),
        "reads": reads,
        "read_many": many,
        "channels": channels,
    }))
}

#[test]
fn golden_dump_matches() -> Result<(), MdfError> {
    let scenario: Value =
        serde_json::from_str(&std::fs::read_to_string(root().join("tests/contract/scenario.json")).unwrap()).unwrap();
    let dir = tempfile::tempdir().map_err(MdfError::IOError)?;
    let path = dir.path().join("scenario.mf4");
    build_scenario_file(&path)?;
    let path = path.to_str().unwrap();

    let mut mdf = Mdf::from_file(path)?;
    let mut index = MdfIndex::from_file(path)?;
    let from_mdf = dump(&mut mdf, &scenario);
    let from_index = dump(&mut index, &scenario);
    assert_eq!(from_index, from_mdf, "Mdf and MdfIndex disagree");

    let golden_path = root().join("tests/contract/golden.json");
    if std::env::var_os("UPDATE_GOLDEN").is_some() {
        let text = serde_json::to_string_pretty(&from_mdf).unwrap();
        std::fs::write(&golden_path, text + "\n").map_err(MdfError::IOError)?;
    }
    let golden: Value = serde_json::from_str(&std::fs::read_to_string(&golden_path).map_err(MdfError::IOError)?).unwrap();
    assert_eq!(
        from_mdf,
        canonical(golden),
        "the Rust answers differ from tests/contract/golden.json — if the change is intended, \
         regenerate it with UPDATE_GOLDEN=1 and make sure the Python and TypeScript tests still match"
    );
    Ok(())
}

#[test]
fn type_methods_match_the_contract() {
    let contract = contract();
    for (name, file) in [("Signal", "src/signal.rs"), ("GroupInfo", "src/types.rs"), ("ReadOptions", "src/types.rs")] {
        assert_eq!(
            public_methods(&[file], name),
            strings(&contract["types"][name]["methods"]["rust"]),
            "public methods of `{name}` differ from docs/api-contract.json"
        );
    }
}

#[test]
fn integers_are_never_truncated() -> Result<(), MdfError> {
    use mf4_rs::ColumnData;
    let dir = tempfile::tempdir().map_err(MdfError::IOError)?;
    let mut w = MdfWriter::new(dir.path().join("narrow.mf4").to_str().unwrap())?;
    w.init_mdf_file()?;
    let g = w.add_channel_group(None)?;
    w.add_channel(&g, "U32", DataType::UnsignedIntegerLE)?;
    w.add_channel(&g, "I32", DataType::SignedIntegerLE)?;
    // Types the writer cannot encode are refused up front.
    for data_type in [DataType::FloatBE, DataType::UnsignedIntegerBE, DataType::SignedIntegerBE] {
        assert!(matches!(w.add_channel(&g, "x", data_type), Err(MdfError::InvalidArgument(_))));
    }
    w.start_data_block(&g)?;
    let ok = [DecodedValue::UnsignedInteger(u32::MAX as u64), DecodedValue::SignedInteger(i32::MIN as i64)];
    w.write_record(&g, &ok)?;
    w.write_columns(&g, &[ColumnData::U64(&[u32::MAX as u64]), ColumnData::I64(&[i32::MIN as i64])])?;
    let too_big = [DecodedValue::UnsignedInteger(1 << 32), DecodedValue::SignedInteger(0)];
    assert!(matches!(w.write_record(&g, &too_big), Err(MdfError::InvalidArgument(_))));
    let too_small = [DecodedValue::UnsignedInteger(0), DecodedValue::SignedInteger(i32::MIN as i64 - 1)];
    assert!(matches!(w.write_record(&g, &too_small), Err(MdfError::InvalidArgument(_))));
    let columns = [ColumnData::U64(&[1 << 32]), ColumnData::I64(&[0])];
    assert!(matches!(w.write_columns(&g, &columns), Err(MdfError::InvalidArgument(_))));
    let columns = [ColumnData::U64(&[0]), ColumnData::I64(&[1 << 31])];
    assert!(matches!(w.write_columns(&g, &columns), Err(MdfError::InvalidArgument(_))));
    w.finish_data_block(&g)?;

    // An all-unsigned group through the u64 fast path, and an odd bit width.
    let g = w.add_channel_group(None)?;
    w.add_channel_with(&g, None, |ch| {
        ch.data_type = DataType::UnsignedIntegerLE;
        ch.name = Some("U12".to_string());
        ch.bit_count = 12;
    })?;
    w.start_data_block(&g)?;
    w.write_record_u64(&g, &[4095])?;
    assert!(matches!(w.write_record_u64(&g, &[4096]), Err(MdfError::InvalidArgument(_))));
    assert!(matches!(
        w.write_record(&g, &[DecodedValue::UnsignedInteger(5000)]),
        Err(MdfError::InvalidArgument(_))
    ));
    w.finish_data_block(&g)?;
    w.finalize()
}

#[test]
fn a_refused_record_leaves_no_trace() -> Result<(), MdfError> {
    let dir = tempfile::tempdir().map_err(MdfError::IOError)?;
    let path = dir.path().join("refused.mf4");
    let mut w = MdfWriter::new(path.to_str().unwrap())?;
    w.init_mdf_file()?;
    let g = w.add_channel_group(None)?;
    w.add_time_channel(&g, "t")?;
    w.add_string_channel(&g, "s")?;
    w.add_channel(&g, "u", DataType::UnsignedIntegerLE)?;
    w.start_data_block(&g)?;
    let record = |t: f64, s: &str, u: u64| {
        [DecodedValue::Float(t), DecodedValue::String(s.to_string()), DecodedValue::UnsignedInteger(u)]
    };
    w.write_record(&g, &record(0.0, "a", 1))?;
    // The text value is encoded before the integer is refused.
    assert!(w.write_record(&g, &record(1.0, "ORPHAN", 1 << 33)).is_err());
    w.write_record(&g, &record(2.0, "b", 2))?;
    // A batch that fails midway keeps the records before the refused one.
    let batch = [record(3.0, "c", 3), record(4.0, "ORPHAN", 1 << 33), record(5.0, "never", 5)];
    assert!(w.write_records(&g, batch.iter().map(|r| r.as_slice())).is_err());
    // …also when the refused record merely has the wrong number of values.
    let short = [DecodedValue::Float(8.0)];
    let first = record(7.0, "e", 7);
    assert!(w.write_records(&g, [first.as_slice(), short.as_slice()]).is_err());
    w.write_record(&g, &record(6.0, "d", 6))?;
    w.finish_data_block(&g)?;

    let g = w.add_channel_group(None)?;
    w.add_channel(&g, "n", DataType::UnsignedIntegerLE)?;
    w.start_data_block(&g)?;
    let batch: [&[u64]; 3] = [&[1], &[2], &[1 << 40]];
    assert!(w.write_records_u64(&g, batch).is_err());
    // A record with the wrong number of values is refused the same way.
    let batch: [&[u64]; 3] = [&[3], &[4, 5], &[6]];
    assert!(w.write_records_u64(&g, batch).is_err());
    w.write_record_u64(&g, &[7])?;
    w.finish_data_block(&g)?;
    w.finalize()?;

    let path = path.to_str().unwrap();
    let mdf = Mdf::from_file(path)?;
    let index = MdfIndex::from_file(path)?;
    for signal in [mdf.read("s", None)?, index.read("s", None)?] {
        let text: Vec<_> = signal.values.iter().map(|v| format!("{v:?}")).collect();
        assert_eq!(signal.timestamps, [0.0, 2.0, 3.0, 7.0, 6.0]);
        assert_eq!(text.len(), 5, "{text:?}");
        assert!(!text.iter().any(|t| t.contains("ORPHAN")), "{text:?}");
    }
    assert_eq!(mdf.values("u", None)?, [1.0, 2.0, 3.0, 7.0, 6.0]);
    assert_eq!(mdf.values("n", None)?, [1.0, 2.0, 3.0, 7.0]);
    assert_eq!(index.values("n", None)?, [1.0, 2.0, 3.0, 7.0]);
    Ok(())
}