saturnus-host 0.12.1

Host-side pieces shared by the Saturnus emulator's front ends: the emulator with its key queue, command-line typing, hidden Kermit transfers, key layouts and skins, ROM identification
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
//! Which calculator a ROM image belongs to, by its content, and which
//! remembered slots a batch of images fills: one set of rules for every
//! host (the Worker through `saturnus-web`'s `identify_rom` and
//! `plan_roms`, the desktop app natively). No I/O, so it builds for `wasm32`.
//!
//! An image is **exact** when its SHA-256 is one of the images Saturnus
//! knows ([`KNOWN`]: those `saturnus rom fetch` downloads and the 49G
//! fallback), which names its models and revision. The same table holds
//! where hpcalc.org offers each image ([`download`]), for the CLI's `rom
//! fetch`, the desktop app's download and the web page's links. Otherwise it **fits**
//! the models whose loader takes its size and form (packed, or unpacked
//! with one nibble per byte), or it is **unknown**. The 39G and 40G share
//! one image. Nothing ambiguous is assigned without the user's say
//! ([`plan`]).

use saturnus_core::Model;
use serde_json::{Value, json};

use crate::sha256;

/// A ROM image Saturnus knows, and where hpcalc.org offers it. hpcalc.org
/// hosts the 48 and 49 images with HP's permission for emulator use (since
/// 2000); the 38G and 39G/40G images are HP's update files mirrored there.
/// Saturnus never hosts or proxies an image: the CLI and the desktop app
/// download from `url` on the user's machine after a confirmation, the web
/// page links to `page` (kb: iterations/iteration-20b-rom-download).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct KnownRom {
    /// SHA-256 of the image, lowercase hex.
    pub sha256: &'static str,
    /// The models that run it.
    pub models: &'static [Model],
    /// Its revision.
    pub revision: &'static str,
    /// The image's name inside the zip, and on disk.
    pub file: &'static str,
    /// The image's size in bytes.
    pub size: usize,
    /// The zip on hpcalc.org holding `file`.
    pub url: &'static str,
    /// hpcalc.org's page about the download, to link.
    pub page: &'static str,
}

/// The ROM images Saturnus knows; per model the first one listed is the
/// one it downloads ([`download`]). Observed on hpcalc.org on 2026-10-05
/// (the pages on 2026-10-08).
pub const KNOWN: [KnownRom; 6] = [
    KnownRom {
        sha256: "e5eb3af020e4910f35a7580a705cf0a46f3ba9d7ba5516582d98010c93af7c74",
        models: &[Model::Hp48sx],
        revision: "48SX J",
        file: "sxrom-j",
        size: 256 * 1024,
        url: "https://www.hpcalc.org/hp48/pc/emulators/sxrom-j.zip",
        page: "https://www.hpcalc.org/details/4371",
    },
    KnownRom {
        sha256: "de3a5a07b0f00640f4ba3599ea4092e9473113aad75c04bd03d3e37c059b5b33",
        models: &[Model::Hp48gx],
        revision: "48GX R",
        file: "gxrom-r",
        size: 512 * 1024,
        url: "https://www.hpcalc.org/hp48/pc/emulators/gxrom-r.zip",
        page: "https://www.hpcalc.org/details/4368",
    },
    // Packed; its I/O window (#00100-#0013F) is already zeroed.
    KnownRom {
        sha256: "3c9f747f637757d3adc414ed14d7f3636033f34f0a72e6e453ee197987f16be7",
        models: &[Model::Hp38g],
        revision: "38G A1.67",
        file: "38G_A167.ROM",
        size: 512 * 1024,
        url: "https://www.hpcalc.org/hp38/pc/38grom.zip",
        page: "https://www.hpcalc.org/details/4775",
    },
    // The image the saturnng 49g oracle runs: the whole 2 MB flash,
    // packed. Its readme labels it for the 48gII/49g+/50g and its boot
    // sector is not the original 49G one, but it boots as a 49G (kb:
    // iteration 5).
    KnownRom {
        sha256: "b01c13e24a692f35e6087106d58ec205b4696d5b5e35d57f8f94015f8bb1f1ca",
        models: &[Model::Hp49g],
        revision: "49G 2.15",
        file: "rom.49g",
        size: 2 * 1024 * 1024,
        url: "https://www.hpcalc.org/hp49/pc/rom/hp4950emurom.zip",
        page: "https://www.hpcalc.org/details/6744",
    },
    // The fallback with the original 49G boot sector, downloaded by hand.
    KnownRom {
        sha256: "58c3de6b7fc75a0ba65fca7437c4d49d8f26ca9e334a57e4d3bc4f8fb2dc8c11",
        models: &[Model::Hp49g],
        revision: "49G 2.10",
        file: "rom.49g",
        size: 2 * 1024 * 1024,
        url: "https://www.hpcalc.org/hp49/pc/rom/hp4950v210.zip",
        page: "https://www.hpcalc.org/details/8888",
    },
    // One image for both models: the 1 MB ROM unpacked, one nibble per
    // byte, with the I/O window of an upload at #00100-#0013F, which the
    // machine zeroes when it loads the image.
    KnownRom {
        sha256: "69220f42d5e90dd8825e7d1596d9eaca490ee6a7a52a3b8b96469a5f3d3f627f",
        models: &[Model::Hp39g, Model::Hp40g],
        revision: "39G/40G (hpcalc rom3940)",
        file: "rom.39g",
        size: 2 * 1024 * 1024,
        url: "https://www.hpcalc.org/hp39/pc/rom3940.zip",
        page: "https://www.hpcalc.org/details/6739",
    },
];

