Skip to main content

saturnus_core/
state.rs

1//! Save and load the complete mutable state of a [`Machine`].
2//!
3//! A small versioned little-endian binary format, written and parsed by
4//! hand so the core crate stays dependency-free. Layout, in order:
5//!
6//! | Field | Encoding |
7//! | --- | --- |
8//! | magic | the 8 bytes `SATURNUS` |
9//! | version | u16, currently 2 |
10//! | model | u8 (0 = HP48 SX, 1 = HP48 GX, 2 = HP49G, 3 = HP 38G, 4 = HP 39G, 5 = HP 40G, 6 = HP 42S, 7 = HP 27S, 8 = HP 17BII, 9 = HP 17B, 10 = HP 28S) |
11//! | ROM checksum | u64, FNV-1a over the NCE1 nibbles |
12//! | CPU | A B C D, R0-R4 (u64); D0 D1 PC (u32); P (u8); ST (u16); HST (u8); carry, mode (u8); OUT, IN (u16); RSTK 8 x u32 top first; INTON, in service, pending (u8) |
13//! | memory controller | 5 chips in daisy-chain order: size flag + u32, base flag + u32, last u32 |
14//! | RAM | NCE2 nibble block, then CE1, CE2, NCE3 nibble blocks (built-in RAM behind those chips; length 0 where there is none) |
15//! | bank latch | u8 (6 bits) |
16//! | NCE1 device | byte block from `Nce1::state_blob`: empty for ROM; on the 49G the flash's lock-bits u32, status u8, read mode u8 (0 array, 1 identifier, 2 query, 3 status, 4 extended status), WP# u8, then the 2 MB array packed |
17//! | I/O | 64 register nibbles; TIMER1 u8, TIMER2 u32, control u8 x 2, TIMER1 phase u32, IRQ levels and edge, TIMER2 pending (u8 x 4); CRC u16; row, row phase, line count u8; KDN u8; card pins u8; card edge u8; UART (below) |
18//! | UART | BAU, IOC, RCS, TCS u8; RBR, TBR u8; 16x accumulator u64; 16x phase u8; wire frame, shifter frame (present u8, then byte u8, position u16, live u8); break present u8 + position u16; IRQ level, edge u8; inbound and outbound byte blocks |
19//! | keyboard | 9 rows, a u8 each (6 IN bits on the 48 matrix, 8 on the 49G's, 7 on the 42S's), a u16 each on the 28S (12 IN bits); ON u8 |
20//! | OUT | u16 |
21//! | cards | per port 1, 2: present u8, then writable u8 and a nibble block (power of two, at most the model's size for the port) |
22//! | machine | shutdown u8; cycles, tick accumulator, stall accumulator u64; scan accumulator u32; key level, ON, timer, key, card, UART edges u8 |
23//! | Lewis block | Lewis models only: nibble block of the 1024 nibbles at #40000 (the 28S's master chip: #FFC00) (display RAM and register storage; the timers and CRC are in the I/O section) |
24//! | Lewis slave | 28S only: nibble block of the slave chip's 1024 nibbles at #FF800, then its timers (as in the I/O section: TIMER1 u8, TIMER2 u32, control u8 x 2, TIMER1 phase u32, IRQ levels and edge u8 x 3) |
25//!
26//! A nibble block is a u32 nibble count followed by the nibbles packed two
27//! per byte, low nibble first. A byte block is a u32 count followed by the
28//! bytes. Booleans are 0 or 1. Parsing checks every
29//! length and range and returns [`Error::InvalidState`] instead of
30//! panicking; trailing bytes are an error. A state only loads into a
31//! machine of the same model built from the same ROM.
32
33use crate::bus::MemoryController;
34use crate::cpu::{ADDR_MASK, Mode, Registers, ReturnStack};
35use crate::error::Error;
36use crate::io::uart::{BYTE_DONE_16THS, FRAME_16THS, Frame};
37use crate::io::{IoRegisters, Keyboard, Timers, Uart};
38use crate::machine::{CARD_MIN_BYTES, Card, Hardware, LewisBoard, Machine, Model, Port};
39use crate::modules::Ram;
40
41/// First bytes of every state.
42const MAGIC: &[u8; 8] = b"SATURNUS";
43/// Format version written by this library.
44const VERSION: u16 = 2;
45/// The format version this library writes and reads (the u16 after the
46/// magic): a host that keeps states tells a newer one from a broken one.
47pub const STATE_FORMAT: u16 = VERSION;
48/// Largest cycle counter a state may carry (about 146 million years at
49/// 2 MHz); larger values are corrupt and would overflow the counter.
50pub(crate) const MAX_CYCLES: u64 = u64::MAX / 2;
51
52/// Little-endian byte sink.
53struct Writer {
54    buf: Vec<u8>,
55}
56
57impl Writer {
58    fn u8(&mut self, v: u8) {
59        self.buf.push(v);
60    }
61    fn bool(&mut self, v: bool) {
62        self.buf.push(u8::from(v));
63    }
64    fn u16(&mut self, v: u16) {
65        self.buf.extend_from_slice(&v.to_le_bytes());
66    }
67    fn u32(&mut self, v: u32) {
68        self.buf.extend_from_slice(&v.to_le_bytes());
69    }
70    fn u64(&mut self, v: u64) {
71        self.buf.extend_from_slice(&v.to_le_bytes());
72    }
73    fn opt_u32(&mut self, v: Option<u32>) {
74        self.bool(v.is_some());
75        self.u32(v.unwrap_or(0));
76    }
77    /// Byte count (u32), then the bytes.
78    fn bytes(&mut self, b: impl ExactSizeIterator<Item = u8>) {
79        self.u32(u32::try_from(b.len()).unwrap_or(u32::MAX));
80        self.buf.extend(b);
81    }
82    /// Nibble count (u32), then two nibbles per byte, low first.
83    fn nibbles(&mut self, n: &[u8]) {
84        self.u32(u32::try_from(n.len()).unwrap_or(u32::MAX));
85        for pair in n.chunks(2) {
86            let hi = pair.get(1).copied().unwrap_or(0);
87            self.buf.push((pair[0] & 0xF) | (hi << 4));
88        }
89    }
90}
91
92/// Bounds-checked little-endian reader.
93struct Reader<'a> {
94    data: &'a [u8],
95    pos: usize,
96}
97
98type R<T> = Result<T, Error>;
99
100impl<'a> Reader<'a> {
101    fn err<T>(&self, reason: &'static str) -> R<T> {
102        Err(Error::InvalidState {
103            reason,
104            offset: self.pos,
105        })
106    }
107    fn take(&mut self, n: usize) -> R<&'a [u8]> {
108        let slice = self
109            .pos
110            .checked_add(n)
111            .and_then(|end| self.data.get(self.pos..end));
112        match slice {
113            Some(s) => {
114                self.pos += n;
115                Ok(s)
116            }
117            None => self.err("truncated"),
118        }
119    }
120    fn array<const N: usize>(&mut self) -> R<[u8; N]> {
121        let mut a = [0u8; N];
122        a.copy_from_slice(self.take(N)?);
123        Ok(a)
124    }
125    fn u8(&mut self) -> R<u8> {
126        Ok(self.array::<1>()?[0])
127    }
128    fn u16(&mut self) -> R<u16> {
129        Ok(u16::from_le_bytes(self.array()?))
130    }
131    fn u32(&mut self) -> R<u32> {
132        Ok(u32::from_le_bytes(self.array()?))
133    }
134    fn u64(&mut self) -> R<u64> {
135        Ok(u64::from_le_bytes(self.array()?))
136    }
137    fn bool(&mut self) -> R<bool> {
138        match self.u8()? {
139            0 => Ok(false),
140            1 => Ok(true),
141            _ => self.err("boolean not 0 or 1"),
142        }
143    }
144    /// A u8 that must be `<= max`.
145    fn small(&mut self, max: u8, reason: &'static str) -> R<u8> {
146        let v = self.u8()?;
147        if v > max { self.err(reason) } else { Ok(v) }
148    }
149    /// A u32 that must be `<= max`.
150    fn u32_max(&mut self, max: u32, reason: &'static str) -> R<u32> {
151        let v = self.u32()?;
152        if v > max { self.err(reason) } else { Ok(v) }
153    }
154    fn addr(&mut self) -> R<u32> {
155        self.u32_max(ADDR_MASK, "address above 20 bits")
156    }
157    fn opt_addr(&mut self) -> R<Option<u32>> {
158        let some = self.bool()?;
159        let v = self.addr()?;
160        Ok(some.then_some(v))
161    }
162    /// A nibble block; its length must satisfy `len_ok`.
163    fn nibbles(&mut self, len_ok: impl Fn(usize) -> bool) -> R<Vec<u8>> {
164        let n = self.u32()? as usize;
165        if !len_ok(n) {
166            return self.err("unexpected nibble block length");
167        }
168        let bytes = self.take(n.div_ceil(2))?;
169        let mut out = Vec::with_capacity(n);
170        for &b in bytes {
171            out.push(b & 0xF);
172            out.push(b >> 4);
173        }
174        out.truncate(n);
175        Ok(out)
176    }
177    /// A byte block.
178    fn bytes(&mut self) -> R<Vec<u8>> {
179        let n = self.u32()? as usize;
180        Ok(self.take(n)?.to_vec())
181    }
182    /// A u16 that must be `<= max`.
183    fn u16_max(&mut self, max: u16, reason: &'static str) -> R<u16> {
184        let v = self.u16()?;
185        if v > max { self.err(reason) } else { Ok(v) }
186    }
187    fn finish(&self) -> R<()> {
188        if self.pos == self.data.len() {
189            Ok(())
190        } else {
191            self.err("trailing bytes")
192        }
193    }
194}
195
196fn model_code(m: Model) -> u8 {
197    match m {
198        Model::Hp48sx => 0,
199        Model::Hp48gx => 1,
200        Model::Hp49g => 2,
201        Model::Hp38g => 3,
202        Model::Hp39g => 4,
203        Model::Hp40g => 5,
204        Model::Hp42s => 6,
205        Model::Hp27s => 7,
206        Model::Hp17bii => 8,
207        Model::Hp17b => 9,
208        Model::Hp28s => 10,
209        Model::Hp19bii => 11,
210    }
211}
212
213/// FNV-1a over the ROM nibbles; binds a state to its ROM. The machine
214/// computes it once at construction.
215pub(crate) fn rom_checksum(nibbles: &[u8]) -> u64 {
216    nibbles.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &n| {
217        (h ^ u64::from(n)).wrapping_mul(0x0000_0100_0000_01B3)
218    })
219}
220
221fn write_cpu(w: &mut Writer, r: &Registers) {
222    for v in [r.a, r.b, r.c, r.d] {
223        w.u64(v);
224    }
225    for v in r.r {
226        w.u64(v);
227    }
228    for v in [r.d0, r.d1, r.pc] {
229        w.u32(v);
230    }
231    w.u8(r.p);
232    w.u16(r.st);
233    w.u8(r.hst);
234    w.bool(r.carry);
235    w.u8(match r.mode {
236        Mode::Hex => 0,
237        Mode::Dec => 1,
238    });
239    w.u16(r.out);
240    w.u16(r.inp);
241    for &l in r.rstk.levels() {
242        w.u32(l);
243    }
244    w.bool(r.interrupts_enabled);
245    w.bool(r.in_interrupt);
246    w.bool(r.interrupt_pending);
247}
248
249fn read_cpu(rd: &mut Reader) -> R<Registers> {
250    // Struct literal fields evaluate in source order, matching write_cpu.
251    let mut r = Registers {
252        a: rd.u64()?,
253        b: rd.u64()?,
254        c: rd.u64()?,
255        d: rd.u64()?,
256        r: [rd.u64()?, rd.u64()?, rd.u64()?, rd.u64()?, rd.u64()?],
257        d0: rd.addr()?,
258        d1: rd.addr()?,
259        pc: rd.addr()?,
260        p: rd.small(15, "P above 15")?,
261        st: rd.u16()?,
262        hst: rd.small(15, "HST above 4 bits")?,
263        carry: rd.bool()?,
264        ..Registers::default()
265    };
266    r.mode = match rd.u8()? {
267        0 => Mode::Hex,
268        1 => Mode::Dec,
269        _ => return rd.err("unknown arithmetic mode"),
270    };
271    r.out = rd.u16()?;
272    if r.out > crate::cpu::regs::OUT_MASK {
273        return rd.err("OUT above 12 bits");
274    }
275    r.inp = rd.u16()?;
276    let mut levels = [0u32; 8];
277    for l in &mut levels {
278        *l = rd.addr()?;
279    }
280    r.rstk = ReturnStack::from_levels(levels);
281    r.interrupts_enabled = rd.bool()?;
282    r.in_interrupt = rd.bool()?;
283    r.interrupt_pending = rd.bool()?;
284    Ok(r)
285}
286
287fn write_mc(w: &mut Writer, mc: &MemoryController) {
288    for c in &mc.chips {
289        w.opt_u32(c.size);
290        w.opt_u32(c.base);
291        w.u32(c.last);
292    }
293}
294
295fn read_mc(rd: &mut Reader) -> R<MemoryController> {
296    let mut mc = MemoryController::new();
297    for c in &mut mc.chips {
298        c.size = rd.opt_addr()?;
299        c.base = rd.opt_addr()?;
300        c.last = rd.addr()?;
301    }
302    Ok(mc)
303}
304
305fn write_timers(w: &mut Writer, t: &Timers) {
306    w.u8(t.t1);
307    w.u32(t.t2);
308    w.u8(t.t1_ctrl);
309    w.u8(t.t2_ctrl);
310    w.u32(t.t1_phase);
311    w.bool(t.t1_irq);
312    w.bool(t.t2_irq);
313    w.bool(t.irq_edge);
314}
315
316fn read_timers(rd: &mut Reader) -> R<Timers> {
317    let mut t = Timers::new();
318    t.t1 = rd.small(15, "TIMER1 above 4 bits")?;
319    t.t2 = rd.u32()?;
320    t.t1_ctrl = rd.small(7, "timer control above 3 bits")?;
321    t.t2_ctrl = rd.small(7, "timer control above 3 bits")?;
322    t.t1_phase = rd.u32_max(
323        crate::io::timers::T2_TICKS_PER_T1_TICK - 1,
324        "TIMER1 phase out of range",
325    )?;
326    t.t1_irq = rd.bool()?;
327    t.t2_irq = rd.bool()?;
328    t.irq_edge = rd.bool()?;
329    Ok(t)
330}
331
332fn write_io(w: &mut Writer, io: &IoRegisters) {
333    for &n in &io.regs {
334        w.u8(n);
335    }
336    write_timers(w, &io.timers);
337    // Was the TIMER2 "pending read" flag; kept so saved states load.
338    w.bool(false);
339    w.u16(io.crc);
340    w.u8(io.row);
341    w.u8(io.row_phase);
342    w.u8(io.line_count);
343    w.bool(io.kdn);
344    w.u8(io.card_status);
345    w.bool(io.card_edge);
346    write_uart(w, &io.uart);
347}
348
349fn write_frame(w: &mut Writer, f: Option<Frame>) {
350    w.bool(f.is_some());
351    if let Some(f) = f {
352        w.u8(f.byte);
353        w.u16(f.pos);
354        w.bool(f.live);
355    }
356}
357
358fn read_frame(rd: &mut Reader) -> R<Option<Frame>> {
359    if !rd.bool()? {
360        return Ok(None);
361    }
362    Ok(Some(Frame {
363        byte: rd.u8()?,
364        pos: rd.u16_max(FRAME_16THS - 1, "UART frame position out of range")?,
365        live: rd.bool()?,
366    }))
367}
368
369fn write_uart(w: &mut Writer, u: &Uart) {
370    for v in [u.bau, u.ioc, u.rcs, u.tcs, u.rbr, u.tbr] {
371        w.u8(v);
372    }
373    w.u64(u.acc);
374    w.u8(u.phase);
375    write_frame(w, u.wire);
376    write_frame(w, u.tx);
377    w.bool(u.brk.is_some());
378    w.u16(u.brk.unwrap_or(0));
379    w.bool(u.irq_level);
380    w.bool(u.irq_edge);
381    w.bytes(u.inbound.iter().copied());
382    w.bytes(u.outbound.iter().copied());
383}
384
385fn read_uart(rd: &mut Reader, clock_hz: u32) -> R<Uart> {
386    let mut u = Uart::new();
387    u.bau = rd.small(7, "baud code above 3 bits")?;
388    u.ioc = rd.small(15, "UART register above 4 bits")?;
389    u.rcs = rd.small(15, "UART register above 4 bits")?;
390    u.tcs = rd.small(15, "UART register above 4 bits")?;
391    u.rbr = rd.u8()?;
392    u.tbr = rd.u8()?;
393    u.acc = rd.u64()?;
394    if u.acc >= u64::from(clock_hz) {
395        return rd.err("UART accumulator out of range");
396    }
397    u.phase = rd.small(15, "UART clock phase above 15")?;
398    u.wire = read_frame(rd)?;
399    u.tx = read_frame(rd)?;
400    let brk = rd.bool()?;
401    let pos = rd.u16_max(BYTE_DONE_16THS, "UART break position out of range")?;
402    u.brk = brk.then_some(pos);
403    u.irq_level = rd.bool()?;
404    u.irq_edge = rd.bool()?;
405    u.inbound = rd.bytes()?.into();
406    u.outbound = rd.bytes()?;
407    Ok(u)
408}
409
410fn read_io(rd: &mut Reader, clock_hz: u32) -> R<IoRegisters> {
411    let mut io = IoRegisters::new();
412    for n in &mut io.regs {
413        *n = rd.small(15, "I/O register above 4 bits")?;
414    }
415    io.timers = read_timers(rd)?;
416    rd.bool()?;
417    io.crc = rd.u16()?;
418    io.row = rd.small(63, "display row above 63")?;
419    io.row_phase = rd.small(1, "display row phase above 1")?;
420    io.line_count = rd.small(63, "line count above 63")?;
421    io.kdn = rd.bool()?;
422    io.card_status = rd.small(15, "card status above 4 bits")?;
423    io.card_edge = rd.bool()?;
424    io.uart = read_uart(rd, clock_hz)?;
425    Ok(io)
426}
427
428fn write_cards(w: &mut Writer, hw: &Hardware) {
429    for port in Port::ALL {
430        match hw.card(port) {
431            Some(c) => {
432                w.bool(true);
433                w.bool(c.writable);
434                w.nibbles(c.ram.as_slice());
435            }
436            None => w.bool(false),
437        }
438    }
439}
440
441fn read_card(rd: &mut Reader, max_bytes: usize) -> R<Option<Card>> {
442    if !rd.bool()? {
443        return Ok(None);
444    }
445    if max_bytes == 0 {
446        return rd.err("card in a port the model does not have");
447    }
448    let writable = rd.bool()?;
449    let nibbles =
450        rd.nibbles(|n| n.is_power_of_two() && (2 * CARD_MIN_BYTES..=2 * max_bytes).contains(&n))?;
451    let mut ram = Ram::new(nibbles.len());
452    ram.as_mut_slice().copy_from_slice(&nibbles);
453    Ok(Some(Card { ram, writable }))
454}
455
456impl Machine {
457    /// Serialize the complete mutable state (a versioned binary format,
458    /// documented in the crate's `src/state.rs`).
459    /// The ROM is not included; [`Machine::load_state`] needs a machine
460    /// built from the same ROM.
461    pub fn save_state(&self) -> Vec<u8> {
462        let mut w = Writer {
463            buf: Vec::with_capacity(self.hw.ram.len() / 2 + 1024),
464        };
465        w.buf.extend_from_slice(MAGIC);
466        w.u16(VERSION);
467        w.u8(model_code(self.model));
468        w.u64(self.rom_sum);
469        write_cpu(&mut w, &self.cpu.regs);
470        write_mc(&mut w, &self.hw.mc);
471        w.nibbles(self.hw.ram.as_slice());
472        for r in &self.hw.chip_ram {
473            w.nibbles(r.as_slice());
474        }
475        w.u8(self.hw.latch);
476        let blob = self.hw.nce1.state_blob();
477        w.bytes(blob.into_iter());
478        write_io(&mut w, &self.hw.io);
479        let wide_rows = self.hw.keyboard.layout().in_mask() > 0xFF;
480        for &r in &self.hw.keyboard.rows {
481            if wide_rows {
482                w.u16(r);
483            } else {
484                w.u8(r as u8);
485            }
486        }
487        w.bool(self.hw.keyboard.on);
488        w.u16(self.hw.out);
489        write_cards(&mut w, &self.hw);
490        w.bool(self.shutdown);
491        w.u64(self.cycles);
492        w.u64(self.tick_acc);
493        w.u64(self.stall_acc);
494        w.u32(self.scan_acc);
495        w.bool(self.key_level);
496        w.bool(self.on_edge);
497        w.bool(self.timer_irq);
498        w.bool(self.key_irq);
499        w.bool(self.card_irq);
500        w.bool(self.uart_irq);
501        if self.hw.profile().lewis.is_some() {
502            w.nibbles(&self.hw.lewis.mem);
503        }
504        if self.hw.profile().lewis == Some(LewisBoard::Clamshell) {
505            w.nibbles(&self.hw.lewis_slave.mem);
506            write_timers(&mut w, &self.hw.lewis_slave.timers);
507        }
508        w.buf
509    }
510
511    /// Replace the machine's state with one from [`Machine::save_state`].
512    /// On error the machine is left unchanged.
513    pub fn load_state(&mut self, data: &[u8]) -> Result<(), Error> {
514        let mut rd = Reader { data, pos: 0 };
515        if rd.take(MAGIC.len())? != MAGIC {
516            return Err(Error::InvalidState {
517                reason: "not a Saturnus state (bad magic)",
518                offset: 0,
519            });
520        }
521        if rd.u16()? != VERSION {
522            return rd.err("unsupported state version");
523        }
524        if rd.u8()? != model_code(self.model) {
525            return Err(Error::StateModelMismatch);
526        }
527        if rd.u64()? != self.rom_sum {
528            return Err(Error::StateRomMismatch);
529        }
530        let regs = read_cpu(&mut rd)?;
531        let mc = read_mc(&mut rd)?;
532        let ram_len = self.hw.ram.len();
533        let ram_nibbles = rd.nibbles(|n| n == ram_len)?;
534        let mut chip_ram = self.hw.chip_ram.clone();
535        for r in &mut chip_ram {
536            let len = r.len();
537            let n = rd.nibbles(|n| n == len)?;
538            r.as_mut_slice().copy_from_slice(&n);
539        }
540        let latch = rd.small(0x3F, "bank latch above 6 bits")?;
541        let blob = rd.bytes()?;
542        // Parsed against the device, installed with the rest below: no
543        // copy of the ROM or flash.
544        let nce1 = match self.hw.nce1.parse_state_blob(&blob) {
545            Ok(n) => n,
546            Err(reason) => return rd.err(reason),
547        };
548        let io = read_io(&mut rd, self.model.clock_hz())?;
549        let mut keyboard = Keyboard::with_layout(self.hw.keyboard.layout());
550        // The 48 matrix has 6 IN lines, the 49G's 8, the 28S's 12 (a u16
551        // per row).
552        let row_max = keyboard.layout().in_mask();
553        const ROW_REASON: &str = "keyboard row has an IN bit the model lacks";
554        for r in &mut keyboard.rows {
555            *r = match u8::try_from(row_max) {
556                Ok(max) => u16::from(rd.small(max, ROW_REASON)?),
557                Err(_) => rd.u16_max(row_max, ROW_REASON)?,
558            };
559        }
560        keyboard.on = rd.bool()?;
561        let out = rd.u16()?;
562        if out > crate::cpu::regs::OUT_MASK {
563            return rd.err("OUT above 12 bits");
564        }
565        let cards = [
566            read_card(&mut rd, self.model.card_max_bytes(Port::One))?,
567            read_card(&mut rd, self.model.card_max_bytes(Port::Two))?,
568        ];
569        let shutdown = rd.bool()?;
570        let cycles = rd.u64()?;
571        // Keep the counter far from u64::MAX so `advance` and `run_cycles`
572        // cannot overflow or saturate within any plausible run.
573        if cycles > MAX_CYCLES {
574            return rd.err("cycle counter out of range");
575        }
576        let tick_acc = rd.u64()?;
577        if tick_acc >= u64::from(self.model.clock_hz()) {
578            return rd.err("tick accumulator out of range");
579        }
580        let stall_acc = rd.u64()?;
581        if stall_acc >= crate::machine::TIME_FRACTION {
582            return rd.err("stall accumulator out of range");
583        }
584        let scan_acc = rd.u32()?;
585        if scan_acc >= crate::machine::SCAN_TICKS {
586            return rd.err("scan accumulator out of range");
587        }
588        let key_level = rd.bool()?;
589        let on_edge = rd.bool()?;
590        let timer_irq = rd.bool()?;
591        let key_irq = rd.bool()?;
592        let card_irq = rd.bool()?;
593        let uart_irq = rd.bool()?;
594        let lewis = if self.hw.profile().lewis.is_some() {
595            Some(rd.nibbles(|n| n == crate::io::lewis::SIZE)?)
596        } else {
597            None
598        };
599        let slave = if self.hw.profile().lewis == Some(LewisBoard::Clamshell) {
600            let mem = rd.nibbles(|n| n == crate::io::lewis::SIZE)?;
601            Some((mem, read_timers(&mut rd)?))
602        } else {
603            None
604        };
605        rd.finish()?;
606
607        // Everything parsed: commit.
608        self.cpu.regs = regs;
609        self.hw.mc = mc;
610        // A frame held across an UNCNFG is not saved: the loaded mapping
611        // is shown as it is.
612        self.hw.held = None;
613        self.hw.ram.as_mut_slice().copy_from_slice(&ram_nibbles);
614        self.hw.chip_ram = chip_ram;
615        self.hw.latch = latch;
616        self.hw.nce1.commit_state_blob(nce1);
617        self.hw.io = io;
618        // The flash write gate follows #11C bit 3 (wiki: hardware/hp49g).
619        let lcr_on = self.hw.io.lcr() & 0x8 != 0;
620        self.hw.nce1.set_write_enabled(lcr_on);
621        self.hw.keyboard = keyboard;
622        self.hw.out = out;
623        self.hw.cards = cards;
624        self.shutdown = shutdown;
625        self.cycles = cycles;
626        self.tick_acc = tick_acc;
627        self.stall_acc = stall_acc;
628        self.scan_acc = scan_acc;
629        self.key_level = key_level;
630        self.on_edge = on_edge;
631        self.timer_irq = timer_irq;
632        self.key_irq = key_irq;
633        self.card_irq = card_irq;
634        self.uart_irq = uart_irq;
635        if let Some(mem) = lewis {
636            self.hw.lewis.mem = mem;
637        }
638        if let Some((mem, timers)) = slave {
639            self.hw.lewis_slave.mem = mem;
640            self.hw.lewis_slave.timers = timers;
641        }
642        Ok(())
643    }
644}
645
646#[cfg(test)]
647mod tests;