Skip to main content

satx_core/
calc.rs

1//! What a user does with a calculator in Kermit server mode: list, change
2//! directory, get, put, run host commands, fetch PICT, backup and restore.
3//!
4//! Everything is built from `C` host commands, `G D` listings, GET and SEND
5//! (wiki: protocols/server-commands). A host command returns the whole stack
6//! as display text and leaves its results on the user's stack, so every
7//! internal query drops what it pushed. A failed command replies `Error: X`
8//! (no E packet) and leaves its arguments on the stack. Evaluating an
9//! undefined name pushes the name and evaluating a variable runs it, so names
10//! are checked against the listing before they are evaluated.
11
12use crate::time::Duration;
13
14use kermit_proto::{Command, OutgoingFile};
15
16use crate::charset::{decode, encode, encode_command};
17use crate::grob::Grob;
18#[cfg(not(target_arch = "wasm32"))]
19use crate::link::{self, Link};
20use crate::object::{HEADER_LEN, KERMIT_PADDING_ALLOWANCE, ObjectType, inspect};
21use crate::object::{object_size, strip_padding, unpack};
22use crate::reply::{Iopar, Listing, StackReply, parse_list, parse_listing, parse_real};
23use crate::reply::{parse_name, parse_stack, parse_string, parse_whole_string};
24use crate::session::KermitCore;
25#[cfg(not(target_arch = "wasm32"))]
26use crate::session::Session;
27use crate::transport::BAUD;
28#[cfg(not(target_arch = "wasm32"))]
29use crate::transport::Transport;
30use crate::xmodem::{
31    XmodemDirection, XmodemPlan, eval_keys, program_text, server_again, stacked_program,
32};
33use crate::{Error, Result};
34
35/// [`Calculator::iopar`]'s command: the user's flags saved and STD set
36/// ([`CalcOps::drop_and_restore_flags`]), IOPAR's items, each a
37/// short real, and their count on level 1. The list itself can be wider
38/// than the 49G's display, which cuts each level at 20 characters (ROM
39/// 1.18: `{ 9600. 0. 0. 0. 3. `) or 22 (2.x: `{9600.,0.,0.,0.,3.,1.}` just
40/// fits, but not in FIX 4). `LIST→` fails on anything but a list and leaves
41/// it on the stack. Every model has it.
42const IOPAR_ITEMS: &str = "RCLF STD IOPAR LIST\u{2192}";
43/// Drops what [`IOPAR_ITEMS`] pushed: `DROPN` takes LIST→'s count from
44/// level 1 and drops that many items, whatever satx made of the reply;
45/// `STOF` puts the flags back.
46const IOPAR_DROP: &str = "DROPN STOF";
47/// [`Calculator::mem`]'s command: the user's flags saved and STD set
48/// ([`CalcOps::drop_and_restore_flags`]), then MEM.
49const MEM_STD: &str = "RCLF STD MEM";
50/// What [`VERSION_CHUNKS`] cuts into: 10 characters, 12 displayed with the
51/// quotes, far below every model's display width.
52const CHUNK: usize = 10;
53/// With `VERSION`'s two strings on the stack (version on level 2,
54/// copyright on level 1): the user's flags saved beneath them and STD
55/// set ([`CalcOps::drop_and_restore_flags`]), the two joined cut into
56/// [`CHUNK`]-character strings (first chunk deepest), and the joined
57/// length on level 1. For the 49G, which cuts the two-line version string
58/// at its display width (`"Version HP49-C\nRevi` on ROM 1.18, of the 29
59/// characters `Version HP49-C\nRevision #1.18`). Where the two meet comes
60/// from the string that arrived whole (the copyright, 19 characters with
61/// its quotes). 70 bytes, one packet (77 at most): the version's length
62/// does not fit in too.
63const VERSION_CHUNKS: &str =
64    "RCLF ROT ROT STD + 1 OVER SIZE FOR k DUP k k 9 + SUB SWAP 10 STEP SIZE";
65/// Temporary variable for [`Calculator::pict`].
66const PICT_VAR: &str = "SATXTMP";
67/// Temporary variable and port-0 object for [`Calculator::backup`].
68const BACKUP_VAR: &str = "SATXBK";
69/// Temporary variable and port-0 object for [`Calculator::restore`].
70pub const RESTORE_VAR: &str = "SATXRS";
71/// Reply timeout for the final `RESTORE`, which never gets a reply (the
72/// session's timeout when that is shorter).
73const RESTORE_TIMEOUT: Duration = Duration::from_secs(3);
74/// A NAK of a host command this soon after it went out is the calculator
75/// rejecting it, not the idle server's NAK
76/// (`Config::first_packet_nak_window`): a `C` of up to ~90 bytes takes
77/// ~94 ms at 9600 baud, and the idle server NAKs once, a server timeout
78/// after its last packet, and then stays silent (measured on Saturnus and
79/// saturnng; real hardware unverified; wiki: protocols/server-commands), so
80/// one that crosses the `C` lands inside 250 ms only by coincidence (the
81/// residual risk, security.md invariant 6).
82const HOST_NAK_WINDOW: Duration = Duration::from_millis(250);
83/// Wait after such a NAK before the one resend it allows, unless an answer
84/// (`S`, short reply or `E`) comes first (`Config::first_packet_nak_grace`; the
85/// session's timeout when that is shorter).
86const HOST_NAK_GRACE: Duration = Duration::from_secs(3);
87/// One byte (10 bits) at the link's [`BAUD`]: a NAK sooner than the `C`'s
88/// length times this after it went out cannot answer it
89/// (`Config::first_packet_nak_byte_time`; ~10 ms for a short command).
90const HOST_BYTE_TIME: Duration = Duration::from_nanos(10_000_000_000 / BAUD as u64);
91
92/// Calculator model, as far as the ROM version text tells.
93#[derive(Clone, Copy, Debug, PartialEq, Eq)]
94pub enum Model {
95    /// HP 48S/SX: no `VERSION` command, no XModem.
96    Hp48Sx,
97    /// HP 48G/GX: `HP48-x, Copyright HP 1993`; XModem with checksum only.
98    Hp48Gx,
99    /// HP 49G: XModem with checksum, HP's CRC (`D`) and 1k blocks.
100    Hp49G,
101    /// HP 38G: no Kermit server; it is the Kermit client of a PC "disk
102    /// drive", asking for `HP38DIR.CUR` first, and has no XModem (wiki:
103    /// protocols/aplet-transfer).
104    Hp38G,
105    /// HP 39G and HP 40G, which run the same ROM and look the same on the
106    /// wire: as the 38G with `HP39DIR.CUR`, and XModem for binary aplets
107    /// ("HP39/40 (Wire)": 128-byte blocks, checksum).
108    Hp39G,
109    /// Anything else.
110    Unknown,
111}
112
113impl Model {
114    /// The model from the `VERSION` text ([`Calculator::version`]): `None`
115    /// is the 48S/SX, which lacks the command; the 48G/GX says
116    /// `HP48-R, Copyright HP 1993`; the 49G says `HP49-C Revision #1.18`
117    /// (ROM 1.x) or `HP48-C Revision #2.15` (2.x) and is told apart by its
118    /// copyright year (1999 or later) or an `HP49`.
119    pub fn from_version(version: Option<&str>) -> Model {
120        let Some(v) = version else {
121            return Model::Hp48Sx;
122        };
123        let year = v
124            .rsplit(|c: char| !c.is_ascii_digit())
125            .find(|w| w.len() == 4)
126            .and_then(|w| w.parse::<u32>().ok());
127        if v.contains("HP49") || year.is_some_and(|y| y >= 1999) {
128            Model::Hp49G
129        } else if v.contains("HP48") {
130            Model::Hp48Gx
131        } else {
132            Model::Unknown
133        }
134    }
135
136    /// The model that asks a "disk drive" for directory file `name`:
137    /// `HP38DIR.` (the 38G) or `HP39DIR.` (the 39G or 40G) and anything
138    /// after, in any case; `None` for other names.
139    pub fn from_directory_file(name: &[u8]) -> Option<Model> {
140        let head = name.get(..8)?.to_ascii_uppercase();
141        match head.as_slice() {
142            b"HP38DIR." => Some(Model::Hp38G),
143            b"HP39DIR." => Some(Model::Hp39G),
144            _ => None,
145        }
146    }
147
148    /// Display name, e.g. `HP 48G/GX`.
149    pub fn name(self) -> &'static str {
150        match self {
151            Model::Hp48Sx => "HP 48S/SX",
152            Model::Hp48Gx => "HP 48G/GX",
153            Model::Hp49G => "HP 49G",
154            Model::Hp38G => "HP 38G",
155            Model::Hp39G => "HP 39G/40G",
156            Model::Unknown => "unknown",
157        }
158    }
159
160    /// Whether the model has XModem: `XRECV`/`XSEND` on the 48G/GX and
161    /// 49G, "HP39/40 (Wire)" for aplets on the 39G and 40G (unknown models
162    /// are given the benefit of the doubt).
163    pub fn has_xmodem(self) -> bool {
164        !matches!(self, Model::Hp48Sx | Model::Hp38G)
165    }
166
167    /// Whether the calculator drives every transfer as the Kermit client
168    /// of a "disk drive" (the 38G, 39G and 40G), instead of running a
169    /// Kermit server the computer drives.
170    pub fn drives_transfers(self) -> bool {
171        matches!(self, Model::Hp38G | Model::Hp39G)
172    }
173}
174
175/// Kermit transfer format, flag -35 on the calculator.
176#[derive(Clone, Copy, Debug, PartialEq, Eq)]
177pub enum TransferMode {
178    /// Flag -35 set: GET returns `HPHP48-x` / `HPHP49-x` + object; PUT of a
179    /// file that is not an HP binary object stores it as a String.
180    Binary,
181    /// Flag -35 clear (a fresh calculator): objects travel as `%%HP:` text.
182    Ascii,
183}
184
185/// What a calculator connection remembers between operations, apart from
186/// the Kermit session.
187#[derive(Debug)]
188pub(crate) struct CalcState {
189    /// Last transfer mode set or read by us; `None` = unknown.
190    pub(crate) mode: Option<TransferMode>,
191    /// State of the generator behind the sync markers.
192    rng: u64,
193}
194
195impl CalcState {
196    /// A fresh state; `seed` makes the sync markers of this connection
197    /// differ from those of an earlier one.
198    pub(crate) fn new(seed: u64) -> Self {
199        CalcState {
200            mode: None,
201            rng: seed,
202        }
203    }
204
205    /// The next sync marker: `SATX-` and six hex digits of a splitmix64
206    /// step (13 characters with the quotes, far below every model's display
207    /// width), plain ASCII without RPL delimiters.
208    fn marker(&mut self) -> String {
209        self.rng = self.rng.wrapping_add(0x9E37_79B9_7F4A_7C15);
210        let mut z = self.rng;
211        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
212        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
213        z ^= z >> 31;
214        format!("SATX-{:06x}", z & 0xFF_FFFF)
215    }
216}
217
218/// The calculator operations as async code on a Kermit core (see
219/// [`crate::machine`]): driven by [`Calculator`] over a transport, or by a
220/// [`Machine`](crate::machine::Machine) from outside.
221pub(crate) struct CalcOps<'a> {
222    pub(crate) k: &'a mut KermitCore,
223    pub(crate) st: &'a mut CalcState,
224}
225
226impl CalcOps<'_> {
227    /// [`Calculator::sync`].
228    pub(crate) async fn sync(&mut self) -> Result<()> {
229        let marker = self.st.marker();
230        self.sync_with(&marker).await
231    }
232
233    async fn sync_with(&mut self, marker: &str) -> Result<()> {
234        let command = format!("\"{marker}\"");
235        for attempt in 0..2 {
236            // The first attempt is sent once and gets one timeout period
237            // (20 s by default), not the whole retry budget; the second has
238            // the normal budget: the marker is the one command that may
239            // safely run twice, only markers are ever dropped.
240            let result = if attempt == 0 {
241                self.host(&command).await
242            } else {
243                self.host_retrying(&command).await
244            };
245            let reply = match result {
246                // The calculator aborted a transfer left over from the dead
247                // client (seen: "Transfer Failed" on the 48SX): an odd
248                // reply like any other.
249                Err(Error::Remote(_)) => continue,
250                // The late reply and our command crossed and the exchange
251                // stalled (seen on the emulated 49G under load: the marker
252                // ran, its reply never came). Once more: the second reply
253                // shows both markers and both are dropped.
254                Err(Error::NoReply { .. } | Error::Kermit(kermit_proto::Error::Timeout))
255                    if attempt == 0 =>
256                {
257                    continue;
258                }
259                reply => reply?,
260            };
261            let ours = reply
262                .levels
263                .iter()
264                .take_while(|level| parse_string(level).as_deref() == Some(marker))
265                .count();
266            if reply.error.is_none() && ours > 0 {
267                self.drop_levels(ours).await?;
268                return Ok(());
269            }
270        }
271        Err(Error::Reply(format!(
272            "not in step with the calculator: neither reply showed the sync marker {marker}"
273        )))
274    }
275
276    /// Before a best-effort cleanup after a failed step: forget the link's
277    /// error so the cleanup tries the link again, as each call to the
278    /// transport did before the seam (a dead link still fails it).
279    fn retry_link(&self) {
280        self.k.link.clear_error();
281    }
282
283    /// [`Calculator::run`].
284    pub(crate) async fn run(&mut self, command: &str) -> Result<StackReply> {
285        self.st.mode = None;
286        self.host(command).await
287    }
288
289    /// Send `command` as a `C` packet exactly once and parse the stack
290    /// reply. A `C` resent after a lost or late ACK runs again on the
291    /// calculator, which cannot tell it from a new command, so the packet
292    /// is never retransmitted (`first_packet_retries = Some(0)`), and a NAK
293    /// (usually a stale one from the idle server) does not shorten the wait.
294    /// One exception: a NAK within [`HOST_NAK_WINDOW`] of the `C` going out,
295    /// but not sooner than the `C`'s wire time ([`HOST_BYTE_TIME`] per
296    /// byte), is the calculator rejecting it, and the `C` is resent once
297    /// after [`HOST_NAK_GRACE`] if no answer (`S`, short reply or `E`) came
298    /// meanwhile (the command did not run). Input waiting before the `C`
299    /// is discarded first (`Session::transact_with`), so a stale NAK is not
300    /// read as one. No answer to the `C` within the timeout is
301    /// [`Error::NoReply`]. Once
302    /// the calculator's `S` is in, the reply packets keep the session's
303    /// retries; a failure after that is the Kermit error (the command ran).
304    async fn host(&mut self, command: &str) -> Result<StackReply> {
305        let timeout = self.k.config().timeout;
306        self.host_once(command, timeout).await
307    }
308
309    /// [`host`](Self::host) with a reply timeout of `timeout`.
310    async fn host_once(&mut self, command: &str, timeout: Duration) -> Result<StackReply> {
311        let normal = self.k.config().clone();
312        let mut once = normal.clone();
313        once.timeout = timeout;
314        once.first_packet_retries = Some(0);
315        once.nak_grace = timeout;
316        once.first_packet_nak_window = Some(HOST_NAK_WINDOW);
317        once.first_packet_nak_grace = Some(HOST_NAK_GRACE.min(timeout));
318        once.first_packet_nak_byte_time = Some(HOST_BYTE_TIME);
319        self.k.set_config(once);
320        let result = self.host_retrying(command).await;
321        self.k.set_config(normal);
322        match result {
323            Err(Error::Kermit(kermit_proto::Error::Timeout)) if !self.k.answered() => {
324                Err(Error::NoReply {
325                    command: command.to_string(),
326                })
327            }
328            other => other,
329        }
330    }
331
332    /// Send `command` as a `C` packet with the session's retries and parse
333    /// the stack reply. Only for a command that may run twice (the sync
334    /// marker).
335    async fn host_retrying(&mut self, command: &str) -> Result<StackReply> {
336        let bytes = encode_command(command)?;
337        let transcript = self.k.transact(Command::Host(bytes)).await?;
338        Ok(parse_stack(&decode(&transcript.text)))
339    }
340
341    /// Run `parts` joined by spaces as one command; if that is too long for
342    /// a packet, run each part on its own in order. The first reply with an
343    /// error becomes [`Error::Calculator`].
344    async fn exec(&mut self, parts: &[String]) -> Result<StackReply> {
345        match self.host(&parts.join(" ")).await {
346            Err(Error::CommandTooLong { .. }) if parts.len() > 1 => {
347                let mut last = StackReply::default();
348                for part in parts {
349                    last = checked(self.host(part).await?)?;
350                }
351                Ok(last)
352            }
353            reply => checked(reply?),
354        }
355    }
356
357    /// Run `command`, read `levels` stack levels (level 1 first) and drop
358    /// them again. Only for short values that every display mode shows
359    /// exactly (a flag's 0 or 1, `1.E0` in `0 SCI`; the 48S/SX's path): the
360    /// 49G cuts each level at its display width, 20 characters on ROM
361    /// 1.18, without a marker, and a real with more digits needs STD
362    /// ([`Self::drop_and_restore_flags`]).
363    async fn query(&mut self, command: &str, levels: usize) -> Result<Vec<String>> {
364        let reply = checked(self.host(command).await?)?;
365        if reply.levels.len() < levels {
366            return Err(Error::Reply(format!(
367                "{command}: expected {levels} stack level(s), got {:?}",
368                reply.levels
369            )));
370        }
371        let values = reply.levels[..levels].to_vec();
372        self.drop_levels(levels).await?;
373        Ok(values)
374    }
375
376    /// Drop `n` levels pushed by an internal query: `DROP`, `DROP2`, or
377    /// `n. DROPN` (a real: a 49G in exact mode reads `7` as an integer).
378    async fn drop_levels(&mut self, n: usize) -> Result<()> {
379        match drop_command(n) {
380            Some(command) => checked(self.host(&command).await?).map(|_| ()),
381            None => Ok(()),
382        }
383    }
384
385    /// Drop `n` levels above the flags a query saved and put the flags
386    /// back, in one command (`n. DROPN STOF`).
387    ///
388    /// A query whose reply holds reals that satx reads starts with `RCLF
389    /// STD`: the user's flags saved on the stack (a list of binary
390    /// integers) and the number display set to STD, so a real arrives with
391    /// all its digits whatever the display mode (in `0 SCI` 9600 shows as
392    /// `1.E4`). The fraction mark (flag -51) stays; [`parse_real`] reads
393    /// both. `RCLF`, `STD` and `STOF` work alike on the 48S/SX, 48G/GX and
394    /// 49G (emulated, 2026-11-08).
395    async fn drop_and_restore_flags(&mut self, n: usize) -> Result<()> {
396        let command = match drop_command(n) {
397            Some(drop) => format!("{drop} STOF"),
398            None => "STOF".to_string(),
399        };
400        checked(self.host(&command).await?).map(|_| ())
401    }
402
403    /// [`Calculator::list`].
404    pub(crate) async fn list(&mut self) -> Result<Listing> {
405        let transcript = self.k.transact(Command::Directory).await?;
406        parse_listing(&decode(&transcript.text))
407    }
408
409    /// [`Calculator::path`].
410    pub(crate) async fn path(&mut self) -> Result<Vec<String>> {
411        if let Some(path) = self.list().await?.path {
412            return Ok(path);
413        }
414        let [value]: [String; 1] = self
415            .query("PATH", 1)
416            .await?
417            .try_into()
418            .map_err(|_| Error::Reply("PATH: no value".into()))?;
419        parse_list(&value).ok_or_else(|| Error::Reply(format!("PATH: not a list: {value:?}")))
420    }
421
422    /// [`Calculator::cd`].
423    pub(crate) async fn cd(&mut self, path: &[&str]) -> Result<()> {
424        let components = match path.split_first() {
425            Some((&"HOME", rest)) => rest,
426            _ => path,
427        };
428        for name in components {
429            validate_name(name)?;
430        }
431        self.exec(&["HOME".to_string()]).await?;
432        for name in components {
433            let listing = self.list().await?;
434            let is_dir = listing
435                .entries
436                .iter()
437                .any(|e| e.name == *name && e.is_directory());
438            if !is_dir {
439                return Err(Error::Reply(format!("{name}: no such directory")));
440            }
441            self.exec(&[(*name).to_string()]).await?;
442        }
443        Ok(())
444    }
445
446    /// [`Calculator::updir`].
447    pub(crate) async fn updir(&mut self) -> Result<()> {
448        self.exec(&["UPDIR".to_string()]).await.map(|_| ())
449    }
450
451    /// [`Calculator::mkdir`].
452    pub(crate) async fn mkdir(&mut self, name: &str) -> Result<()> {
453        self.exec(&[format!("{} CRDIR", quote(name)?)])
454            .await
455            .map(|_| ())
456    }
457
458    /// [`Calculator::remove`].
459    pub(crate) async fn remove(&mut self, name: &str) -> Result<()> {
460        let quoted = quote(name)?;
461        let is_dir = self
462            .list()
463            .await?
464            .entries
465            .iter()
466            .find(|e| e.name == name)
467            .map(|e| e.is_directory())
468            .ok_or_else(|| Error::Reply(format!("{name}: no such variable")))?;
469        let purge = if is_dir { "PGDIR" } else { "PURGE" };
470        self.exec(&[format!("{quoted} {purge}")]).await.map(|_| ())
471    }
472
473    /// [`Calculator::rename`].
474    pub(crate) async fn rename(&mut self, from: &str, to: &str) -> Result<()> {
475        let quoted_from = quote(from)?;
476        let quoted_to = quote(to)?;
477        let listing = self.list().await?;
478        let is_dir = listing
479            .entries
480            .iter()
481            .find(|e| e.name == from)
482            .map(|e| e.is_directory())
483            .ok_or_else(|| Error::Reply(format!("{from}: no such variable")))?;
484        if listing.entries.iter().any(|e| e.name == to) {
485            return Err(Error::Reply(format!("{to}: already exists")));
486        }
487        let purge = if is_dir { "PGDIR" } else { "PURGE" };
488        self.exec(&[
489            format!("{quoted_from} RCL"),
490            format!("{quoted_to} STO"),
491            format!("{quoted_from} {purge}"),
492        ])
493        .await
494        .map(|_| ())
495    }
496
497    /// [`Calculator::mem`]: read in STD ([`MEM_STD`]), as a backup checks
498    /// it against its size (Files on the 48S/SX, whose listing lacks it).
499    pub(crate) async fn mem(&mut self) -> Result<f64> {
500        let reply = checked(self.host(MEM_STD).await?)?;
501        let value = reply.level(1).unwrap_or_default().to_string();
502        self.drop_and_restore_flags(1).await?;
503        parse_real(&value).ok_or_else(|| Error::Reply(format!("MEM: not a number: {value:?}")))
504    }
505
506    /// [`Calculator::version`].
507    pub(crate) async fn version(&mut self) -> Result<Option<String>> {
508        let reply = checked(self.host("VERSION").await?)?;
509        // 48SX: the undefined name evaluates to itself.
510        let level1 = reply.level(1).unwrap_or_default().trim();
511        if level1 == "VERSION" || parse_name(level1).as_deref() == Some("VERSION") {
512            self.drop_levels(1).await?;
513            return Ok(None);
514        }
515        let (Some(l2), Some(l1)) = (reply.level(2), reply.level(1)) else {
516            return Err(Error::Reply(format!(
517                "VERSION: expected two strings, got {:?}",
518                reply.levels
519            )));
520        };
521        let bad = |s: &str| Error::Reply(format!("VERSION: not a string: {s:?}"));
522        parse_string(l2).ok_or_else(|| bad(l2))?;
523        parse_string(l1).ok_or_else(|| bad(l1))?;
524        let (version, copyright) = match (parse_whole_string(l2), parse_whole_string(l1)) {
525            (Some(version), Some(copyright)) => {
526                self.drop_levels(2).await?;
527                (version, copyright)
528            }
529            (None, None) => {
530                // Nothing tells where the two would meet in the chunks.
531                self.drop_levels(2).await?;
532                return Err(Error::Reply(format!(
533                    "VERSION: both strings arrived cut: {:?}",
534                    reply.levels
535                )));
536            }
537            // The 49G cut one at its display width.
538            (version, copyright) => {
539                let below = reply.levels.len() - 2;
540                self.whole_version(version, copyright, below).await?
541            }
542        };
543        let version = version.split_whitespace().collect::<Vec<_>>().join(" ");
544        Ok(Some(format!("{version}, {copyright}")))
545    }
546
547    /// `VERSION`'s two strings, still on the stack above `below` levels of
548    /// the user's, whole: fetched in chunks by [`VERSION_CHUNKS`], then
549    /// dropped with the chunks and the user's flags put back. `version` or
550    /// `copyright` is the one that arrived whole and tells where the two
551    /// meet in the joined text.
552    async fn whole_version(
553        &mut self,
554        version: Option<String>,
555        copyright: Option<String>,
556        below: usize,
557    ) -> Result<(String, String)> {
558        let reply = match checked(self.host(VERSION_CHUNKS).await?) {
559            Err(e @ Error::Calculator { .. }) => {
560                self.drop_after_failed_chunks(&e, below).await?;
561                return Err(e);
562            }
563            reply => reply?,
564        };
565        let bad =
566            |reply: &StackReply| Error::Reply(format!("VERSION: bad chunks: {:?}", reply.levels));
567        // The saved flags are the first list from level 1 down: above them
568        // are only the chunks (strings) and the total (a real).
569        let Some(flags) = (1..=reply.levels.len()).find(|&n| reply.level(n).is_some_and(is_flags))
570        else {
571            return Err(bad(&reply));
572        };
573        self.drop_and_restore_flags(flags - 1).await?;
574        let total = reply.level(1).and_then(parse_count);
575        let joined = (2..flags)
576            .rev()
577            .map(|n| reply.level(n).and_then(parse_whole_string))
578            .collect::<Option<String>>()
579            .unwrap_or_default();
580        let split = match (&version, &copyright) {
581            (_, Some(copyright)) if joined.ends_with(copyright.as_str()) => {
582                Some(joined.len() - copyright.len())
583            }
584            (Some(version), None) if joined.starts_with(version.as_str()) => Some(version.len()),
585            _ => None,
586        };
587        match (total, split) {
588            (Some(total), Some(split))
589                if joined.chars().count() == total && flags - 2 == total.div_ceil(CHUNK) =>
590            {
591                let (version, copyright) = joined.split_at(split);
592                Ok((version.to_string(), copyright.to_string()))
593            }
594            _ => Err(bad(&reply)),
595        }
596    }
597
598    /// After [`VERSION_CHUNKS`] failed (`err`'s stack is what it left):
599    /// drop everything above the user's `below` levels and, if the flags
600    /// were saved by then (the deepest of those levels), put them back.
601    async fn drop_after_failed_chunks(&mut self, err: &Error, below: usize) -> Result<()> {
602        let Error::Calculator { stack, .. } = err else {
603            return Ok(());
604        };
605        let ours = stack.len().saturating_sub(below);
606        match ours.checked_sub(1).and_then(|deepest| stack.get(deepest)) {
607            Some(deepest) if is_flags(deepest) => self.drop_and_restore_flags(ours - 1).await,
608            _ => self.drop_levels(ours).await,
609        }
610    }
611
612    /// [`Calculator::iopar`]: read item by item, in STD ([`IOPAR_ITEMS`]).
613    pub(crate) async fn iopar(&mut self) -> Result<Iopar> {
614        let reply = match checked(self.host(IOPAR_ITEMS).await?) {
615            Err(e @ Error::Calculator { .. }) => {
616                // IOPAR is no list: LIST→ left it (or the undefined name)
617                // on the stack, above the saved flags.
618                if let Error::Calculator { stack, .. } = &e
619                    && stack.get(1).is_some_and(|l| is_flags(l))
620                {
621                    self.drop_and_restore_flags(1).await?;
622                }
623                return Err(e);
624            }
625            reply => reply?,
626        };
627        checked(self.host(IOPAR_DROP).await?)?;
628        let Some(n) = reply.level(1).and_then(parse_count) else {
629            return Err(Error::Reply(format!(
630                "IOPAR: no item count: {:?}",
631                reply.levels
632            )));
633        };
634        if reply.levels.len() < n + 2 {
635            return Err(Error::Reply(format!(
636                "IOPAR: expected {n} items, got {:?}",
637                reply.levels
638            )));
639        }
640        // Level n + 1 is the first item.
641        let items: Vec<&str> = (2..=n + 1)
642            .rev()
643            .map(|level| reply.level(level).unwrap_or_default())
644            .collect();
645        Iopar::from_items(&items)
646            .ok_or_else(|| Error::Reply(format!("IOPAR: bad list: {{ {} }}", items.join(" "))))
647    }
648
649    /// [`Calculator::set_iopar`].
650    pub(crate) async fn set_iopar(&mut self, iopar: &Iopar) -> Result<()> {
651        self.exec(&[
652            "PATH HOME".to_string(),
653            format!("{} 'IOPAR' STO", iopar.to_rpl()),
654            "EVAL".to_string(),
655        ])
656        .await
657        .map(|_| ())
658    }
659
660    /// [`Calculator::transfer_mode`].
661    pub(crate) async fn transfer_mode(&mut self) -> Result<TransferMode> {
662        let values = self.query("-35 FS?", 1).await?;
663        let value = values.first().map(String::as_str).unwrap_or_default();
664        let mode = match parse_real(value) {
665            Some(1.0) => TransferMode::Binary,
666            Some(0.0) => TransferMode::Ascii,
667            _ => return Err(Error::Reply(format!("-35 FS?: not a flag: {value:?}"))),
668        };
669        self.st.mode = Some(mode);
670        Ok(mode)
671    }
672
673    /// [`Calculator::set_transfer_mode`].
674    pub(crate) async fn set_transfer_mode(&mut self, mode: TransferMode) -> Result<()> {
675        if self.st.mode == Some(mode) {
676            return Ok(());
677        }
678        let command = match mode {
679            TransferMode::Binary => "-35 SF",
680            TransferMode::Ascii => "-35 CF",
681        };
682        self.exec(&[command.to_string()]).await?;
683        self.st.mode = Some(mode);
684        Ok(())
685    }
686
687    /// [`Calculator::get`].
688    pub(crate) async fn get(&mut self, name: &str, mode: TransferMode) -> Result<Vec<u8>> {
689        validate_name(name)?;
690        self.set_transfer_mode(mode).await?;
691        let transcript = self.k.transact(Command::Get(encode(name)?)).await?;
692        let [file]: [_; 1] = transcript.files.try_into().map_err(|files: Vec<_>| {
693            Error::Reply(format!(
694                "GET {name}: expected one file, got {}",
695                files.len()
696            ))
697        })?;
698        Ok(match mode {
699            TransferMode::Binary => strip_padding(&file.data, KERMIT_PADDING_ALLOWANCE).to_vec(),
700            TransferMode::Ascii => file.data,
701        })
702    }
703
704    /// [`Calculator::put`].
705    pub(crate) async fn put(
706        &mut self,
707        name: &str,
708        data: &[u8],
709        mode: TransferMode,
710    ) -> Result<String> {
711        validate_name(name)?;
712        self.set_transfer_mode(mode).await?;
713        let file = OutgoingFile {
714            name: encode(name)?,
715            data: data.to_vec(),
716        };
717        let transcript = self.k.transact(Command::Send(vec![file])).await?;
718        transcript
719            .stored_names
720            .into_iter()
721            .next()
722            .ok_or_else(|| Error::Reply(format!("SEND {name}: no file stored")))
723    }
724
725    /// [`Calculator::pict`].
726    pub(crate) async fn pict(&mut self) -> Result<Grob> {
727        Grob::from_file(&self.pict_file().await?)
728    }
729
730    /// [`Calculator::pict`] as the binary transfer file the calculator
731    /// sent, checked to hold a GROB.
732    pub(crate) async fn pict_file(&mut self) -> Result<Vec<u8>> {
733        self.refuse_existing(PICT_VAR).await?;
734        self.exec(&[format!("PICT RCL '{PICT_VAR}' STO")]).await?;
735        let data = self.get(PICT_VAR, TransferMode::Binary).await;
736        self.retry_link();
737        let purge = self.exec(&[format!("'{PICT_VAR}' PURGE")]).await;
738        let data = data?;
739        purge?;
740        Grob::from_file(&data)?;
741        Ok(data)
742    }
743
744    /// [`Calculator::backup`].
745    pub(crate) async fn backup(&mut self) -> Result<Vec<u8>> {
746        self.refuse_existing(BACKUP_VAR).await?;
747        self.exec(&[format!(":0:{BACKUP_VAR} ARCHIVE")]).await?;
748        let result = self.backup_steps().await;
749        if result.is_err() {
750            // Best effort: the error being reported matters more.
751            self.retry_link();
752            let _ = self.exec(&[format!(":0:{BACKUP_VAR} PURGE")]).await;
753            self.retry_link();
754            let _ = self.exec(&[format!("'{BACKUP_VAR}' PGDIR")]).await;
755        }
756        let data = result?;
757        let info = inspect(&data)?;
758        if info.object_type != Some(ObjectType::Directory) {
759            return Err(Error::Object(format!(
760                "backup is not a directory (prolog {:05X})",
761                info.prolog
762            )));
763        }
764        Ok(data)
765    }
766
767    async fn backup_steps(&mut self) -> Result<Vec<u8>> {
768        // STO before PURGE, else "Object In Use".
769        let copied = self
770            .exec(&[
771                format!(":0:{BACKUP_VAR} RCL"),
772                format!("'{BACKUP_VAR}' STO"),
773                format!(":0:{BACKUP_VAR} PURGE"),
774            ])
775            .await;
776        // A `STO` that failed (no room for the copy) leaves the name and
777        // the recalled archive on the stack, which keeps the port object in
778        // use: the cleanup's `PURGE` would fail too. Only this command: a
779        // later failure's level 2 is the user's. A 49G in algebraic mode
780        // shows the name without its quotes.
781        if let Err(Error::Calculator { stack, .. }) = &copied
782            && stack.first().is_some_and(|l| {
783                l.trim() == BACKUP_VAR || parse_name(l).as_deref() == Some(BACKUP_VAR)
784            })
785        {
786            self.retry_link();
787            let _ = self.drop_levels(2).await;
788        }
789        copied?;
790        let data = self.get(BACKUP_VAR, TransferMode::Binary).await?;
791        self.exec(&[format!("'{BACKUP_VAR}' PGDIR")]).await?;
792        Ok(data)
793    }
794
795    /// [`Calculator::restore`].
796    pub(crate) async fn restore(&mut self, data: &[u8]) -> Result<()> {
797        self.restore_leaving(data, None).await
798    }
799
800    /// [`Calculator::restore`], with flag -35 set to `mode` just before
801    /// `RESTORE`: the warm start ends server mode, so a host that changed
802    /// the flag for its session cannot put it back afterwards. RESTORE
803    /// keeps the calculator's flags (a backup made with -35 clear restored
804    /// onto a calculator with it set leaves it set; Saturnus, 48SX and
805    /// 48GX, 2026-10-11).
806    pub(crate) async fn restore_leaving(
807        &mut self,
808        data: &[u8],
809        mode: Option<TransferMode>,
810    ) -> Result<()> {
811        check_backup(data)?;
812        self.refuse_existing(RESTORE_VAR).await?;
813        let stored = self.put(RESTORE_VAR, data, TransferMode::Binary).await?;
814        if stored != RESTORE_VAR {
815            return Err(Error::Reply(format!(
816                "backup stored as {stored}, expected {RESTORE_VAR}"
817            )));
818        }
819        let copied = self
820            .exec(&[
821                format!("'{RESTORE_VAR}' RCL"),
822                format!(":0:{RESTORE_VAR} STO"),
823                format!("'{RESTORE_VAR}' PGDIR"),
824            ])
825            .await;
826        if let Err(e) = copied {
827            self.retry_link();
828            let _ = self.exec(&[format!("'{RESTORE_VAR}' PGDIR")]).await;
829            return Err(e);
830        }
831        if let Some(mode) = mode {
832            self.set_transfer_mode(mode).await?;
833        }
834        self.restore_from_port().await
835    }
836
837    /// `RESTORE` from `:0:SATXRS`. The warm start ends server mode, so no
838    /// reply ever comes; but no reply is also what a lost `C` gives. A
839    /// probe follows: no answer means the warm start ended server mode
840    /// (success). An answer leaves the result unknown ([`Error::Reply`],
841    /// `:0:SATXRS` stays): the `RESTORE` may have been lost, or it ran and
842    /// someone restarted `SERVER` within the probe's timeout.
843    async fn restore_from_port(&mut self) -> Result<()> {
844        self.st.mode = None;
845        let timeout = self.k.config().timeout;
846        let restore = format!(":0:{RESTORE_VAR} RESTORE");
847        match self.host_once(&restore, RESTORE_TIMEOUT.min(timeout)).await {
848            Err(Error::NoReply { .. }) => {}
849            Err(e) => return Err(e),
850            Ok(reply) => {
851                checked(reply)?;
852                return Err(Error::Reply("calculator did not restart".into()));
853            }
854        }
855        let marker = self.st.marker();
856        let probe = self.host_once(&format!("\"{marker}\""), timeout).await;
857        let still_running = || {
858            Error::Reply(format!(
859                "the calculator answers again, so RESTORE's result is unknown: it may have \
860                 run before the server was restarted; the backup stays in :0:{RESTORE_VAR}"
861            ))
862        };
863        match probe {
864            Err(Error::NoReply { .. }) => Ok(()),
865            Err(Error::Remote(_)) => Err(still_running()),
866            Err(e) => Err(e),
867            Ok(reply) => {
868                if reply.error.is_none()
869                    && reply.level(1).and_then(parse_string).as_deref() == Some(marker.as_str())
870                {
871                    // Best effort: the probe's own marker; the error matters
872                    // more.
873                    let _ = self.drop_levels(1).await;
874                }
875                Err(still_running())
876            }
877        }
878    }
879
880    /// [`Calculator::purge_restore_leftover`].
881    pub(crate) async fn purge_restore_leftover(&mut self) -> Result<()> {
882        self.exec(&[format!(":0:{RESTORE_VAR} PURGE")])
883            .await
884            .map(|_| ())
885    }
886
887    /// [`Calculator::finish`].
888    pub(crate) async fn finish(&mut self) -> Result<()> {
889        self.k.transact(Command::Finish).await.map(|_| ())
890    }
891
892    /// [`Calculator::model`].
893    pub(crate) async fn model(&mut self) -> Result<Model> {
894        Ok(Model::from_version(self.version().await?.as_deref()))
895    }
896
897    /// [`Calculator::prepare_for_xmodem`].
898    pub(crate) async fn prepare_for_xmodem(
899        &mut self,
900        direction: XmodemDirection,
901        name: &str,
902    ) -> Result<XmodemPlan> {
903        validate_name(name)?;
904        let model = self.model().await?;
905        if !model.has_xmodem() {
906            return Err(Error::Unsupported(format!(
907                "the {} has no XModem; use Kermit",
908                model.name()
909            )));
910        }
911        let exists = self.list().await?.entries.iter().any(|e| e.name == name);
912        if direction == XmodemDirection::FromCalculator && !exists {
913            return Err(Error::Reply(format!("{name}: no such variable")));
914        }
915        if direction == XmodemDirection::ToCalculator && exists && model == Model::Hp48Gx {
916            // XRECV stops with "XRECV Error: Name Conflict" before any start
917            // character and leaves the name on the stack (emulated 48GX,
918            // 2026-10-05).
919            return Err(Error::Reply(format!("{name}: already exists")));
920        }
921        let mut switched_to_rpn = false;
922        if model == Model::Hp49G {
923            let flag = self.query("-95. FS?", 1).await?;
924            let alg = flag.first().and_then(|v| parse_real(v)) == Some(1.0);
925            if alg {
926                self.exec(&["-95. CF".to_string()]).await?;
927                switched_to_rpn = true;
928            }
929        }
930        // The program the user runs with EVAL once the server has ended
931        // (XRECV and XSEND do not run inside it): on the stack, not run.
932        if let Err(e) = self.exec(&[stacked_program(direction, name)]).await {
933            // Nothing happened for the user: algebraic mode back, as it was.
934            if switched_to_rpn {
935                let _ = self.exec(&["-95. SF".to_string()]).await;
936            }
937            return Err(e);
938        }
939        self.finish().await?;
940        self.st.mode = None;
941
942        let mut notes = Vec::new();
943        if direction == XmodemDirection::ToCalculator && exists {
944            notes.push(match model {
945                Model::Hp49G => format!(
946                    "{name} exists: the 49G does not overwrite it but stores the object as {name}.1."
947                ),
948                _ => format!(
949                    "{name} exists: the 49G stores the object as {name}.1 and the 48G/GX \
950                     refuses with \"Name Conflict\"; this model is unknown."
951                ),
952            });
953        }
954        if direction == XmodemDirection::ToCalculator && model == Model::Hp48Gx {
955            notes.push(format!(
956                "If the transfer fails, {name} may be left holding an empty string."
957            ));
958        }
959        if switched_to_rpn {
960            notes.push(
961                "The calculator was in algebraic mode and is now in RPN mode \
962                 (flag -95 cleared); type -95 SF to switch back."
963                    .to_string(),
964            );
965        }
966        notes.push(
967            "If you do not go on, press \u{2190} (backspace) instead: it drops the program, \
968             and the stack is as it was."
969                .to_string(),
970        );
971        notes.push(format!(
972            "The calculator has left server mode; {} after the transfer.",
973            server_again(model)
974        ));
975        Ok(XmodemPlan {
976            model,
977            direction,
978            name: name.to_string(),
979            program: program_text(direction, name),
980            keys: eval_keys(model).iter().map(|k| k.to_string()).collect(),
981            switched_to_rpn,
982            exists,
983            notes,
984        })
985    }
986
987    /// Fail if `name` exists in the current directory.
988    async fn refuse_existing(&mut self, name: &str) -> Result<()> {
989        if self.list().await?.entries.iter().any(|e| e.name == name) {
990            return Err(Error::Reply(format!(
991                "{name} exists in the current directory; remove it first"
992            )));
993        }
994        Ok(())
995    }
996}
997
998/// A calculator in Kermit server mode, over a blocking [`Transport`] with
999/// the system clock. For a link driven from outside (a browser), see
1000/// [`machine::Machine`](crate::machine::Machine), which runs the same
1001/// operations.
1002#[derive(Debug)]
1003#[cfg(not(target_arch = "wasm32"))]
1004pub struct Calculator {
1005    session: Session,
1006    state: CalcState,
1007}
1008
1009#[cfg(not(target_arch = "wasm32"))]
1010impl Calculator {
1011    /// Wrap an open session. The transfer mode is unknown until read or set.
1012    pub fn new(session: Session) -> Self {
1013        Calculator {
1014            session,
1015            state: CalcState::new(entropy()),
1016        }
1017    }
1018
1019    /// Open `addr` (see [`crate::transport::open`]) with default options
1020    /// and [`sync`](Calculator::sync).
1021    pub fn open(addr: &str) -> Result<Self> {
1022        let mut calc = Calculator::new(Session::open(addr)?);
1023        calc.sync()?;
1024        Ok(calc)
1025    }
1026
1027    /// The underlying session. Forgets the cached transfer mode, since the
1028    /// caller may change flag -35 through it.
1029    pub fn session(&mut self) -> &mut Session {
1030        self.state.mode = None;
1031        &mut self.session
1032    }
1033
1034    /// The underlying session, consuming the calculator.
1035    pub fn into_session(self) -> Session {
1036        self.session
1037    }
1038
1039    /// The open link, consuming the calculator, e.g. for an
1040    /// [`XmodemSession`](crate::XmodemSession) after
1041    /// [`Calculator::prepare_for_xmodem`].
1042    pub fn into_transport(self) -> Box<dyn Transport> {
1043        self.session.into_transport()
1044    }
1045
1046    /// The transport, the link and the operations, borrowed apart.
1047    fn split(&mut self) -> (&mut dyn Transport, Link, CalcOps<'_>) {
1048        let link = self.session.core.link.clone();
1049        let ops = CalcOps {
1050            k: &mut self.session.core,
1051            st: &mut self.state,
1052        };
1053        (self.session.transport.as_mut(), link, ops)
1054    }
1055
1056    #[cfg(test)]
1057    fn sync_with(&mut self, marker: &str) -> Result<()> {
1058        let (transport, link, mut c) = self.split();
1059        link::drive(transport, &link, c.sync_with(marker), &mut |_| {})
1060    }
1061
1062    #[cfg(test)]
1063    fn restore_from_port(&mut self) -> Result<()> {
1064        let (transport, link, mut c) = self.split();
1065        link::drive(transport, &link, c.restore_from_port(), &mut |_| {})
1066    }
1067
1068    /// Get in step with the server at the start of a session.
1069    ///
1070    /// When a client dies while a host command runs, the calculator still
1071    /// finishes the command and offers its reply (an S packet repeated
1072    /// every 5 s for about a minute). The next client's first command is
1073    /// eaten as a bad ACK and the late reply arrives in its place. Sequence
1074    /// numbers restart at zero for every command and host commands and
1075    /// `G D` both answer with text, so the late reply cannot be told apart
1076    /// on the wire, and repeating an arbitrary command would repeat its
1077    /// effect. Instead the session starts with a sacrificial command that
1078    /// pushes a marker string unique to this session ([`sync_marker`],
1079    /// short enough that no model truncates it). A reply whose level 1 is
1080    /// the marker is ours: the marker is dropped (every copy of it on top
1081    /// of the stack, in case an earlier attempt was not eaten after all).
1082    /// Any other reply was a late one and our command was eaten: the marker
1083    /// command is sent once more. Nothing but the marker is ever dropped
1084    /// and nothing else is ever resent. Link errors are returned; a second
1085    /// odd reply is [`Error::Reply`]: satx and the calculator are not in
1086    /// step, and nothing is run on a stack it cannot vouch for.
1087    pub fn sync(&mut self) -> Result<()> {
1088        let (transport, link, mut c) = self.split();
1089        link::drive(transport, &link, c.sync(), &mut |_| {})
1090    }
1091
1092    /// Run a host command (Unicode or ASCII trigraphs such as `\->`) and
1093    /// return the stack. An `Error:` reply is `Ok` with `error` set. Forgets
1094    /// the cached transfer mode, since the command may change flag -35.
1095    /// The command is sent once: no reply in time is [`Error::NoReply`],
1096    /// never a second run.
1097    pub fn run(&mut self, command: &str) -> Result<StackReply> {
1098        let (transport, link, mut c) = self.split();
1099        link::drive(transport, &link, c.run(command), &mut |_| {})
1100    }
1101
1102    /// The current directory listing (`G D`).
1103    pub fn list(&mut self) -> Result<Listing> {
1104        let (transport, link, mut c) = self.split();
1105        link::drive(transport, &link, c.list(), &mut |_| {})
1106    }
1107
1108    /// The current directory path, e.g. `["HOME", "D1"]`: from the listing
1109    /// header (48GX, 49G) or a `PATH` query (48SX, whose listing has none).
1110    pub fn path(&mut self) -> Result<Vec<String>> {
1111        let (transport, link, mut c) = self.split();
1112        link::drive(transport, &link, c.path(), &mut |_| {})
1113    }
1114
1115    /// Change to the absolute directory `path`, e.g. `["HOME", "D1"]` (the
1116    /// leading `HOME` is optional). Each component is checked against the
1117    /// listing before it is evaluated.
1118    pub fn cd(&mut self, path: &[&str]) -> Result<()> {
1119        let (transport, link, mut c) = self.split();
1120        link::drive(transport, &link, c.cd(path), &mut |_| {})
1121    }
1122
1123    /// Go to the parent directory (`UPDIR`).
1124    pub fn updir(&mut self) -> Result<()> {
1125        let (transport, link, mut c) = self.split();
1126        link::drive(transport, &link, c.updir(), &mut |_| {})
1127    }
1128
1129    /// Create directory `name` in the current directory (`CRDIR`).
1130    pub fn mkdir(&mut self, name: &str) -> Result<()> {
1131        let (transport, link, mut c) = self.split();
1132        link::drive(transport, &link, c.mkdir(name), &mut |_| {})
1133    }
1134
1135    /// Delete variable `name` from the current directory; a directory is
1136    /// deleted with its contents (`PGDIR`).
1137    pub fn remove(&mut self, name: &str) -> Result<()> {
1138        let (transport, link, mut c) = self.split();
1139        link::drive(transport, &link, c.remove(name), &mut |_| {})
1140    }
1141
1142    /// Rename variable `from` to `to` in the current directory (`RCL`, `STO`,
1143    /// then `PURGE` or `PGDIR`). `to` must not exist yet.
1144    pub fn rename(&mut self, from: &str, to: &str) -> Result<()> {
1145        let (transport, link, mut c) = self.split();
1146        link::drive(transport, &link, c.rename(from, to), &mut |_| {})
1147    }
1148
1149    /// Free memory in bytes (`MEM`).
1150    pub fn mem(&mut self) -> Result<f64> {
1151        let (transport, link, mut c) = self.split();
1152        link::drive(transport, &link, c.mem(), &mut |_| {})
1153    }
1154
1155    /// The ROM version text, e.g. `Version HP48-R, Copyright HP 1993`;
1156    /// `None` on the 48SX, which has no `VERSION` command.
1157    pub fn version(&mut self) -> Result<Option<String>> {
1158        let (transport, link, mut c) = self.split();
1159        link::drive(transport, &link, c.version(), &mut |_| {})
1160    }
1161
1162    /// The serial settings (`IOPAR`).
1163    pub fn iopar(&mut self) -> Result<Iopar> {
1164        let (transport, link, mut c) = self.split();
1165        link::drive(transport, &link, c.iopar(), &mut |_| {})
1166    }
1167
1168    /// Store `iopar` as `IOPAR` in HOME and return to the current directory.
1169    /// Takes effect when the calculator reopens the port (e.g. the next
1170    /// `SERVER`), not in the running session.
1171    pub fn set_iopar(&mut self, iopar: &Iopar) -> Result<()> {
1172        let (transport, link, mut c) = self.split();
1173        link::drive(transport, &link, c.set_iopar(iopar), &mut |_| {})
1174    }
1175
1176    /// Read the transfer mode (flag -35) and cache it.
1177    pub fn transfer_mode(&mut self) -> Result<TransferMode> {
1178        let (transport, link, mut c) = self.split();
1179        link::drive(transport, &link, c.transfer_mode(), &mut |_| {})
1180    }
1181
1182    /// Set the transfer mode (flag -35) unless the cached mode already is
1183    /// `mode`.
1184    pub fn set_transfer_mode(&mut self, mode: TransferMode) -> Result<()> {
1185        let (transport, link, mut c) = self.split();
1186        link::drive(transport, &link, c.set_transfer_mode(mode), &mut |_| {})
1187    }
1188
1189    /// GET variable `name` from the current directory in `mode`. Binary
1190    /// data is cut after the object (the calculator pads the last packet).
1191    pub fn get(&mut self, name: &str, mode: TransferMode) -> Result<Vec<u8>> {
1192        let (transport, link, mut c) = self.split();
1193        link::drive(transport, &link, c.get(name, mode), &mut |_| {})
1194    }
1195
1196    /// SEND `data` as variable `name` in `mode` and return the name the
1197    /// calculator stored it under (it can differ, e.g. a `.1` suffix when
1198    /// the name exists).
1199    pub fn put(&mut self, name: &str, data: &[u8], mode: TransferMode) -> Result<String> {
1200        let (transport, link, mut c) = self.split();
1201        link::drive(transport, &link, c.put(name, data, mode), &mut |_| {})
1202    }
1203
1204    /// Fetch the graphics screen PICT (plots, drawings) via `PICT RCL`, a
1205    /// temporary variable `SATXTMP` and a binary GET; the variable is purged
1206    /// afterwards. A calculator that never drew anything has a 0x0 PICT;
1207    /// `ERASE` makes it 131x64. The display itself cannot be captured over
1208    /// the link: `LCD→` in server mode only sees the server's own banner.
1209    /// Leaves the calculator in binary transfer mode.
1210    pub fn pict(&mut self) -> Result<Grob> {
1211        let (transport, link, mut c) = self.split();
1212        link::drive(transport, &link, c.pict(), &mut |_| {})
1213    }
1214
1215    /// Back up HOME: `ARCHIVE` into port 0, recall it into a temporary
1216    /// variable `SATXBK`, GET that in binary mode, then remove both. Returns
1217    /// the binary transfer file of the Directory object. `ARCHIVE :IO:name`
1218    /// fails in server mode ("Port Not Available"), hence the detour.
1219    /// Leaves the calculator in binary transfer mode.
1220    pub fn backup(&mut self) -> Result<Vec<u8>> {
1221        let (transport, link, mut c) = self.split();
1222        link::drive(transport, &link, c.backup(), &mut |_| {})
1223    }
1224
1225    /// Replace HOME with the backup `data` (from [`Calculator::backup`]):
1226    /// binary PUT as `SATXRS`, copy to port 0, `RESTORE` from there. The
1227    /// calculator warm-starts and leaves server mode; restart `SERVER` on
1228    /// it, then call [`Calculator::purge_restore_leftover`] to delete
1229    /// `:0:SATXRS`. `data` must be a Directory whose object walk succeeds
1230    /// (a truncated file never reaches `RESTORE`).
1231    pub fn restore(&mut self, data: &[u8]) -> Result<()> {
1232        let (transport, link, mut c) = self.split();
1233        link::drive(transport, &link, c.restore(data), &mut |_| {})
1234    }
1235
1236    /// Delete the backup object `:0:SATXRS` that [`Calculator::restore`]
1237    /// leaves in port 0, once `SERVER` runs again.
1238    pub fn purge_restore_leftover(&mut self) -> Result<()> {
1239        let (transport, link, mut c) = self.split();
1240        link::drive(transport, &link, c.purge_restore_leftover(), &mut |_| {})
1241    }
1242
1243    /// End server mode (`G F`).
1244    pub fn finish(&mut self) -> Result<()> {
1245        let (transport, link, mut c) = self.split();
1246        link::drive(transport, &link, c.finish(), &mut |_| {})
1247    }
1248
1249    /// The model, from the `VERSION` text (see [`Model::from_version`]).
1250    pub fn model(&mut self) -> Result<Model> {
1251        let (transport, link, mut c) = self.split();
1252        link::drive(transport, &link, c.model(), &mut |_| {})
1253    }
1254
1255    /// Get the calculator ready for an XModem transfer of variable `name`
1256    /// in the current directory and say what the user must press.
1257    ///
1258    /// `XRECV` and `XSEND` cannot be started through the Kermit server (they
1259    /// fail with "Port Not Available" on the 49G and 48GX), so this checks
1260    /// the name (it must exist for `XSEND`), switches a 49G in algebraic
1261    /// mode to RPN (flag -95; EVAL of the program needs RPN), puts the
1262    /// program `« 'NAME' XRECV »` (or `XSEND`) on the stack
1263    /// ([`stacked_program`]) and ends
1264    /// server mode with Kermit FINISH. An existing `NAME` is refused for
1265    /// `XRECV` on the 48G/GX ("XRECV Error: Name Conflict"); the 49G stores
1266    /// the object as `NAME.1` instead, which the plan's notes say. The user then presses
1267    /// [`XmodemPlan::keys`] (EVAL) on the calculator while an
1268    /// [`XmodemSession`](crate::XmodemSession) on
1269    /// [`Calculator::into_transport`] waits. Afterwards the calculator is
1270    /// out of server mode with the stack as before: `SERVER` must be
1271    /// started again. A user who does not go on drops the program with the
1272    /// backspace key. Errors for the 48S/SX, which has no XModem.
1273    pub fn prepare_for_xmodem(
1274        &mut self,
1275        direction: XmodemDirection,
1276        name: &str,
1277    ) -> Result<XmodemPlan> {
1278        let (transport, link, mut c) = self.split();
1279        link::drive(
1280            transport,
1281            &link,
1282            c.prepare_for_xmodem(direction, name),
1283            &mut |_| {},
1284        )
1285    }
1286}
1287
1288/// Seed for the sync markers of a [`Calculator`]: the per-process random
1289/// hasher keys mixed with the time.
1290fn entropy() -> u64 {
1291    use std::hash::{BuildHasher, Hasher};
1292    #[cfg(not(target_arch = "wasm32"))]
1293    use std::time::{SystemTime, UNIX_EPOCH};
1294    #[cfg(target_arch = "wasm32")]
1295    use web_time::{SystemTime, UNIX_EPOCH};
1296    // RandomState is seeded per process from the OS; mix in the time so two
1297    // states in one process differ too.
1298    let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
1299    if let Ok(since) = SystemTime::now().duration_since(UNIX_EPOCH) {
1300        hasher.write_u128(since.as_nanos());
1301    }
1302    hasher.finish()
1303}
1304
1305/// A sync marker as [`Calculator::sync`] pushes: `SATX-` and six random
1306/// hex digits (13 characters with the quotes, far below every model's
1307/// display width), plain ASCII without RPL delimiters.
1308pub fn sync_marker() -> String {
1309    CalcState::new(entropy()).marker()
1310}
1311
1312/// Check that `data` is a backup [`Calculator::restore`] can upload: a
1313/// binary Directory object whose size walk succeeds.
1314fn check_backup(data: &[u8]) -> Result<()> {
1315    let info = inspect(data).map_err(|e| Error::Object(format!("not a backup: {e}")))?;
1316    if info.object_type != Some(ObjectType::Directory) {
1317        return Err(Error::Object(format!(
1318            "not a backup: prolog {:05X} is not a directory",
1319            info.prolog
1320        )));
1321    }
1322    let nibbles = unpack(data.get(HEADER_LEN..).unwrap_or_default());
1323    object_size(&nibbles, 0).map_err(|e| Error::Object(format!("not a backup: {e}")))?;
1324    Ok(())
1325}
1326
1327/// The command that drops `n` levels: `DROP`, `DROP2`, or `n. DROPN` (a
1328/// real: a 49G in exact mode reads `7` as an integer); `None` for none.
1329fn drop_command(n: usize) -> Option<String> {
1330    match n {
1331        0 => None,
1332        1 => Some("DROP".to_string()),
1333        2 => Some("DROP2".to_string()),
1334        n => Some(format!("{n}. DROPN")),
1335    }
1336}
1337
1338/// A displayed level that is the flags `RCLF` saved: a list of binary
1339/// integers (`{ # 1688849860264944d # 0d }`, the 49G's cut
1340/// `{# 6000204010FF0h;# 0h`).
1341fn is_flags(level: &str) -> bool {
1342    level.trim_start().starts_with('{') && level.contains('#')
1343}
1344
1345/// A displayed count or length (`7`, `7.`, `7.0000`), if it is a whole
1346/// number of a sane size.
1347fn parse_count(level: &str) -> Option<usize> {
1348    let x = parse_real(level)?;
1349    (x.fract() == 0.0 && (0.0..1.0e6).contains(&x)).then_some(x as usize)
1350}
1351
1352/// Turn a reply with an error into [`Error::Calculator`].
1353fn checked(reply: StackReply) -> Result<StackReply> {
1354    match reply.error {
1355        Some(message) => Err(Error::Calculator {
1356            message,
1357            stack: reply.levels,
1358        }),
1359        None => Ok(reply),
1360    }
1361}
1362
1363/// `'NAME'` after [`validate_name`].
1364fn quote(name: &str) -> Result<String> {
1365    validate_name(name)?;
1366    Ok(format!("'{name}'"))
1367}
1368
1369/// Check that `name` is a plain global variable name
1370/// (`saturnus_objects::transfer::is_plain_name`: 1 to 127 characters, not
1371/// starting with a digit or `.`, no whitespace, control characters,
1372/// backslash, `@` or RPL delimiters and operators, encodable in the HP character
1373/// set). The names Windows reserves for devices (`CON`, `NUL`, `COM1`, ...,
1374/// also with an extension such as `NUL.X`, any case) are refused on every
1375/// platform: a name is the default file name of a download, and the
1376/// calculator has commands of most of these names anyway.
1377pub fn validate_name(name: &str) -> Result<()> {
1378    if !saturnus_objects::transfer::is_plain_name(name) || is_windows_device(name) {
1379        return Err(Error::Name(name.to_string()));
1380    }
1381    Ok(())
1382}
1383
1384/// `CON`, `PRN`, `AUX`, `NUL`, `COM1`-`COM9` or `LPT1`-`LPT9`, in any case,
1385/// alone or before a `.`.
1386fn is_windows_device(name: &str) -> bool {
1387    let stem = name
1388        .split('.')
1389        .next()
1390        .unwrap_or_default()
1391        .to_ascii_uppercase();
1392    match stem.as_bytes() {
1393        b"CON" | b"PRN" | b"AUX" | b"NUL" => true,
1394        [b'C', b'O', b'M', d] | [b'L', b'P', b'T', d] => (b'1'..=b'9').contains(d),
1395        _ => false,
1396    }
1397}
1398
1399#[cfg(test)]
1400#[allow(clippy::unwrap_used, clippy::expect_used)]
1401pub(crate) mod tests {
1402    use super::*;
1403    use crate::session::Options;
1404    use crate::transport::MemoryTransport;
1405    use kermit_proto::codec::{BlockCheck, Deframer, Framing, Packet, parse_frame};
1406    use kermit_proto::prefix::{self, Quoting};
1407    use std::sync::{Arc, Mutex};
1408
1409    pub(crate) type Log = Arc<Mutex<Vec<String>>>;
1410
1411    /// A Kermit server answering `C` and `G D` like the 48SX trace
1412    /// `48sx-host.trace`, with block check type 1: S, then X, D.., Z, B,
1413    /// each after the ACK of the previous one. `reply` maps the decoded
1414    /// command (`G D` for the listing) to the reply text.
1415    pub(crate) fn fake_server(
1416        log: Log,
1417        mut reply: impl FnMut(&str) -> String + Send + 'static,
1418    ) -> impl FnMut(&[u8]) -> Vec<Vec<u8>> + Send {
1419        let check = BlockCheck::Type1;
1420        let mut deframer = Deframer::new();
1421        let mut queue: Vec<Packet> = Vec::new();
1422        move |bytes| {
1423            let wire = |p: &Packet| p.encode(check, &Framing::default()).unwrap();
1424            deframer.push(bytes);
1425            let mut out = Vec::new();
1426            while let Some(frame) = deframer.next_frame() {
1427                let p = parse_frame(&frame, check).unwrap();
1428                let data = prefix::decode(&p.data, &Quoting::default()).unwrap();
1429                match p.kind {
1430                    b'G' if data == b"F" => {
1431                        // FINISH: a plain ACK.
1432                        log.lock().unwrap().push("G F".into());
1433                        out.push(wire(&Packet::new(p.seq, b'Y', Vec::new())));
1434                    }
1435                    b'C' | b'G' => {
1436                        let command = if p.kind == b'G' {
1437                            format!("G {}", decode(&data))
1438                        } else {
1439                            decode(&data)
1440                        };
1441                        log.lock().unwrap().push(command.clone());
1442                        let reply = reply(&command);
1443                        // `SILENT` never answers (the client times out);
1444                        // `E:message` plays an E packet instead of a reply.
1445                        if reply == "SILENT" {
1446                            queue.clear();
1447                            continue;
1448                        }
1449                        if let Some(message) = reply.strip_prefix("E:") {
1450                            queue.clear();
1451                            out.push(wire(&Packet::new(0, b'E', message.as_bytes().to_vec())));
1452                            continue;
1453                        }
1454                        let text = encode(&reply).unwrap();
1455                        queue = vec![Packet::new(1, b'X', Vec::new())];
1456                        let mut rest = text.as_slice();
1457                        while !rest.is_empty() {
1458                            let (enc, used) = prefix::encode(rest, &Quoting::default(), 90);
1459                            let seq = u8::try_from(queue.len() + 1).unwrap();
1460                            queue.push(Packet::new(seq, b'D', enc));
1461                            rest = &rest[used..];
1462                        }
1463                        let seq = u8::try_from(queue.len() + 1).unwrap();
1464                        queue.push(Packet::new(seq, b'Z', Vec::new()));
1465                        queue.push(Packet::new(seq + 1, b'B', Vec::new()));
1466                        out.push(wire(&Packet::new(0, b'S', b"~* @-#Y1 ".to_vec())));
1467                    }
1468                    b'Y' => {
1469                        if let Some(next) = queue.iter().find(|q| q.seq == p.seq + 1) {
1470                            out.push(wire(next));
1471                        }
1472                    }
1473                    // A reply packet NAKed: send it again.
1474                    b'N' => {
1475                        if let Some(again) = queue.iter().find(|q| q.seq == p.seq) {
1476                            out.push(wire(again));
1477                        }
1478                    }
1479                    // The client gave up (timeout).
1480                    b'E' => queue.clear(),
1481                    kind => panic!("unexpected packet {}", char::from(kind)),
1482                }
1483            }
1484            out
1485        }
1486    }
1487
1488    fn calc(reply: impl FnMut(&str) -> String + Send + 'static) -> (Calculator, Log) {
1489        let log: Log = Arc::default();
1490        let transport = MemoryTransport::new(fake_server(Arc::clone(&log), reply));
1491        let mut kermit = Options::default().kermit;
1492        kermit.timeout = Duration::from_millis(200);
1493        // The fake server never repeats a B: no linger, no wait.
1494        kermit.linger = Duration::ZERO;
1495        let options = Options {
1496            kermit,
1497            drain: Duration::ZERO,
1498            turnaround: Duration::ZERO,
1499        };
1500        let session = Session::new(Box::new(transport), options).unwrap();
1501        (Calculator::new(session), log)
1502    }
1503
1504    fn sent(log: &Log) -> Vec<String> {
1505        log.lock().unwrap().clone()
1506    }
1507
1508    const EMPTY: &str = "Empty Stack\r\n";
1509    const GX_DIR: &str =
1510        "{ HOME D1 } 127847\r\nX 10.5 Real Number 1234\r\nSUB 5.5 Directory 4321\r\n";
1511    const SX_DIR: &str = "X 10.5 Real Number 1234\r\nSUB 5.5 Directory 4321\r\n";
1512
1513    /// The 48SX's `RCLF` as the emulated one shows it.
1514    const SX_FLAGS: &str = "{ # 1008d # 0d }";
1515    /// The emulated 49G's (ROM 2.15) `RCLF`, cut at 22 characters.
1516    const G49_FLAGS: &str = "{# 2000204010FF0h,# 0h";
1517
1518    #[test]
1519    fn mem_drops_its_value() {
1520        let (mut c, log) = calc(|cmd| match cmd {
1521            MEM_STD => format!("2: {SX_FLAGS}\r\n1:              12345\r\n"),
1522            _ => EMPTY.into(),
1523        });
1524        assert_eq!(c.mem().unwrap(), 12345.0);
1525        assert_eq!(sent(&log), [MEM_STD, "DROP STOF"]);
1526    }
1527
1528    #[test]
1529    fn path_from_listing_header() {
1530        let (mut c, log) = calc(|cmd| match cmd {
1531            "G D" => GX_DIR.into(),
1532            _ => panic!("unexpected {cmd}"),
1533        });
1534        assert_eq!(c.path().unwrap(), ["HOME", "D1"]);
1535        assert_eq!(sent(&log), ["G D"]);
1536    }
1537
1538    const MARKER: &str = "SATX-0a1b2c";
1539    const MARKER_CMD: &str = "\"SATX-0a1b2c\"";
1540
1541    /// Sync with [`MARKER`] against a server whose replies to the marker
1542    /// command are `replies` in order (then an empty stack); the log of
1543    /// what was sent.
1544    fn sync_against(replies: Vec<&'static str>) -> Vec<String> {
1545        let (result, log) = try_sync_against(replies);
1546        result.unwrap();
1547        log
1548    }
1549
1550    /// [`sync_against`] without the unwrap.
1551    fn try_sync_against(replies: Vec<&'static str>) -> (Result<()>, Vec<String>) {
1552        let mut replies = replies.into_iter();
1553        let (mut c, log) = calc(move |cmd| match cmd {
1554            MARKER_CMD => replies.next().unwrap_or(EMPTY).into(),
1555            "DROP" | "DROP2" => EMPTY.into(),
1556            _ => panic!("unexpected {cmd}"),
1557        });
1558        let result = c.sync_with(MARKER);
1559        (result, sent(&log))
1560    }
1561
1562    fn assert_not_in_step(result: Result<()>) {
1563        assert!(
1564            matches!(&result, Err(Error::Reply(m)) if m.contains("not in step")),
1565            "{result:?}"
1566        );
1567    }
1568
1569    #[test]
1570    fn sync_marker_is_short_and_plain() {
1571        let m = sync_marker();
1572        assert_eq!(m.len(), 11, "{m}");
1573        assert!(m.starts_with("SATX-"));
1574        assert!(m[5..].chars().all(|c| c.is_ascii_hexdigit()), "{m}");
1575        assert_ne!(sync_marker(), sync_marker());
1576    }
1577
1578    #[test]
1579    fn sync_in_step_costs_two_transactions() {
1580        let one = "1:      \"SATX-0a1b2c\"\r\n";
1581        assert_eq!(sync_against(vec![one]), [MARKER_CMD, "DROP"]);
1582    }
1583
1584    /// The first command after an aborted client is eaten by the server and
1585    /// answered with the late reply of the aborted command (here a stack
1586    /// display): sync sends the marker again and drops only the marker.
1587    #[test]
1588    fn sync_skips_a_stale_reply() {
1589        let stale = "2:                  1\r\n1:                  2\r\n";
1590        let ours = "3:                  1\r\n2:                  2\r\n1:      \"SATX-0a1b2c\"\r\n";
1591        assert_eq!(
1592            sync_against(vec![stale, ours]),
1593            [MARKER_CMD, MARKER_CMD, "DROP"]
1594        );
1595    }
1596
1597    /// A late reply that is a 49G path cut at the display width (no closing
1598    /// brace, fixture `49g-vars.txt` style) is not taken for ours.
1599    #[test]
1600    fn sync_skips_a_truncated_path_reply() {
1601        let stale = "1: {HOME,SATXAAAA,SATXBB\r\n";
1602        let ours = "2: {HOME,SATXAAAA,SATXBB\r\n1:      \"SATX-0a1b2c\"\r\n";
1603        assert_eq!(
1604            sync_against(vec![stale, ours]),
1605            [MARKER_CMD, MARKER_CMD, "DROP"]
1606        );
1607    }
1608
1609    /// The aborted command's own result was a path: it stays on the stack.
1610    #[test]
1611    fn sync_keeps_a_path_shaped_stale_result() {
1612        let stale = "1:          { HOME }\r\n";
1613        let ours = "2:          { HOME }\r\n1:      \"SATX-0a1b2c\"\r\n";
1614        // One DROP for the marker; the path at level 2 is the user's.
1615        assert_eq!(
1616            sync_against(vec![stale, ours]),
1617            [MARKER_CMD, MARKER_CMD, "DROP"]
1618        );
1619    }
1620
1621    /// In a deep 49G directory the stack shows truncated values; the marker
1622    /// at level 1 is recognised all the same and only it is dropped.
1623    #[test]
1624    fn sync_in_a_deep_49g_directory() {
1625        let ours = "2: {D1,G,TG,B,C,A,P,L,S,R\r\n1: \"SATX-0a1b2c\"\r\n";
1626        assert_eq!(sync_against(vec![ours]), [MARKER_CMD, "DROP"]);
1627    }
1628
1629    /// Our first marker command was not eaten after all: both copies are
1630    /// ours and both go.
1631    #[test]
1632    fn sync_drops_every_copy_of_its_marker() {
1633        let stale = "Error: Bad Argument Type\r\n";
1634        let ours =
1635            "3:                  7\r\n2:      \"SATX-0a1b2c\"\r\n1:      \"SATX-0a1b2c\"\r\n";
1636        assert_eq!(
1637            sync_against(vec![stale, ours]),
1638            [MARKER_CMD, MARKER_CMD, "DROP2"]
1639        );
1640    }
1641
1642    /// An E packet (the calculator aborting a leftover transfer) is an odd
1643    /// reply, not an error: the marker goes again.
1644    #[test]
1645    fn sync_survives_an_error_packet() {
1646        let ours = "1:      \"SATX-0a1b2c\"\r\n";
1647        assert_eq!(
1648            sync_against(vec!["E:Transfer Failed", ours]),
1649            [MARKER_CMD, MARKER_CMD, "DROP"]
1650        );
1651        let (result, log) = try_sync_against(vec!["E:Transfer Failed", "E:Transfer Failed"]);
1652        assert_eq!(log, [MARKER_CMD, MARKER_CMD]);
1653        assert_not_in_step(result);
1654    }
1655
1656    /// The first marker command ran but its reply never came (timeout): the
1657    /// second reply shows both markers and both go. A second timeout is a
1658    /// link failure.
1659    #[test]
1660    fn sync_retries_once_after_a_timeout() {
1661        let mut n = 0;
1662        let (mut c, log) = calc(move |cmd| {
1663            n += 1;
1664            match (cmd, n) {
1665                (MARKER_CMD, 1) => "SILENT".into(),
1666                (MARKER_CMD, _) => {
1667                    "3:                  7\r\n2:      \"SATX-0a1b2c\"\r\n1:      \"SATX-0a1b2c\"\r\n"
1668                        .into()
1669                }
1670                ("DROP2", _) => EMPTY.into(),
1671                _ => panic!("unexpected {cmd}"),
1672            }
1673        });
1674        c.sync_with(MARKER).unwrap();
1675        assert_eq!(sent(&log), [MARKER_CMD, MARKER_CMD, "DROP2"]);
1676        // The normal budget is back for everything after the sync.
1677        assert_eq!(
1678            c.session().config().retries,
1679            Options::default().kermit.retries
1680        );
1681
1682        let (mut c, log) = calc(|_| "SILENT".into());
1683        let err = c.sync_with(MARKER).unwrap_err();
1684        assert!(
1685            matches!(err, Error::Kermit(kermit_proto::Error::Timeout)),
1686            "{err:?}"
1687        );
1688        // The first attempt is one try (no retransmission), the second the
1689        // normal budget (1 + 5); only the marker is ever sent.
1690        let log = sent(&log);
1691        assert_eq!(log.len(), 1 + 6, "{log:?}");
1692        assert!(log.iter().all(|c| c == MARKER_CMD), "{log:?}");
1693    }
1694
1695    /// Audit PR #18, #2: two odd replies in a row are an error (they used
1696    /// to be accepted as success). Nothing is dropped and there is no third
1697    /// attempt: a marker below level 1 or another marker is not ours to
1698    /// drop.
1699    #[test]
1700    fn sync_never_drops_what_it_did_not_push() {
1701        let error = "Error: Bad Argument Type\r\n1:                  1\r\n";
1702        let (result, log) = try_sync_against(vec![error, EMPTY]);
1703        assert_eq!(log, [MARKER_CMD, MARKER_CMD]);
1704        assert_not_in_step(result);
1705        let below = "2:      \"SATX-0a1b2c\"\r\n1:                  1\r\n";
1706        let other = "1:      \"SATX-ffffff\"\r\n";
1707        let (result, log) = try_sync_against(vec![below, other]);
1708        assert_eq!(log, [MARKER_CMD, MARKER_CMD]);
1709        assert_not_in_step(result);
1710    }
1711
1712    /// Audit PR #18, #1: a host command goes out once. Its reply is late
1713    /// (never comes here) and a NAK is read within the `C`'s wire time (a
1714    /// stale NAK of the idle server that was waiting in the input, read at
1715    /// once, or one sent while the `C` was on the wire, read halfway
1716    /// through it; PR #26 review, #1): no `C` is resent, neither after the
1717    /// NAK nor after the timeout, and the error says the command may have
1718    /// run. On a fake clock through the [`Machine`](crate::Machine): with
1719    /// the real clock a runner that stalled for the `C`'s wire time
1720    /// (~17 ms) between sending it and reading the NAK made it the
1721    /// calculator's rejection, and the `C` went out twice (macOS CI, PR
1722    /// 147). That the session's retries come back after a host command is
1723    /// [`host_command_late_nak_is_not_resent`]'s check.
1724    #[test]
1725    fn host_command_is_never_resent() {
1726        use crate::machine::{Machine, Op};
1727        use crate::time::Instant;
1728        for halves in [0, 1] {
1729            let log: Log = Arc::default();
1730            let mut server = fake_server(Arc::clone(&log), |_| "SILENT".into());
1731            let check = BlockCheck::Type1;
1732            let mut deframer = Deframer::new();
1733            let timeout = Duration::from_millis(300);
1734            let mut kermit = Options::default().kermit;
1735            kermit.timeout = timeout;
1736            let options = Options {
1737                kermit,
1738                drain: Duration::ZERO,
1739                turnaround: Duration::ZERO,
1740            };
1741            let t0 = Instant::now();
1742            let mut clock = t0;
1743            let mut m = Machine::new(clock, options, 1);
1744            m.set_events(false);
1745            m.start(clock, Op::Run("1 'X' STO+".into())).unwrap();
1746            let mut result = None;
1747            for _ in 0..1000 {
1748                while let Some(bytes) = m.poll_transmit() {
1749                    let mut out = server(&bytes);
1750                    // A NAK after each C, at once or halfway through its
1751                    // wire time: a stale one from the idle server, or the
1752                    // server asking for the C again.
1753                    deframer.push(&bytes);
1754                    while let Some(frame) = deframer.next_frame() {
1755                        if parse_frame(&frame, check).unwrap().kind == b'C' {
1756                            let nak = Packet::new(0, b'N', Vec::new());
1757                            out.push(nak.encode(check, &Framing::default()).unwrap());
1758                            let wire = HOST_BYTE_TIME * u32::try_from(bytes.len()).unwrap();
1759                            clock += wire * halves / 2;
1760                        }
1761                    }
1762                    for chunk in out {
1763                        m.handle_input(clock, &chunk);
1764                    }
1765                }
1766                result = m.poll_result();
1767                if result.is_some() {
1768                    break;
1769                }
1770                let deadline = m.next_timeout().expect("waits without a deadline");
1771                clock = clock.max(deadline);
1772                m.handle_timeout(clock);
1773            }
1774            let err = result.expect("no result").unwrap_err();
1775            assert!(
1776                matches!(&err, Error::NoReply { command } if command == "1 'X' STO+"),
1777                "{err:?}"
1778            );
1779            assert!(err.to_string().contains("may have run"), "{err}");
1780            assert_eq!(sent(&log), ["1 'X' STO+"], "NAK after {halves}/2 wire time");
1781            // The NAK did not cut the wait short (the old grace was 1 s, here
1782            // longer than the timeout; the deadline is the full timeout).
1783            assert!(clock - t0 >= timeout, "{:?}", clock - t0);
1784        }
1785    }
1786
1787    /// Iteration 13: the idle server's NAK (it NAKs once, a server timeout
1788    /// after its last packet, and then stays silent) arrives after
1789    /// [`HOST_NAK_WINDOW`] (300 ms after the `C`), with the reply late
1790    /// (never here): it may have crossed a `C` the server took, so no `C` is
1791    /// resent, and the wait is the full timeout.
1792    #[test]
1793    fn host_command_late_nak_is_not_resent() {
1794        let log: Log = Arc::default();
1795        let mut server = fake_server(Arc::clone(&log), |_| "SILENT".into());
1796        let check = BlockCheck::Type1;
1797        let mut deframer = Deframer::new();
1798        let transport = MemoryTransport::new(move |bytes: &[u8]| {
1799            let mut out = server(bytes);
1800            // A NAK after each C, outside the immediate-NAK window: a
1801            // stale one from the idle server that crossed the C.
1802            deframer.push(bytes);
1803            while let Some(frame) = deframer.next_frame() {
1804                if parse_frame(&frame, check).unwrap().kind == b'C' {
1805                    std::thread::sleep(HOST_NAK_WINDOW + Duration::from_millis(50));
1806                    let nak = Packet::new(0, b'N', Vec::new());
1807                    out.push(nak.encode(check, &Framing::default()).unwrap());
1808                }
1809            }
1810            out
1811        });
1812        let mut kermit = Options::default().kermit;
1813        kermit.timeout = Duration::from_millis(600);
1814        let options = Options {
1815            kermit,
1816            drain: Duration::ZERO,
1817            turnaround: Duration::ZERO,
1818        };
1819        let mut c = Calculator::new(Session::new(Box::new(transport), options).unwrap());
1820        let start = std::time::Instant::now();
1821        let err = c.run("1 'X' STO+").unwrap_err();
1822        assert!(
1823            matches!(&err, Error::NoReply { command } if command == "1 'X' STO+"),
1824            "{err:?}"
1825        );
1826        assert!(err.to_string().contains("may have run"), "{err}");
1827        assert_eq!(sent(&log), ["1 'X' STO+"]);
1828        // The NAK did not cut the wait short (the old grace was 1 s, here
1829        // longer than the timeout; the deadline is the full timeout).
1830        assert!(start.elapsed() >= Duration::from_millis(600));
1831        // The session's own budget is back for the next transaction.
1832        assert_eq!(
1833            c.session().config().retries,
1834            Options::default().kermit.retries
1835        );
1836        assert_eq!(c.session().config().first_packet_retries, None);
1837    }
1838
1839    /// Iteration 13 (Saturnus trace, 48SX): the calculator NAKs a `C` at
1840    /// once and never answers it (it rejected the packet; the command did
1841    /// not run). The `C` is resent once after the immediate-NAK grace, and
1842    /// the answer to the resend completes the command, which ran once. The
1843    /// wiring only; the timing is kermit-proto's `immediate_nak_*` tests.
1844    #[test]
1845    fn host_command_rejected_at_once_is_resent() {
1846        let log: Log = Arc::default();
1847        let mut server = fake_server(Arc::clone(&log), |_| "1:                 42\r\n".into());
1848        let wire: Log = Arc::default();
1849        let on_wire = Arc::clone(&wire);
1850        let check = BlockCheck::Type1;
1851        let mut deframer = Deframer::new();
1852        let transport = MemoryTransport::new(move |bytes: &[u8]| {
1853            deframer.push(bytes);
1854            let mut first_c = false;
1855            while let Some(frame) = deframer.next_frame() {
1856                if parse_frame(&frame, check).unwrap().kind == b'C' {
1857                    let mut seen = on_wire.lock().unwrap();
1858                    seen.push("C".into());
1859                    first_c = seen.len() == 1;
1860                }
1861            }
1862            if first_c {
1863                // Rejected: a NAK once the C is in (after its wire time at
1864                // 9600 baud, ~11 ms); the server never runs the C.
1865                std::thread::sleep(Duration::from_millis(30));
1866                let nak = Packet::new(0, b'N', Vec::new());
1867                return vec![nak.encode(check, &Framing::default()).unwrap()];
1868            }
1869            server(bytes)
1870        });
1871        // A short timeout: the immediate-NAK grace is capped by it.
1872        let mut kermit = Options::default().kermit;
1873        kermit.timeout = Duration::from_millis(300);
1874        kermit.linger = Duration::ZERO;
1875        let options = Options {
1876            kermit,
1877            drain: Duration::ZERO,
1878            turnaround: Duration::ZERO,
1879        };
1880        let mut c = Calculator::new(Session::new(Box::new(transport), options).unwrap());
1881        assert_eq!(c.run("6 7 *").unwrap().levels, ["42"]);
1882        assert_eq!(sent(&wire), ["C", "C"]);
1883        assert_eq!(sent(&log), ["6 7 *"]);
1884        // The session's own config is back for the next transaction.
1885        assert_eq!(c.session().config().first_packet_nak_window, None);
1886    }
1887
1888    /// A calculator over `fake_server` whose D packets are lost `drop`
1889    /// times (`usize::MAX`: always).
1890    fn calc_dropping_data(
1891        drop: usize,
1892        reply: impl FnMut(&str) -> String + Send + 'static,
1893    ) -> (Calculator, Log) {
1894        let log: Log = Arc::default();
1895        let mut server = fake_server(Arc::clone(&log), reply);
1896        let mut left = drop;
1897        let mut deframer = Deframer::new();
1898        let transport = MemoryTransport::new(move |bytes: &[u8]| {
1899            let mut out = server(bytes);
1900            out.retain(|chunk| {
1901                deframer.push(chunk);
1902                let data = deframer
1903                    .next_frame()
1904                    .is_some_and(|f| parse_frame(&f, BlockCheck::Type1).unwrap().kind == b'D');
1905                if data && left > 0 {
1906                    left -= 1;
1907                    return false;
1908                }
1909                true
1910            });
1911            out
1912        });
1913        let mut kermit = Options::default().kermit;
1914        kermit.timeout = Duration::from_millis(100);
1915        kermit.linger = Duration::ZERO;
1916        let options = Options {
1917            kermit,
1918            drain: Duration::ZERO,
1919            turnaround: Duration::ZERO,
1920        };
1921        let session = Session::new(Box::new(transport), options).unwrap();
1922        (Calculator::new(session), log)
1923    }
1924
1925    /// PR #20 review: the single-shot rule covers the `C` only. A reply
1926    /// packet lost after the calculator's `S` is re-requested, and a reply
1927    /// that never completes is a Kermit timeout (the command ran), not
1928    /// `NoReply`.
1929    #[test]
1930    fn host_reply_packets_keep_their_retries() {
1931        let reply = |_: &str| "1:                 42\r\n".to_string();
1932        let (mut c, log) = calc_dropping_data(1, reply);
1933        assert_eq!(c.run("6 7 *").unwrap().levels, ["42"]);
1934        assert_eq!(sent(&log), ["6 7 *"]);
1935
1936        let (mut c, log) = calc_dropping_data(usize::MAX, reply);
1937        let err = c.run("6 7 *").unwrap_err();
1938        assert!(
1939            matches!(err, Error::Kermit(kermit_proto::Error::Timeout)),
1940            "{err:?}"
1941        );
1942        assert_eq!(sent(&log), ["6 7 *"]);
1943    }
1944
1945    /// `fake_server` behind a link that swallows the first `R` packet (a
1946    /// GET) and fails the read after it once: a transient link error.
1947    struct GlitchOnGet {
1948        inner: MemoryTransport,
1949        fail_next_read: bool,
1950        glitched: bool,
1951    }
1952
1953    impl Transport for GlitchOnGet {
1954        fn write_packet(&mut self, packet: &[u8]) -> std::io::Result<()> {
1955            if !self.glitched && packet.get(3) == Some(&b'R') {
1956                self.glitched = true;
1957                self.fail_next_read = true;
1958                return Ok(());
1959            }
1960            self.inner.write_packet(packet)
1961        }
1962
1963        fn read(&mut self, buf: &mut [u8], timeout: Duration) -> std::io::Result<usize> {
1964            if std::mem::take(&mut self.fail_next_read) {
1965                return Err(std::io::Error::other("glitch"));
1966            }
1967            self.inner.read(buf, timeout)
1968        }
1969    }
1970
1971    /// PR 108 review: a link error in PICT's GET does not stop the
1972    /// best-effort PURGE of the temporary variable from trying the link
1973    /// again, as before the seam.
1974    #[test]
1975    fn pict_cleanup_tries_the_link_after_a_link_error() {
1976        let log: Log = Arc::default();
1977        let server = fake_server(Arc::clone(&log), |cmd: &str| match cmd {
1978            "G D" => SX_DIR.into(),
1979            _ => EMPTY.into(),
1980        });
1981        let transport = GlitchOnGet {
1982            inner: MemoryTransport::new(server),
1983            fail_next_read: false,
1984            glitched: false,
1985        };
1986        let mut kermit = Options::default().kermit;
1987        kermit.timeout = Duration::from_millis(200);
1988        kermit.linger = Duration::ZERO;
1989        let options = Options {
1990            kermit,
1991            drain: Duration::ZERO,
1992            turnaround: Duration::ZERO,
1993        };
1994        let mut c = Calculator::new(Session::new(Box::new(transport), options).unwrap());
1995        let err = c.pict().unwrap_err();
1996        assert!(
1997            matches!(&err, Error::Io(e) if e.to_string() == "glitch"),
1998            "{err:?}"
1999        );
2000        assert_eq!(
2001            sent(&log),
2002            ["G D", "PICT RCL 'SATXTMP' STO", "-35 SF", "'SATXTMP' PURGE"]
2003        );
2004    }
2005
2006    /// A `STO` that fails for lack of room leaves the name and the recalled
2007    /// archive on the stack; they go first, or the port object's `PURGE`
2008    /// fails with "Object In Use". Any other failure drops nothing.
2009    #[test]
2010    fn a_failed_backup_drops_what_keeps_the_port_object_in_use() {
2011        for (level, dropped) in [("'SATXBK'", true), ("SATXBK", true), ("'OTHER'", false)] {
2012            let (mut c, log) = calc(move |cmd| match cmd {
2013                "G D" => "{ HOME } 1000\r\n".to_string(),
2014                ":0:SATXBK RCL 'SATXBK' STO :0:SATXBK PURGE" => {
2015                    format!("Error: Insufficient Memory\r\n2: Directory\r\n1: {level}\r\n")
2016                }
2017                _ => "Empty Stack\r\n".to_string(),
2018            });
2019            let err = c.backup().unwrap_err();
2020            assert!(matches!(err, Error::Calculator { .. }), "{err:?}");
2021            let sent = log.lock().unwrap().clone();
2022            let purge = sent.iter().position(|s| s == ":0:SATXBK PURGE").unwrap();
2023            let drop2 = sent.iter().position(|s| s == "DROP2");
2024            if dropped {
2025                assert!(drop2.is_some_and(|d| d < purge), "{sent:?}");
2026            } else {
2027                assert_eq!(drop2, None, "{sent:?}");
2028            }
2029        }
2030    }
2031
2032    /// Audit PR #18, #3: a backup whose directory walk fails (here cut in
2033    /// half) is refused before anything is sent; it used to pass on its
2034    /// Directory prolog alone and reach RESTORE.
2035    #[test]
2036    fn restore_refuses_a_truncated_backup() {
2037        let path = format!("{}/fixtures/48sx-D1.hp", env!("CARGO_MANIFEST_DIR"));
2038        let full = std::fs::read(path).unwrap();
2039        let cut = &full[..full.len() / 2];
2040        assert_eq!(
2041            inspect(cut).unwrap().object_type,
2042            Some(ObjectType::Directory)
2043        );
2044        let (mut c, log) = calc(|cmd| panic!("unexpected {cmd}"));
2045        let err = c.restore(cut).unwrap_err();
2046        assert!(
2047            matches!(&err, Error::Object(m) if m.starts_with("not a backup")),
2048            "{err:?}"
2049        );
2050        assert!(sent(&log).is_empty());
2051    }
2052
2053    /// PR #20 review: a backup holding a directory with an attached
2054    /// library (field #123, not #7FF) is a backup like any other.
2055    #[test]
2056    fn check_backup_accepts_an_attached_library() {
2057        let nibbles = |lib: u32| -> Vec<u8> {
2058            let mut n = Vec::new();
2059            for (value, width) in [(0x02A96u32, 5), (lib, 3), (0, 5)] {
2060                n.extend((0..width).map(|i| ((value >> (4 * i)) & 0xF) as u8));
2061            }
2062            n
2063        };
2064        for lib in [0x7FF, 0x123] {
2065            let mut data = b"HPHP48-R".to_vec();
2066            data.extend(crate::object::pack(&nibbles(lib)));
2067            check_backup(&data).unwrap();
2068        }
2069    }
2070
2071    /// Audit PR #18, #9: no reply to RESTORE is success only when the probe
2072    /// after it gets no reply either (the warm start ended server mode); an
2073    /// answered probe leaves the result unknown (PR #20 review: SERVER may
2074    /// have been restarted after a RESTORE that ran).
2075    #[test]
2076    fn restore_probe_after_the_silent_restore() {
2077        const RESTORE: &str = ":0:SATXRS RESTORE";
2078        // RESTORE ran: the calculator is gone, the probe times out.
2079        let (mut c, log) = calc(|_| "SILENT".into());
2080        c.restore_from_port().unwrap();
2081        let log = sent(&log);
2082        assert_eq!(log.len(), 2, "{log:?}");
2083        assert_eq!(log[0], RESTORE);
2084        assert!(log[1].starts_with("\"SATX-"), "{log:?}");
2085
2086        // The server answers the probe: RESTORE lost, or SERVER restarted.
2087        let (mut c, log) = calc(|cmd| match cmd {
2088            RESTORE => "SILENT".into(),
2089            "DROP" => EMPTY.into(),
2090            probe => format!("1: {probe}\r\n"),
2091        });
2092        let err = c.restore_from_port().unwrap_err();
2093        assert!(
2094            matches!(&err, Error::Reply(m) if m.contains("RESTORE's result is unknown")),
2095            "{err:?}"
2096        );
2097        let log = sent(&log);
2098        assert_eq!(log.len(), 3, "{log:?}");
2099        assert_eq!(log[2], "DROP", "the probe's marker is dropped");
2100    }
2101
2102    #[test]
2103    fn path_query_without_header() {
2104        let (mut c, log) = calc(|cmd| match cmd {
2105            "G D" => SX_DIR.into(),
2106            "PATH" => "1:          { HOME D1 }\r\n".into(),
2107            _ => EMPTY.into(),
2108        });
2109        assert_eq!(c.path().unwrap(), ["HOME", "D1"]);
2110        assert_eq!(sent(&log), ["G D", "PATH", "DROP"]);
2111    }
2112
2113    #[test]
2114    fn version_48sx() {
2115        let (mut c, log) = calc(|cmd| match cmd {
2116            "VERSION" => "1:  'VERSION'\r\n".into(),
2117            _ => EMPTY.into(),
2118        });
2119        assert_eq!(c.version().unwrap(), None);
2120        assert_eq!(sent(&log), ["VERSION", "DROP"]);
2121    }
2122
2123    #[test]
2124    fn version_48gx() {
2125        let (mut c, log) = calc(|cmd| match cmd {
2126            "VERSION" => "2:     \"Version HP48-R\"\r\n1:  \"Copyright HP 1993\"\r\n".into(),
2127            _ => EMPTY.into(),
2128        });
2129        assert_eq!(
2130            c.version().unwrap().as_deref(),
2131            Some("Version HP48-R, Copyright HP 1993")
2132        );
2133        assert_eq!(sent(&log), ["VERSION", "DROP2"]);
2134    }
2135
2136    /// A two-line version string that arrived whole.
2137    #[test]
2138    fn version_49g_two_line_string() {
2139        let (mut c, _) = calc(|cmd| match cmd {
2140            "VERSION" => {
2141                "2: \"Version HP49-C\r\nRevision #1.19-6\"\r\n1:  \"Copyright HP 2009\"\r\n".into()
2142            }
2143            _ => EMPTY.into(),
2144        });
2145        assert_eq!(
2146            c.version().unwrap().as_deref(),
2147            Some("Version HP49-C Revision #1.19-6, Copyright HP 2009")
2148        );
2149    }
2150
2151    /// The stack reply to [`VERSION_CHUNKS`] with `version` and
2152    /// `copyright` on the stack above `below` (deepest first): the saved
2153    /// flags, the chunks, the total.
2154    fn chunk_reply(version: &str, copyright: &str, below: &[&str]) -> String {
2155        let joined: Vec<char> = format!("{version}{copyright}").chars().collect();
2156        let mut levels: Vec<String> = below.iter().map(|l| (*l).to_string()).collect();
2157        levels.push(G49_FLAGS.to_string());
2158        for chunk in joined.chunks(CHUNK) {
2159            let chunk: String = chunk.iter().collect();
2160            levels.push(format!("\"{}\"", chunk.replace('\n', "\r\n")));
2161        }
2162        levels.push(format!("{}.", joined.len()));
2163        let depth = levels.len();
2164        levels
2165            .iter()
2166            .enumerate()
2167            .map(|(i, level)| format!("{}: {level}\r\n", depth - i))
2168            .collect()
2169    }
2170
2171    /// ROM 1.18 on a real 49G (2026-11-08): `VERSION`'s level 2 cut at 20
2172    /// characters. The whole text comes in chunks; the user's 4711 stays.
2173    #[test]
2174    fn version_49g_1_18_cut_at_the_display_width() {
2175        let (mut c, log) = calc(|cmd| match cmd {
2176            "VERSION" => {
2177                "3: 4711.\r\n2: \"Version HP49-C\r\nRevi\r\n1: \"Copyright HP 2000\"\r\n".into()
2178            }
2179            VERSION_CHUNKS => chunk_reply(
2180                "Version HP49-C\nRevision #1.18",
2181                "Copyright HP 2000",
2182                &["4711."],
2183            ),
2184            _ => EMPTY.into(),
2185        });
2186        let version = c.version().unwrap();
2187        assert_eq!(
2188            version.as_deref(),
2189            Some("Version HP49-C Revision #1.18, Copyright HP 2000")
2190        );
2191        assert_eq!(Model::from_version(version.as_deref()), Model::Hp49G);
2192        // 46 characters: five chunks and the total above the flags.
2193        assert_eq!(sent(&log), ["VERSION", VERSION_CHUNKS, "6. DROPN STOF"]);
2194    }
2195
2196    /// ROM 2.15 on the emulated 49G: level 2 cut at 22 characters; the
2197    /// chunks as it sent them.
2198    #[test]
2199    fn version_49g_2_15_cut_at_the_display_width() {
2200        let (mut c, log) = calc(|cmd| match cmd {
2201            "VERSION" => "2: \"Version HP48-C\r\nRevisi\r\n1: \"Copyright HP 2009\"\r\n".into(),
2202            VERSION_CHUNKS => format!(
2203                "7: {G49_FLAGS}\r\n6: \"Version HP\"\r\n5: \"48-C\r\nRevis\"\r\n\
2204                 4: \"ion #2.15C\"\r\n3: \"opyright H\"\r\n2: \"P 2009\"\r\n1: 46.\r\n"
2205            ),
2206            _ => EMPTY.into(),
2207        });
2208        assert_eq!(
2209            c.version().unwrap().as_deref(),
2210            Some("Version HP48-C Revision #2.15, Copyright HP 2009")
2211        );
2212        assert_eq!(sent(&log), ["VERSION", VERSION_CHUNKS, "6. DROPN STOF"]);
2213    }
2214
2215    /// Chunks that do not add up are an error, and what the command pushed
2216    /// is dropped all the same, the flags put back.
2217    #[test]
2218    fn version_chunks_that_do_not_add_up() {
2219        let (mut c, log) = calc(|cmd| match cmd {
2220            "VERSION" => "2: \"Version HP49-C\r\nRevi\r\n1: \"Copyright HP 2000\"\r\n".into(),
2221            VERSION_CHUNKS => format!(
2222                "4: {G49_FLAGS}\r\n3: \"Version\"\r\n2: \"Copyright HP 2000\"\r\n1: 20.\r\n"
2223            ),
2224            _ => EMPTY.into(),
2225        });
2226        let err = c.version().unwrap_err();
2227        assert!(
2228            matches!(&err, Error::Reply(m) if m.contains("bad chunks")),
2229            "{err:?}"
2230        );
2231        assert_eq!(sent(&log), ["VERSION", VERSION_CHUNKS, "3. DROPN STOF"]);
2232    }
2233
2234    /// The copyright cut and the version whole: the version tells where
2235    /// the two meet.
2236    #[test]
2237    fn version_with_the_copyright_cut() {
2238        let (mut c, log) = calc(|cmd| match cmd {
2239            "VERSION" => "2: \"HP49-C\"\r\n1: \"Copyright HP 2000 and l\r\n".into(),
2240            VERSION_CHUNKS => chunk_reply("HP49-C", "Copyright HP 2000 and later", &[]),
2241            _ => EMPTY.into(),
2242        });
2243        assert_eq!(
2244            c.version().unwrap().as_deref(),
2245            Some("HP49-C, Copyright HP 2000 and later")
2246        );
2247        assert_eq!(sent(&log), ["VERSION", VERSION_CHUNKS, "5. DROPN STOF"]);
2248    }
2249
2250    /// Both strings cut: nothing tells where they meet; they are dropped.
2251    #[test]
2252    fn version_with_both_strings_cut() {
2253        let (mut c, log) = calc(|cmd| match cmd {
2254            "VERSION" => "2: \"Version HP49-C\r\nRevi\r\n1: \"Copyright HP 2000 an\r\n".into(),
2255            _ => EMPTY.into(),
2256        });
2257        let err = c.version().unwrap_err();
2258        assert!(
2259            matches!(&err, Error::Reply(m) if m.contains("both")),
2260            "{err:?}"
2261        );
2262        assert_eq!(sent(&log), ["VERSION", "DROP2"]);
2263    }
2264
2265    /// A failed chunk command leaves what it pushed and the two strings (or
2266    /// what became of them); all of it above the user's 4711 is dropped,
2267    /// and the flags are put back if it got as far as saving them.
2268    #[test]
2269    fn version_chunks_that_fail() {
2270        let cut = "3: 4711.\r\n2: \"Version HP49-C\r\nRevi\r\n1: \"Copyright HP 2000\"\r\n";
2271        let after_rclf = format!(
2272            "Error: Insufficient Memory\r\n5: 4711.\r\n4: {G49_FLAGS}\r\n\
2273             3: \"Version HP\"\r\n2: \"49-C\r\nRevis\"\r\n1: \"Version HP49-C\r\nRevi\r\n"
2274        );
2275        let before_rclf = format!("Error: Insufficient Memory\r\n{cut}");
2276        for (failed, cleanup) in [(after_rclf, "3. DROPN STOF"), (before_rclf, "DROP2")] {
2277            let (mut c, log) = calc(move |cmd| match cmd {
2278                "VERSION" => cut.into(),
2279                VERSION_CHUNKS => failed.clone(),
2280                _ => EMPTY.into(),
2281            });
2282            let err = c.version().unwrap_err();
2283            assert!(
2284                matches!(&err, Error::Calculator { message, .. } if message == "Insufficient Memory"),
2285                "{err:?}"
2286            );
2287            assert_eq!(sent(&log), ["VERSION", VERSION_CHUNKS, cleanup]);
2288        }
2289    }
2290
2291    /// ROM 1.18 on a real 49G cuts IOPAR's list (`{ 9600. 0. 0. 0. 3. `);
2292    /// satx never reads the list, only its items.
2293    #[test]
2294    fn iopar_item_by_item() {
2295        let items_49g = format!(
2296            "8: {G49_FLAGS}\r\n7: 9600.\r\n6: 0.\r\n5: 0.\r\n4: 0.\r\n3: 3.\r\n2: 1.\r\n1: 6.\r\n"
2297        );
2298        let items_48 = format!(
2299            "9: 4711\r\n8: {SX_FLAGS}\r\n7: 9600\r\n6: 0\r\n5: 0\r\n4: 0\r\n3: 3\r\n2: 1\r\n\
2300             1: 6\r\n"
2301        );
2302        // With the fraction mark `,` (flag -51), which STD keeps.
2303        let items_comma = format!(
2304            "8: {G49_FLAGS}\r\n7: 2400,\r\n6: -2,\r\n5: 1,\r\n4: 0,\r\n3: 1,\r\n2: 3,\r\n1: 6,\r\n"
2305        );
2306        let other = Iopar {
2307            baud: 2400,
2308            parity: -2,
2309            receive_pacing: true,
2310            transmit_pacing: false,
2311            checksum: 1,
2312            translate: 3,
2313        };
2314        for (items, expected) in [
2315            (items_49g, Iopar::default()),
2316            (items_48, Iopar::default()),
2317            (items_comma, other),
2318        ] {
2319            let (mut c, log) = calc(move |cmd| match cmd {
2320                "IOPAR" => "1: { 9600. 0. 0. 0. 3. \r\n".into(),
2321                IOPAR_ITEMS => items.clone(),
2322                _ => EMPTY.into(),
2323            });
2324            assert_eq!(c.iopar().unwrap(), expected);
2325            assert_eq!(sent(&log), [IOPAR_ITEMS, IOPAR_DROP]);
2326        }
2327    }
2328
2329    /// IOPAR that is not a six-item list: LIST→ refuses anything but a list
2330    /// and leaves it, which is dropped, the flags put back; a list of
2331    /// another length is dropped with its items. An error with no saved
2332    /// flags where they belong leaves the stack alone.
2333    #[test]
2334    fn iopar_that_is_not_a_six_item_list() {
2335        let (mut c, log) = calc(|cmd| match cmd {
2336            IOPAR_ITEMS => format!("Error: Bad Argument Type\r\n2: {SX_FLAGS}\r\n1: 'IOPAR'\r\n"),
2337            _ => EMPTY.into(),
2338        });
2339        let err = c.iopar().unwrap_err();
2340        assert!(matches!(&err, Error::Calculator { .. }), "{err:?}");
2341        assert_eq!(sent(&log), [IOPAR_ITEMS, "DROP STOF"]);
2342
2343        let (mut c, log) = calc(|cmd| match cmd {
2344            IOPAR_ITEMS => "Error: Insufficient Memory\r\n1: 4711\r\n".into(),
2345            _ => EMPTY.into(),
2346        });
2347        assert!(c.iopar().is_err());
2348        assert_eq!(sent(&log), [IOPAR_ITEMS]);
2349
2350        let (mut c, log) = calc(|cmd| match cmd {
2351            IOPAR_ITEMS => format!("4: {SX_FLAGS}\r\n3: 9600\r\n2: 0\r\n1: 2\r\n"),
2352            _ => EMPTY.into(),
2353        });
2354        let err = c.iopar().unwrap_err();
2355        assert!(
2356            matches!(&err, Error::Reply(m) if m.contains("bad list")),
2357            "{err:?}"
2358        );
2359        assert_eq!(sent(&log), [IOPAR_ITEMS, IOPAR_DROP]);
2360    }
2361
2362    /// A real as `0 SCI` shows it: one digit (9600 is `1.E4`).
2363    fn sci_0(x: f64) -> String {
2364        if x == 0.0 {
2365            return "0.E0".into();
2366        }
2367        let mut exp = x.abs().log10().floor() as i32;
2368        let mut digit = (x / 10f64.powi(exp)).round();
2369        if digit.abs() >= 10.0 {
2370            digit /= 10.0;
2371            exp += 1;
2372        }
2373        format!("{digit}.E{exp}")
2374    }
2375
2376    /// A 49G in `0 SCI` (as on the emulated one, 2026-11-08): reals show
2377    /// with one digit (`1.E4`) until a command sets STD and again after
2378    /// STOF. IOPAR, MEM and VERSION read all the digits all the same, and
2379    /// the mode is back afterwards.
2380    #[test]
2381    fn queries_in_0_sci() {
2382        let std = Arc::new(Mutex::new(false));
2383        let mode = Arc::clone(&std);
2384        let (mut c, log) = calc(move |cmd| {
2385            let mut std = mode.lock().unwrap();
2386            if cmd.contains("STD") {
2387                *std = true;
2388            }
2389            let real = |x: f64| if *std { format!("{x}.") } else { sci_0(x) };
2390            let reply = match cmd {
2391                "VERSION" => G49_VERSION.into(),
2392                VERSION_CHUNKS => {
2393                    let joined = "Version HP48-C\nRevision #2.15Copyright HP 2009";
2394                    let mut levels = vec![G49_FLAGS.to_string()];
2395                    let chars: Vec<char> = joined.chars().collect();
2396                    for chunk in chars.chunks(CHUNK) {
2397                        let chunk: String = chunk.iter().collect();
2398                        levels.push(format!("\"{}\"", chunk.replace('\n', "\r\n")));
2399                    }
2400                    levels.push(real(chars.len() as f64));
2401                    let depth = levels.len();
2402                    levels
2403                        .iter()
2404                        .enumerate()
2405                        .map(|(i, l)| format!("{}: {l}\r\n", depth - i))
2406                        .collect()
2407                }
2408                IOPAR_ITEMS => {
2409                    let items = [9600.0, 0.0, 0.0, 0.0, 3.0, 1.0, 6.0];
2410                    let mut text = format!("8: {G49_FLAGS}\r\n");
2411                    for (i, x) in items.iter().enumerate() {
2412                        text.push_str(&format!("{}: {}\r\n", 7 - i, real(*x)));
2413                    }
2414                    text
2415                }
2416                MEM_STD => format!("2: {G49_FLAGS}\r\n1: {}\r\n", real(245_886.0)),
2417                "-35 FS?" => format!("1: {}\r\n", real(1.0)),
2418                _ => EMPTY.into(),
2419            };
2420            if cmd.ends_with("STOF") {
2421                *std = false;
2422            }
2423            reply
2424        });
2425        assert_eq!(c.iopar().unwrap(), Iopar::default());
2426        assert!(!*std.lock().unwrap(), "STD left on after IOPAR");
2427        assert_eq!(c.mem().unwrap(), 245_886.0);
2428        assert_eq!(
2429            c.version().unwrap().as_deref(),
2430            Some("Version HP48-C Revision #2.15, Copyright HP 2009")
2431        );
2432        assert!(!*std.lock().unwrap(), "STD left on after VERSION");
2433        // A flag is 0 or 1 in any mode: `1.E0`.
2434        assert_eq!(c.transfer_mode().unwrap(), TransferMode::Binary);
2435        assert_eq!(
2436            sent(&log),
2437            [
2438                IOPAR_ITEMS,
2439                IOPAR_DROP,
2440                MEM_STD,
2441                "DROP STOF",
2442                "VERSION",
2443                VERSION_CHUNKS,
2444                "6. DROPN STOF",
2445                "-35 FS?",
2446                "DROP",
2447            ]
2448        );
2449        assert_eq!(sci_0(9600.0), "1.E4");
2450        assert_eq!(sci_0(46.0), "5.E1");
2451    }
2452
2453    #[test]
2454    fn model_from_version() {
2455        use Model::*;
2456        assert_eq!(Model::from_version(None), Hp48Sx);
2457        assert_eq!(
2458            Model::from_version(Some("Version HP48-R, Copyright HP 1993")),
2459            Hp48Gx
2460        );
2461        assert_eq!(
2462            Model::from_version(Some("Version HP48-C Revision #2.15, Copyright HP 2009")),
2463            Hp49G
2464        );
2465        assert_eq!(
2466            Model::from_version(Some("Version HP49-C, Copyright HP 2000")),
2467            Hp49G
2468        );
2469        assert_eq!(Model::from_version(Some("something else")), Unknown);
2470        assert_eq!(Hp48Gx.name(), "HP 48G/GX");
2471        assert!(!Hp48Sx.has_xmodem() && Hp48Gx.has_xmodem() && Hp49G.has_xmodem());
2472    }
2473
2474    const G49_VERSION: &str = "2: \"Version HP48-C\r\nRevisi\r\n1:  \"Copyright HP 2009\"\r\n";
2475    const GX_VERSION: &str = "2:     \"Version HP48-R\"\r\n1:  \"Copyright HP 1993\"\r\n";
2476
2477    #[test]
2478    fn prepare_xrecv_on_49g_in_alg_mode() {
2479        let (mut c, log) = calc(|cmd| match cmd {
2480            "VERSION" => G49_VERSION.into(),
2481            VERSION_CHUNKS => {
2482                chunk_reply("Version HP48-C\nRevision #2.15", "Copyright HP 2009", &[])
2483            }
2484            "G D" => "{ HOME } 2000.\r\nSATXX 10.5 String 1234.\r\n".into(),
2485            "-95. FS?" => "1:                     1.\r\n".into(),
2486            _ => EMPTY.into(),
2487        });
2488        let plan = c
2489            .prepare_for_xmodem(XmodemDirection::ToCalculator, "SATXX")
2490            .unwrap();
2491        assert_eq!(
2492            sent(&log),
2493            [
2494                "VERSION",
2495                VERSION_CHUNKS,
2496                "6. DROPN STOF",
2497                "G D",
2498                "-95. FS?",
2499                "DROP",
2500                "-95. CF",
2501                "\u{ab} 'SATXX' XRECV \u{bb}",
2502                "G F"
2503            ]
2504        );
2505        assert_eq!(plan.model, Model::Hp49G);
2506        assert_eq!(plan.program, "\u{ab} 'SATXX' XRECV \u{bb}");
2507        assert_eq!(plan.keys, ["right-shift", "SYMB"]);
2508        assert!(plan.exists && plan.switched_to_rpn);
2509        let text = plan.instructions();
2510        assert!(
2511            text.starts_with(
2512                "\u{ab} 'SATXX' XRECV \u{bb} is on the calculator's stack. On the calculator, \
2513                 press right-shift, then SYMB (EVAL) to run it."
2514            ),
2515            "{text}"
2516        );
2517        assert!(text.contains("SATXX.1"), "{text}");
2518        assert!(text.contains("-95 SF"), "{text}");
2519        assert!(text.contains("drops the program"), "{text}");
2520        assert!(
2521            text.ends_with("type SERVER and press ENTER after the transfer."),
2522            "{text}"
2523        );
2524    }
2525
2526    /// Review of PR #261: the program could not be put on the stack, so
2527    /// the 49G goes back to algebraic mode and the error is the push's.
2528    #[test]
2529    fn prepare_xrecv_failed_push_restores_alg_mode() {
2530        let (mut c, log) = calc(|cmd| match cmd {
2531            "VERSION" => G49_VERSION.into(),
2532            VERSION_CHUNKS => {
2533                chunk_reply("Version HP48-C\nRevision #2.15", "Copyright HP 2009", &[])
2534            }
2535            "G D" => "{ HOME } 2000.\r\n".into(),
2536            "-95. FS?" => "1:                     1.\r\n".into(),
2537            "\u{ab} 'SATXX' XRECV \u{bb}" => "Error: Insufficient Memory\r\n".into(),
2538            _ => EMPTY.into(),
2539        });
2540        let err = c
2541            .prepare_for_xmodem(XmodemDirection::ToCalculator, "SATXX")
2542            .unwrap_err();
2543        assert!(matches!(err, Error::Calculator { .. }), "{err:?}");
2544        let sent = sent(&log);
2545        assert_eq!(
2546            &sent[sent.len() - 3..],
2547            ["-95. CF", "\u{ab} 'SATXX' XRECV \u{bb}", "-95. SF"]
2548        );
2549    }
2550
2551    #[test]
2552    fn prepare_xsend_on_48gx() {
2553        let (mut c, log) = calc(|cmd| match cmd {
2554            "VERSION" => GX_VERSION.into(),
2555            "G D" => "{ HOME } 2000\r\nSATXX 10.5 String 1234\r\n".into(),
2556            _ => EMPTY.into(),
2557        });
2558        let plan = c
2559            .prepare_for_xmodem(XmodemDirection::FromCalculator, "SATXX")
2560            .unwrap();
2561        assert_eq!(
2562            sent(&log),
2563            [
2564                "VERSION",
2565                "DROP2",
2566                "G D",
2567                "\u{ab} 'SATXX' XSEND \u{bb}",
2568                "G F"
2569            ]
2570        );
2571        assert_eq!(plan.keys, ["EVAL"]);
2572        assert!(!plan.switched_to_rpn);
2573        assert_eq!(plan.notes.len(), 2);
2574        let text = plan.instructions();
2575        assert!(text.contains("press EVAL to run it."), "{text}");
2576        assert!(text.ends_with("press right-shift, then \u{2192} (or type SERVER and press ENTER) after the transfer."), "{text}");
2577    }
2578
2579    #[test]
2580    fn prepare_refuses_existing_name_on_48gx() {
2581        let (mut c, log) = calc(|cmd| match cmd {
2582            "VERSION" => GX_VERSION.into(),
2583            "G D" => "{ HOME } 2000\r\nSATXX 10.5 String 1234\r\n".into(),
2584            _ => EMPTY.into(),
2585        });
2586        let err = c
2587            .prepare_for_xmodem(XmodemDirection::ToCalculator, "SATXX")
2588            .unwrap_err();
2589        assert!(matches!(&err, Error::Reply(m) if m == "SATXX: already exists"));
2590        assert_eq!(sent(&log), ["VERSION", "DROP2", "G D"]);
2591    }
2592
2593    #[test]
2594    fn prepare_refuses_before_finishing() {
2595        // XSEND of a missing variable, and any XModem on a 48SX, fail
2596        // without ending server mode.
2597        let (mut c, log) = calc(|cmd| match cmd {
2598            "VERSION" => GX_VERSION.into(),
2599            "G D" => "{ HOME } 2000\r\n".into(),
2600            _ => EMPTY.into(),
2601        });
2602        let err = c
2603            .prepare_for_xmodem(XmodemDirection::FromCalculator, "NOSUCH")
2604            .unwrap_err();
2605        assert!(matches!(&err, Error::Reply(m) if m == "NOSUCH: no such variable"));
2606        assert!(!sent(&log).contains(&"G F".to_string()));
2607        assert!(matches!(
2608            c.prepare_for_xmodem(XmodemDirection::ToCalculator, "A B"),
2609            Err(Error::Name(_))
2610        ));
2611
2612        let (mut c, log) = calc(|cmd| match cmd {
2613            "VERSION" => "1:  'VERSION'\r\n".into(),
2614            _ => EMPTY.into(),
2615        });
2616        let err = c
2617            .prepare_for_xmodem(XmodemDirection::ToCalculator, "X")
2618            .unwrap_err();
2619        assert!(matches!(err, Error::Unsupported(_)), "{err:?}");
2620        assert_eq!(sent(&log), ["VERSION", "DROP"]);
2621    }
2622
2623    #[test]
2624    fn cd_checks_each_component() {
2625        let (mut c, log) = calc(|cmd| match cmd {
2626            "G D" => "D1 5.5 Directory 4321\r\nX 10.5 Real Number 1234\r\n".into(),
2627            _ => EMPTY.into(),
2628        });
2629        c.cd(&["HOME", "D1"]).unwrap();
2630        assert_eq!(sent(&log), ["HOME", "G D", "D1"]);
2631
2632        log.lock().unwrap().clear();
2633        let err = c.cd(&["NOSUCH"]).unwrap_err();
2634        assert!(matches!(&err, Error::Reply(m) if m.contains("no such directory")));
2635        assert_eq!(sent(&log), ["HOME", "G D"]);
2636
2637        log.lock().unwrap().clear();
2638        let err = c.cd(&["HOME", "X"]).unwrap_err();
2639        assert!(matches!(&err, Error::Reply(m) if m.contains("no such directory")));
2640        assert_eq!(sent(&log), ["HOME", "G D"]);
2641
2642        log.lock().unwrap().clear();
2643        assert!(matches!(c.cd(&["A B"]), Err(Error::Name(_))));
2644        assert!(sent(&log).is_empty());
2645    }
2646
2647    #[test]
2648    fn rename_joined_split_and_directory() {
2649        let (mut c, log) = calc(|cmd| match cmd {
2650            "G D" => format!(
2651                "X 10.5 Real Number 1234\r\nSUB 5.5 Directory 4321\r\n{} 10.5 Real Number 1\r\n",
2652                "L".repeat(40)
2653            ),
2654            _ => EMPTY.into(),
2655        });
2656        c.rename("X", "Y").unwrap();
2657        assert_eq!(sent(&log), ["G D", "'X' RCL 'Y' STO 'X' PURGE"]);
2658
2659        log.lock().unwrap().clear();
2660        let long = "L".repeat(40);
2661        let to = "M".repeat(40);
2662        c.rename(&long, &to).unwrap();
2663        assert_eq!(
2664            sent(&log),
2665            [
2666                "G D".to_string(),
2667                format!("'{long}' RCL"),
2668                format!("'{to}' STO"),
2669                format!("'{long}' PURGE"),
2670            ]
2671        );
2672
2673        log.lock().unwrap().clear();
2674        c.rename("SUB", "SUB2").unwrap();
2675        assert_eq!(sent(&log), ["G D", "'SUB' RCL 'SUB2' STO 'SUB' PGDIR"]);
2676
2677        log.lock().unwrap().clear();
2678        assert!(matches!(c.rename("NOSUCH", "Z"), Err(Error::Reply(_))));
2679        assert!(matches!(c.rename("X", "SUB"), Err(Error::Reply(_))));
2680        assert_eq!(sent(&log), ["G D", "G D"]);
2681    }
2682
2683    #[test]
2684    fn remove_checks_listing() {
2685        let (mut c, log) = calc(|cmd| match cmd {
2686            "G D" => SX_DIR.into(),
2687            _ => EMPTY.into(),
2688        });
2689        let err = c.remove("NOSUCH").unwrap_err();
2690        assert!(matches!(&err, Error::Reply(m) if m.contains("no such variable")));
2691        assert_eq!(sent(&log), ["G D"]);
2692        c.remove("SUB").unwrap();
2693        c.remove("X").unwrap();
2694        assert_eq!(
2695            sent(&log),
2696            ["G D", "G D", "'SUB' PGDIR", "G D", "'X' PURGE"]
2697        );
2698    }
2699
2700    #[test]
2701    fn calculator_error() {
2702        let (mut c, _) = calc(|_| "Error: Undefined Name\r\n1:          'NOSUCH'\r\n".into());
2703        let reply = c.run("'NOSUCH' RCL").unwrap();
2704        assert_eq!(reply.error.as_deref(), Some("Undefined Name"));
2705        let err = c.mkdir("NOSUCH").unwrap_err();
2706        assert!(
2707            matches!(&err, Error::Calculator { message, stack }
2708                if message == "Undefined Name" && stack == &["'NOSUCH'"]),
2709            "{err:?}"
2710        );
2711    }
2712
2713    #[test]
2714    fn transfer_mode_is_cached() {
2715        let (mut c, log) = calc(|_| EMPTY.into());
2716        c.set_transfer_mode(TransferMode::Binary).unwrap();
2717        c.set_transfer_mode(TransferMode::Binary).unwrap();
2718        assert_eq!(sent(&log), ["-35 SF"]);
2719        c.set_transfer_mode(TransferMode::Ascii).unwrap();
2720        assert_eq!(sent(&log), ["-35 SF", "-35 CF"]);
2721        // An arbitrary command may change the flag.
2722        c.run("1").unwrap();
2723        c.set_transfer_mode(TransferMode::Ascii).unwrap();
2724        assert_eq!(sent(&log), ["-35 SF", "-35 CF", "1", "-35 CF"]);
2725    }
2726
2727    #[test]
2728    fn transfer_mode_query() {
2729        let (mut c, log) = calc(|cmd| match cmd {
2730            "-35 FS?" => "1: 1.\r\n".into(),
2731            _ => EMPTY.into(),
2732        });
2733        assert_eq!(c.transfer_mode().unwrap(), TransferMode::Binary);
2734        c.set_transfer_mode(TransferMode::Binary).unwrap();
2735        assert_eq!(sent(&log), ["-35 FS?", "DROP"]);
2736    }
2737
2738    #[test]
2739    fn set_iopar_stores_reals() {
2740        // Recorded on the emulated 49G: `{ 9600 0 0 0 3 3 }` stored as exact
2741        // integers, the server answered nothing and stopped with "Invalid
2742        // IOPAR". The list must hold reals, in one command.
2743        let (mut c, log) = calc(|_| EMPTY.into());
2744        let iopar = Iopar {
2745            translate: 3,
2746            ..Iopar::default()
2747        };
2748        c.set_iopar(&iopar).unwrap();
2749        assert_eq!(
2750            sent(&log),
2751            ["PATH HOME { 9600. 0. 0. 0. 3. 3. } 'IOPAR' STO EVAL"]
2752        );
2753        // The widest list still fits one `C` packet, so it is never split.
2754        log.lock().unwrap().clear();
2755        let wide = Iopar {
2756            baud: 115_200,
2757            parity: -4,
2758            receive_pacing: true,
2759            transmit_pacing: true,
2760            checksum: 3,
2761            translate: 255,
2762        };
2763        c.set_iopar(&wide).unwrap();
2764        assert_eq!(
2765            sent(&log),
2766            ["PATH HOME { 115200. -4. 1. 1. 3. 255. } 'IOPAR' STO EVAL"]
2767        );
2768    }
2769
2770    #[test]
2771    fn command_too_long() {
2772        let (mut c, log) = calc(|_| EMPTY.into());
2773        let err = c.run(&"1".repeat(200)).unwrap_err();
2774        assert!(
2775            matches!(err, Error::CommandTooLong { len: 200, .. }),
2776            "{err:?}"
2777        );
2778        assert!(sent(&log).is_empty());
2779        c.run("1").unwrap();
2780    }
2781
2782    #[test]
2783    fn names() {
2784        for ok in [
2785            "A",
2786            "SATXE2E",
2787            "IOPAR",
2788            "x\u{0304}",
2789            "Σ1",
2790            "a.b",
2791            "CONS",
2792            "COM0",
2793            "COM10",
2794            "LPT",
2795            "XNUL",
2796            &"N".repeat(127),
2797        ] {
2798            assert!(validate_name(ok).is_ok(), "{ok:?}");
2799        }
2800        for bad in [
2801            "",
2802            "1A",
2803            ".A",
2804            "A B",
2805            "A\tB",
2806            "A'",
2807            "A\"",
2808            "«A",
2809            "{A}",
2810            "A[1]",
2811            "F(X)",
2812            "#A",
2813            ":0:A",
2814            "A,B",
2815            "A;B",
2816            "A+B",
2817            "A-B",
2818            "A*B",
2819            "A/B",
2820            "A^B",
2821            "A=B",
2822            "A<B",
2823            "A>B",
2824            "A\u{1}",
2825            "A\u{263A}",
2826            // security.md "Windows file names": backslash and device names.
2827            "A\\B",
2828            "CON",
2829            "nul",
2830            "Aux",
2831            "PRN",
2832            "COM1",
2833            "lpt9",
2834            "NUL.X",
2835            "con.txt",
2836            &"N".repeat(128),
2837        ] {
2838            assert!(matches!(validate_name(bad), Err(Error::Name(_))), "{bad:?}");
2839        }
2840    }
2841}