/// The revision of the image with SHA-256 `sha256`, if Saturnus knows it.
pub fn revision(sha256: &str) -> Option<&'static str> {
    KNOWN
        .iter()
        .find(|k| k.sha256 == sha256)
        .map(|k| k.revision)
}

/// The image Saturnus downloads for `model`, or `None` for the Pioneers
/// (42S, 27S, 17BII, 17B): HP never released their ROMs and no site may offer them; the owner
/// dumps their own calculator (kb: iteration 15).
pub fn download(model: Model) -> Option<&'static KnownRom> {
    KNOWN.iter().find(|k| k.models.contains(&model))
}

/// [`download`] as JSON for the pages: `{file, size, url, page, revision}`,
/// or `null`.
pub fn download_json(model: Model) -> Value {
    download(model).map_or(Value::Null, |k| {
        json!({"file": k.file, "size": k.size, "url": k.url, "page": k.page, "revision": k.revision})
    })
}

/// What an image is.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Identity {
    /// A known image: the models that run it and its revision.
    Exact {
        models: Vec<Model>,
        revision: &'static str,
    },
    /// Not known, but its size and form fit these models (one or more).
    Fits(Vec<Model>),
    /// No model takes it.
    Unknown,
}

impl Identity {
    /// The models the image could be for.
    pub fn models(&self) -> &[Model] {
        match self {
            Identity::Exact { models, .. } | Identity::Fits(models) => models,
            Identity::Unknown => &[],
        }
    }
}

/// An identified image.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RomId {
    pub sha256: String,
    pub identity: Identity,
}

impl RomId {
    /// The revision of an exact image.
    pub fn revision(&self) -> Option<&'static str> {
        match self.identity {
            Identity::Exact { revision, .. } => Some(revision),
            _ => None,
        }
    }
}

/// Texts that name a Pioneer model's ROM: a 64 KB image fits the 42S,
/// 27S, 17BII and 17B alike, and a 96 KB one the 17B and 17BII, so the
/// size does not tell them apart. Each is the start of the pass message of
/// that model's self-test, which its main ROM keeps near its end ("OK-42S-",
/// "OK-27S-", "17B II-", "OK-17B-E"; the language ROM of a 96 KB image
/// says "OK-17B-L" on both 17Bs). Checked on the owner's images; wiki:
/// hardware/hp42s, hardware/hp27s, hardware/hp17bii "Self-test". The ROMs
/// keep their messages as ASCII bytes in the packed image. The 28S's
/// self-test passes with "OK-28S", kept from an odd nibble (wiki:
/// hardware/hp28s "Self-test"; seen on the owner's revision 2BB image).
/// The 19BII's self-test passes with "OK-19B II", which its ROM keeps
/// whole (wiki: hardware/hp19bii "Self-test"; seen on the owner's image).
/// Its two halves end "OK-19B-1DK" and "OK-19B-2A", but a bare "OK-19B"
/// could name a 19B ROM too, which Saturnus does not run.
pub const SIGNATURES: [(Model, &str); 6] = [
    (Model::Hp42s, "OK-42S-"),
    (Model::Hp27s, "OK-27S-"),
    (Model::Hp17bii, "17B II-"),
    (Model::Hp17b, "OK-17B-E"),
    (Model::Hp28s, "OK-28S"),
    (Model::Hp19bii, "OK-19B II"),
];

/// Whether the packed image `rom`, or `shifted` (the same image one
/// nibble later), holds `text` as bytes.
fn holds_text(rom: &[u8], shifted: &[u8], text: &str) -> bool {
    let t = text.as_bytes();
    rom.windows(t.len()).any(|w| w == t) || shifted.windows(t.len()).any(|w| w == t)
}

/// The models whose loader takes `rom`, by size and form: a 2 MB file is a
/// packed 49G flash or, when every byte is a nibble, an unpacked 39G/40G;
/// a 4 MB file is an unpacked 49G only when every byte is a nibble. The
/// 48GX and 38G both take 512 KB. A 64 KB image fits the four Pioneers
/// and a 96 KB one the 17B and 17BII, unless it carries exactly one
/// model's [`SIGNATURES`] text, which names it. A 128 KB image fits the
/// 28S or the 19BII only with that model's text: the 28C and 19B ROMs are
/// 128 KB too, and Saturnus runs neither.
pub fn fitting_models(rom: &[u8]) -> Vec<Model> {
    const TWO_MB: usize = 2 * 1024 * 1024;
    let nibbles = || rom.iter().all(|&b| b < 16);
    let unpacked_2mb = rom.len() == TWO_MB && nibbles();
    let fits: Vec<Model> = Model::ALL
        .into_iter()
        .filter(|&m| m.accepts_rom_len(rom.len()))
        .filter(|&m| match m {
            Model::Hp49g if rom.len() == TWO_MB => !unpacked_2mb,
            Model::Hp49g => nibbles(),
            Model::Hp39g | Model::Hp40g if rom.len() == TWO_MB => unpacked_2mb,
            _ => true,
        })
        .collect();
    let clamshell = !fits.is_empty() && fits.iter().all(|m| m.is_lewis() && !m.is_pioneer());
    if (fits.len() > 1 && fits.iter().all(|m| m.is_pioneer())) || clamshell {
        // In address order, so no text is cut at a unit's edge.
        let rom = saturnus_core::pioneer_address_order(rom);
        let shifted: Vec<u8> = rom.windows(2).map(|w| (w[0] >> 4) | (w[1] << 4)).collect();
        let signed: Vec<Model> = SIGNATURES
            .iter()
            .filter(|(m, text)| fits.contains(m) && holds_text(&rom, &shifted, text))
            .map(|&(m, _)| m)
            .collect();
        if let [one] = signed.as_slice() {
            return vec![*one];
        }
        if clamshell {
            return Vec::new();
        }
    }
    fits
}

/// Identify `rom` by its content.
pub fn identify(rom: &[u8]) -> RomId {
    let sha256 = sha256::hex_digest(rom);
    let identity = match KNOWN.iter().find(|k| k.sha256 == sha256) {
        Some(k) => Identity::Exact {
            models: k.models.to_vec(),
            revision: k.revision,
        },
        None => match fitting_models(rom) {
            m if m.is_empty() => Identity::Unknown,
            m => Identity::Fits(m),
        },
    };
    RomId { sha256, identity }
}

/// A file of a batch for [`plan`].
#[derive(Clone, Debug)]
pub struct Candidate {
    /// The file's name, for the notice.
    pub name: String,
    pub identity: Identity,
    /// Chosen by the user (a dialog, the picker, a drop), not found
    /// beside the chosen file.
    pub chosen: bool,
}

/// What to do with a batch: indexes into the candidates.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Plan {
    /// Slot `model` takes candidate `n`.
    pub assign: Vec<(Model, usize)>,
    /// Candidate `n` could be the ROM of these models; the user decides.
    pub offer: Vec<(Vec<Model>, usize)>,
    /// The model to boot: the selected one if it got a ROM, else the
    /// first a chosen file was assigned to.
    pub boot: Option<Model>,
    /// One line for the user: what was assigned besides the boot, what
    /// is offered, and why a chosen file was not taken.
    pub notice: String,
}

fn title(m: Model) -> String {
    m.name().to_uppercase()
}

/// "48GX", "39G and 40G", "48GX or 38G".
fn titles(models: &[Model], conjunction: &str) -> String {
    let t: Vec<String> = models.iter().map(|&m| title(m)).collect();
    match t.as_slice() {
        [] => String::new(),
        [one] => one.clone(),
        [init @ .., last] => format!("{} {conjunction} {last}", init.join(", ")),
    }
}

/// `c` with the models it names cut to [`crate::skins::hosted_models`];
/// unknown when none is left.
fn hosted_only(c: &Candidate) -> Candidate {
    let keep = |ms: &[Model]| -> Vec<Model> {
        ms.iter()
            .copied()
            .filter(|&m| crate::skins::skin(m).is_some())
            .collect()
    };
    let identity = match &c.identity {
        Identity::Unknown => Identity::Unknown,
        Identity::Fits(ms) => match keep(ms) {
            k if k.is_empty() => Identity::Unknown,
            k => Identity::Fits(k),
        },
        Identity::Exact { models, revision } => match keep(models) {
            k if k.is_empty() => Identity::Unknown,
            k => Identity::Exact {
                models: k,
                revision,
            },
        },
    };
    Candidate {
        identity,
        ..c.clone()
    }
}

/// Assign a batch of identified files to the model slots, `selected`
/// being the model the user chose them for and `filled` the slots that
/// already hold a ROM. The rules:
///
/// - A chosen file that is exact fills every slot of its models (the user
///   gave it). One that fits fills `selected` if it fits it, or its one
///   model if it fits only one; one that fits several others is offered.
///   An unknown one is refused in the notice.
/// - A file found beside it that is exact fills the empty slots of its
///   models; one that only fits is offered for its empty slots; an
///   unknown one is left alone. Found files never replace a slot.
/// - Within a batch the first file for a slot wins (hosts sort the found
///   files by name).
pub fn plan(selected: Model, files: &[Candidate], filled: &[Model]) -> Plan {
    // Only models the pages offer get slots: an image of a model without
    // a drawn skin yet (the 28S, iteration 43b) counts as unknown here.
    let files: Vec<Candidate> = files.iter().map(hosted_only).collect();
    let files = files.as_slice();
    let mut plan = Plan::default();
    let taken = |plan: &Plan, m: Model| plan.assign.iter().any(|&(a, _)| a == m);
    let mut refused = Vec::new();
    let mut found = Vec::new();
    // Chosen files first, so they win over found ones.
    let order = files
        .iter()
        .enumerate()
        .filter(|(_, f)| f.chosen)
        .chain(files.iter().enumerate().filter(|(_, f)| !f.chosen));
    for (n, f) in order {
        let empty: Vec<Model> = f
            .identity
            .models()
            .iter()
            .copied()
            .filter(|&m| !taken(&plan, m) && (f.chosen || !filled.contains(&m)))
            .collect();
        match (&f.identity, f.chosen) {
            (Identity::Unknown, true) => refused.push(format!(
                "{} is not a ROM for any model Saturnus supports",
                f.name
            )),
            (Identity::Unknown, false) => {}
            (Identity::Exact { models, .. }, _) => {
                if !f.chosen && !empty.is_empty() {
                    found.push(format!("{} for the {}", f.name, titles(&empty, "and")));
                }
                // A chosen file whose models an earlier chosen file took
                // (two 49G revisions at once) is named, not dropped.
                if f.chosen && empty.is_empty() {
                    refused.push(format!(
                        "{} was not used: another file in the batch is the {} ROM",
                        f.name,
                        titles(models, "and")
                    ));
                }
                plan.assign.extend(empty.iter().map(|&m| (m, n)));
            }
            (Identity::Fits(models), true) => {
                let target = if models.contains(&selected) {
                    Some(selected)
                } else if let [one] = models.as_slice() {
                    Some(*one)
                } else {
                    None
                };
                match target {
                    Some(m) if !taken(&plan, m) => plan.assign.push((m, n)),
                    Some(m) => refused.push(format!(
                        "{} was not used: another file in the batch is the {} ROM",
                        f.name,
                        title(m)
                    )),
                    None => plan.offer.push((models.clone(), n)),
                }
            }
            (Identity::Fits(_), false) => {
                if !empty.is_empty() {
                    plan.offer.push((empty, n));
                }
            }
        }
    }
    let chosen_models = || {
        plan.assign
            .iter()
            .filter(|&&(_, n)| files[n].chosen)
            .map(|&(m, _)| m)
    };
    plan.boot = if chosen_models().any(|m| m == selected) {
        Some(selected)
    } else {
        chosen_models().next()
    };
    let mut parts = Vec::new();
    if !found.is_empty() {
        parts.push(format!("Also found: {}.", found.join(", ")));
    }
    for (models, n) in &plan.offer {
        parts.push(format!(
            "{} could be the {} ROM.",
            files[*n].name,
            titles(models, "or")
        ));
    }
    for r in refused {
        parts.push(format!("{r}."));
    }
    plan.notice = parts.join(" ");
    plan
}

/// [`RomId`] as JSON: `{sha256, kind: "exact"|"fits"|"unknown", models,
/// revision}`.
pub fn rom_id_json(id: &RomId) -> Value {
    let kind = match id.identity {
        Identity::Exact { .. } => "exact",
        Identity::Fits(_) => "fits",
        Identity::Unknown => "unknown",
    };
    let models: Vec<&str> = id.identity.models().iter().map(|m| m.name()).collect();
    json!({"sha256": id.sha256, "kind": kind, "models": models, "revision": id.revision()})
}

fn identity_from_json(v: &Value) -> crate::Result<Identity> {
    let models = v
        .get("models")
        .and_then(Value::as_array)
        .map(|a| {
            a.iter()
                .map(|m| m.as_str().unwrap_or_default().parse::<Model>())
                .collect::<Result<Vec<_>, _>>()
        })
        .transpose()?
        .unwrap_or_default();
    Ok(match v.get("kind").and_then(Value::as_str) {
        Some("exact") => {
            let sha = v.get("sha256").and_then(Value::as_str).unwrap_or_default();
            let revision = revision(sha).ok_or("an exact image of no known revision")?;
            Identity::Exact { models, revision }
        }
        Some("fits") => Identity::Fits(models),
        _ => Identity::Unknown,
    })
}

/// [`plan`] over JSON: `input` is `{selected, filled: [model], files:
/// [{name, chosen, id}]}` with `id` from [`rom_id_json`]; the result is
/// `{assign: [{model, file}], offer: [{models, file}], boot, notice}`.
pub fn plan_json(input: &Value) -> crate::Result<Value> {
    let selected = input
        .get("selected")
        .and_then(Value::as_str)
        .unwrap_or_default()
        .parse::<Model>()?;
    let filled = input
        .get("filled")
        .and_then(Value::as_array)
        .map(|a| {
            a.iter()
                .map(|m| m.as_str().unwrap_or_default().parse::<Model>())
                .collect::<Result<Vec<_>, _>>()
        })
        .transpose()?
        .unwrap_or_default();
    let files = input
        .get("files")
        .and_then(Value::as_array)
        .ok_or("\"files\" is missing")?
        .iter()
        .map(|f| {
            Ok(Candidate {
                name: f
                    .get("name")
                    .and_then(Value::as_str)
                    .unwrap_or_default()
                    .to_string(),
                chosen: f.get("chosen").and_then(Value::as_bool).unwrap_or(false),
                identity: identity_from_json(f.get("id").unwrap_or(&Value::Null))?,
            })
        })
        .collect::<crate::Result<Vec<_>>>()?;
    let p = plan(selected, &files, &filled);
    Ok(json!({
        "assign": p.assign.iter().map(|&(m, n)| json!({"model": m.name(), "file": n})).collect::<Vec<_>>(),
        "offer": p.offer.iter().map(|(ms, n)| json!({
            "models": ms.iter().map(|m| m.name()).collect::<Vec<_>>(),
            "file": n,
        })).collect::<Vec<_>>(),
        "boot": p.boot.map(Model::name),
        "notice": p.notice,
    }))
}

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

    const KB: usize = 1024;

    fn fits(rom: &[u8]) -> Identity {
        identify(rom).identity
    }

    #[test]
    fn synthetic_images_fit_by_size_and_form() {
        assert_eq!(
            fits(&[0; 64 * KB]),
            Identity::Fits(vec![Hp42s, Hp27s, Hp17bii, Hp17b])
        );
        assert_eq!(fits(&[0; 96 * KB]), Identity::Fits(vec![Hp17bii, Hp17b]));
        assert_eq!(fits(&[0; 256 * KB]), Identity::Fits(vec![Hp48sx]));
        assert_eq!(fits(&[0; 512 * KB]), Identity::Fits(vec![Hp48gx, Hp38g]));
        assert_eq!(fits(&[0; 1024 * KB]), Identity::Fits(vec![Hp39g, Hp40g]));
        // 2 MB of nibbles: an unpacked 39G/40G; with a byte above 15, a
        // packed 49G flash.
        let mut two = vec![0x0f; 2048 * KB];
        assert_eq!(fits(&two), Identity::Fits(vec![Hp39g, Hp40g]));
        two[7] = 0x10;
        assert_eq!(fits(&two), Identity::Fits(vec![Hp49g]));
        // 4 MB: an unpacked 49G only if every byte is a nibble.
        let mut four = vec![0u8; 4096 * KB];
        assert_eq!(fits(&four), Identity::Fits(vec![Hp49g]));
        four[0] = 0xff;
        assert_eq!(fits(&four), Identity::Unknown);
        assert_eq!(fits(&[0; 1000]), Identity::Unknown);
        assert_eq!(fits(&[]), Identity::Unknown);
    }

    /// A 64 KB image with one model's signature text is that model's, at
    /// either nibble alignment; with none it fits all four Pioneers. The
    /// images are synthetic: zeros around the text.
    #[test]
    fn signatures_name_a_64_kb_image() {
        let pioneers = vec![Hp42s, Hp27s, Hp17bii, Hp17b];
        for &(model, text) in SIGNATURES.iter().filter(|(m, _)| m.is_pioneer()) {
            let mut rom = vec![0u8; 64 * KB];
            rom[0x7000..0x7000 + text.len()].copy_from_slice(text.as_bytes());
            assert_eq!(fits(&rom), Identity::Fits(vec![model]), "{text}");
            // One nibble later: each byte straddles two.
            let mut shifted = vec![0u8; 64 * KB];
            for (i, b) in text.bytes().enumerate() {
                shifted[0x7000 + i] |= b << 4;
                shifted[0x7001 + i] |= b >> 4;
            }
            assert_eq!(fits(&shifted), Identity::Fits(vec![model]), "{text}");
            // A 96 KB image is the 17B's or the 17BII's.
            let mut big = rom.clone();
            big.resize(96 * KB, 0);
            let want = if matches!(model, Hp17b | Hp17bii) {
                vec![model]
            } else {
                vec![Hp17bii, Hp17b]
            };
            assert_eq!(fits(&big), Identity::Fits(want), "{text}");
        }
        let mut both = vec![0u8; 64 * KB];
        let mut at = 0x100;
        for &(_, text) in &SIGNATURES {
            both[at..at + text.len()].copy_from_slice(text.as_bytes());
            at += 0x100;
        }
        assert_eq!(
            fits(&both),
            Identity::Fits(pioneers.clone()),
            "several signatures name no one"
        );
        assert_eq!(fits(&vec![0x5a; 64 * KB]), Identity::Fits(pioneers));
    }

    /// A 28S image, chosen while another model is shown, fills the 28S's
    /// slot and boots it (iteration 43b gave it a skin); found beside
    /// another file, it is offered for the slot, as any image that only
    /// fits.
    #[test]
    fn a_28s_image_fills_its_slot() {
        let id = Identity::Fits(vec![Hp28s]);
        let p = plan(Hp48sx, &[file("hp28s.rom", id.clone(), true)], &[]);
        assert_eq!(p.boot, Some(Hp28s));
        assert_eq!(p.assign, [(Hp28s, 0)]);
        assert!(p.offer.is_empty());
        let p = plan(Hp48sx, &[file("hp28s.rom", id, false)], &[]);
        assert_eq!(p.offer, [(vec![Hp28s], 0)]);
        assert!(p.assign.is_empty() && p.boot.is_none());
    }

    /// A 128 KB image is the 28S's or the 19BII's only with its text, at
    /// either nibble alignment and in either byte order; without one (a
    /// 28C or 19B ROM) it fits no model.
    #[test]
    fn a_128_kb_image_needs_the_28s_text() {
        let text = b"OK-28S";
        assert_eq!(fits(&vec![0u8; 128 * KB]), Identity::Unknown);
        let mut rom = vec![0u8; 128 * KB];
        for (i, &b) in text.iter().enumerate() {
            rom[0x1F04F + i] |= b << 4;
            rom[0x1F050 + i] |= b >> 4;
        }
        assert_eq!(fits(&rom), Identity::Fits(vec![Hp28s]));
        let mut aligned = vec![0u8; 128 * KB];
        aligned[0x100..0x100 + text.len()].copy_from_slice(text);
        assert_eq!(fits(&aligned), Identity::Fits(vec![Hp28s]));
        let mut bii = vec![0u8; 128 * KB];
        bii[0x1FFF3..0x1FFF3 + 6].copy_from_slice(b"OK-19B");
        assert_eq!(fits(&bii), Identity::Unknown, "a 19B's text is not enough");
        bii[0x16F50..0x16F50 + 9].copy_from_slice(b"OK-19B II");
        assert_eq!(fits(&bii), Identity::Fits(vec![Hp19bii]));
        let mut both = aligned.clone();
        both[0x16F50..0x16F50 + 9].copy_from_slice(b"OK-19B II");
        assert_eq!(fits(&both), Identity::Unknown, "two texts name no one");
        // The same text in a 64 KB image names no Pioneer.
        let mut small = vec![0u8; 64 * KB];
        small[0x100..0x100 + text.len()].copy_from_slice(text);
        assert_eq!(
            fits(&small),
            Identity::Fits(vec![Hp42s, Hp27s, Hp17bii, Hp17b])
        );
    }

    /// An unsigned 64 KB image chosen for a Pioneer goes to that model; for
    /// another model it is offered with the four Pioneers named.
    #[test]
    fn an_unsigned_pioneer_image_is_offered() {
        let all = Identity::Fits(vec![Hp42s, Hp27s, Hp17bii, Hp17b]);
        let p = plan(Hp27s, &[file("dump.rom", all.clone(), true)], &[]);
        assert_eq!(p.boot, Some(Hp27s));
        let p = plan(Hp48sx, &[file("dump.rom", all, true)], &[]);
        assert_eq!(p.boot, None);
        assert_eq!(p.offer, [(vec![Hp42s, Hp27s, Hp17bii, Hp17b], 0)]);
        assert_eq!(
            p.notice,
            "dump.rom could be the 42S, 27S, 17BII or 17B ROM."
        );
    }

    #[test]
    fn known_images_are_exact_and_fit_their_models() {
        for k in KNOWN {
            assert_eq!(k.sha256.len(), 64);
            assert_eq!(revision(k.sha256), Some(k.revision));
            assert!(!k.models.is_empty());
            for &m in k.models {
                assert!(m.accepts_rom_len(k.size), "{}", k.revision);
            }
            assert!(k.url.starts_with("https://www.hpcalc.org/") && k.url.ends_with(".zip"));
            assert!(k.page.starts_with("https://www.hpcalc.org/details/"));
        }
        assert_eq!(revision(&"0".repeat(64)), None);
        let id = identify(b"abc");
        assert_eq!(
            id.sha256,
            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
        );
        assert_eq!(id.revision(), None);
    }

    fn exact(models: &[Model]) -> Identity {
        Identity::Exact {
            models: models.to_vec(),
            revision: "test",
        }
    }

    fn file(name: &str, identity: Identity, chosen: bool) -> Candidate {
        Candidate {
            name: name.into(),
            identity,
            chosen,
        }
    }

    /// One ROM chosen for the 48SX in a folder holding the others: the
    /// exact ones fill their empty slots, the 39G/40G image both; the
    /// unknown file is left alone; the 42S dump only fits, so it is
    /// offered; the slot the user set (the 38G) is kept.
    #[test]
    fn a_chosen_rom_and_its_folder() {
        let files = [
            file("sxrom-j", exact(&[Hp48sx]), true),
            file("38G_A167.ROM", exact(&[Hp38g]), false),
            file("gxrom-r", exact(&[Hp48gx]), false),
            file("hp42s-c.rom", Identity::Fits(vec![Hp42s]), false),
            file("notes.bin", Identity::Unknown, false),
            file("rom-2.10.49g", exact(&[Hp49g]), false),
            file("rom.39g", exact(&[Hp39g, Hp40g]), false),
            file("rom.49g", exact(&[Hp49g]), false),
        ];
        let p = plan(Hp48sx, &files, &[Hp38g]);
        assert_eq!(
            p.assign,
            [(Hp48sx, 0), (Hp48gx, 2), (Hp49g, 5), (Hp39g, 6), (Hp40g, 6)]
        );
        assert_eq!(p.offer, [(vec![Hp42s], 3)]);
        assert_eq!(p.boot, Some(Hp48sx));
        assert_eq!(
            p.notice,
            "Also found: gxrom-r for the 48GX, rom-2.10.49g for the 49G, rom.39g for the 39G and \
             40G. hp42s-c.rom could be the 42S ROM."
        );
        // With every slot filled, a folder offers and assigns nothing.
        let all: Vec<Model> = Model::ALL.to_vec();
        let p = plan(Hp48sx, &files, &all);
        assert_eq!(p.assign, [(Hp48sx, 0)]);
        assert!(p.offer.is_empty());
        assert_eq!(p.notice, "");
    }

    #[test]
    fn chosen_files_by_identity() {
        // A 512 KB unknown image chosen for the 48GX goes there; for the
        // 48SX it is ambiguous: offered, not booted.
        let gx_or_38 = || file("x.rom", Identity::Fits(vec![Hp48gx, Hp38g]), true);
        let p = plan(Hp48gx, &[gx_or_38()], &[]);
        assert_eq!(
            (p.assign.as_slice(), p.boot),
            (&[(Hp48gx, 0)][..], Some(Hp48gx))
        );
        let p = plan(Hp48sx, &[gx_or_38()], &[]);
        assert!(p.assign.is_empty());
        assert_eq!(p.offer, [(vec![Hp48gx, Hp38g], 0)]);
        assert_eq!(p.boot, None);
        assert_eq!(p.notice, "x.rom could be the 48GX or 38G ROM.");
        // A known image chosen for another model boots its own, replacing
        // a slot the user set before.
        let p = plan(Hp48sx, &[file("g", exact(&[Hp48gx]), true)], &[Hp48gx]);
        assert_eq!(
            (p.assign.as_slice(), p.boot),
            (&[(Hp48gx, 0)][..], Some(Hp48gx))
        );
        // A file of one fitting model goes to it.
        let p = plan(Hp48sx, &[file("d", Identity::Fits(vec![Hp42s]), true)], &[]);
        assert_eq!(p.boot, Some(Hp42s));
        // Unknown: refused, nothing assigned.
        let p = plan(Hp48sx, &[file("a.txt", Identity::Unknown, true)], &[]);
        assert!(p.assign.is_empty() && p.boot.is_none());
        assert_eq!(
            p.notice,
            "a.txt is not a ROM for any model Saturnus supports."
        );
        // Several chosen at once (the page's picker): each to its model;
        // the selected one boots; the second file for a slot is not used.
        let files = [
            file("a", exact(&[Hp48gx]), true),
            file("b", exact(&[Hp48sx]), true),
            file("c", Identity::Fits(vec![Hp48sx]), true),
        ];
        let p = plan(Hp48sx, &files, &[]);
        assert_eq!(p.assign, [(Hp48gx, 0), (Hp48sx, 1)]);
        assert_eq!(p.boot, Some(Hp48sx));
        assert_eq!(
            p.notice,
            "c was not used: another file in the batch is the 48SX ROM."
        );
        // Two exact images of one model at once: the first is used, the
        // second named.
        let files = [
            file("rom.49g", exact(&[Hp49g]), true),
            file("rom-2.10.49g", exact(&[Hp49g]), true),
        ];
        let p = plan(Hp49g, &files, &[]);
        assert_eq!(p.assign, [(Hp49g, 0)]);
        assert_eq!(
            p.notice,
            "rom-2.10.49g was not used: another file in the batch is the 49G ROM."
        );
    }

    #[test]
    fn plan_over_json() {
        let id = rom_id_json(&identify(&[0; 256 * KB]));
        assert_eq!(id["kind"], "fits");
        assert_eq!(id["models"], json!(["48sx"]));
        assert_eq!(id["revision"], Value::Null);
        let out = plan_json(&json!({
            "selected": "48sx",
            "filled": [],
            "files": [{"name": "a", "chosen": true, "id": id}],
        }))
        .unwrap();
        assert_eq!(out["assign"], json!([{"model": "48sx", "file": 0}]));
        assert_eq!(out["boot"], "48sx");
        assert!(plan_json(&json!({"selected": "99x", "files": []})).is_err());
    }

    /// Every model but the Pioneers has one download; the 49G's is 2.15, the
    /// 39G and 40G share theirs.
    #[test]
    fn downloads_per_model() {
        for m in Model::ALL {
            match download(m) {
                None => assert!(m.is_lewis(), "{}", m.name()),
                Some(k) => assert!(k.models.contains(&m)),
            }
        }
        assert_eq!(download(Hp49g).map(|k| k.revision), Some("49G 2.15"));
        assert_eq!(download(Hp39g), download(Hp40g));
        assert_eq!(download_json(Hp42s), Value::Null);
        assert_eq!(
            download_json(Hp48sx),
            json!({
                "file": "sxrom-j",
                "size": 262_144,
                "url": "https://www.hpcalc.org/hp48/pc/emulators/sxrom-j.zip",
                "page": "https://www.hpcalc.org/details/4371",
                "revision": "48SX J",
            })
        );
    }

    /// The images of `SATURNUS_ROM_DIR` (skipped without it, each skipped
    /// when missing): six are known exactly; the Pioneers have no published
    /// image, so each dump fits only its model by its signature, in either
    /// order (the 42S's in address order, the others in dump order).
    #[test]
    fn rom_dir_images() {
        let Some(dir) = std::env::var_os("SATURNUS_ROM_DIR") else {
            return;
        };
        let dir = std::path::PathBuf::from(dir);
        let want: [(&str, Identity); 13] = [
            ("sxrom-j", exact(&[Hp48sx])),
            ("gxrom-r", exact(&[Hp48gx])),
            ("38G_A167.ROM", exact(&[Hp38g])),
            ("rom.49g", exact(&[Hp49g])),
            ("rom-2.10.49g", exact(&[Hp49g])),
            ("rom.39g", exact(&[Hp39g, Hp40g])),
            ("hp42s-c.rom", Identity::Fits(vec![Hp42s])),
            ("hp27s.rom", Identity::Fits(vec![Hp27s])),
            ("hp17bii.rom", Identity::Fits(vec![Hp17bii])),
            ("hp17b.rom", Identity::Fits(vec![Hp17b])),
            ("hp28s.rom", Identity::Fits(vec![Hp28s])),
            ("hp28c.rom", Identity::Unknown),
            ("hp19bii.rom", Identity::Fits(vec![Hp19bii])),
        ];
        for (name, identity) in want {
            let Ok(rom) = std::fs::read(dir.join(name)) else {
                eprintln!("{name} not in SATURNUS_ROM_DIR, skipped");
                continue;
            };
            let got = identify(&rom).identity;
            match (&got, &identity) {
                (Identity::Exact { models: a, .. }, Identity::Exact { models: b, .. }) => {
                    assert_eq!(a, b, "{name}")
                }
                _ => assert_eq!(got, identity, "{name}"),
            }
        }
    }
}