saturnus-objects 0.10.1

HP 48/49 RPL objects for saturnus hosts: the exact object decoder and a read-only view of a paused machine's user memory (directories, stack, flags)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! The command line being edited and the state of the ROM's editor (entry
//! mode, alpha, shifts), read from RAM without pressing a key.
//!
//! The ROM keeps the text reversed and NUL-terminated just below its
//! temporary environments, with no length field; the cursor and the
//! editor's flags sit in system RAM. Locations per model were found by
//! observation (wiki: hardware/command-line; the 28S: wiki:
//! hardware/hp28s "Command line").

use crate::error::Error;
use saturnus_core::{Machine, Model};
use serde::Serialize;

use crate::charset;
use crate::object::Memory;

type Result<T, E = Error> = std::result::Result<T, E>;

/// Most characters read (the 49G's RAM could hold more, but no line the
/// ROM edits is that long; more means the pointers are not the ROM's).
pub const MAX_CHARS: usize = 65_536;

/// Where a model's ROM keeps its editor in RAM (wiki:
/// hardware/command-line). `*_ptr` fields hold 5-nibble pointers; the
/// others are nibbles whose bits are listed with them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EditorLayout {
    /// Pointer just past the text's first character (the temporary
    /// environments, `local_vars` in the 1991 address list).
    pub text_end_ptr: u32,
    /// Pointer past the data stack, the lowest the text may reach.
    pub stack_end_ptr: u32,
    /// The cursor, 5 nibbles, in characters from the start.
    pub cursor: u32,
    /// Bit 1 insert mode, bit 2 algebraic entry.
    pub entry: u32,
    /// Bit 1 a command line is open, bit 2 lowercase lock.
    pub line: u32,
    /// Bit 0 left shift, bit 1 right shift, bit 2 alpha.
    pub keys: u32,
    /// Bit 0 alpha lock.
    pub alpha_lock: u32,
    /// Bit 0 program entry.
    pub program: u32,
    /// The message nibble: on the 48 bit 0 is set while the header shows a
    /// message (an error); on the 49G it, or the nibble after it, reads
    /// #F while an error box has the keyboard.
    pub message: u32,
    /// Errors show in a box (49G), not in the header (48).
    pub message_box: bool,
    /// The byte the 49G's CHARS application opens on (it remembers the
    /// last one); `None` where CHARS always opens on 128 (48GX) or does
    /// not exist (48SX).
    pub chars_position: Option<u32>,
}

impl EditorLayout {
    /// 48SX (ROM J).
    pub const HP48SX: EditorLayout = EditorLayout {
        text_end_ptr: 0x70583,
        stack_end_ptr: 0x7057E,
        cursor: 0x70704,
        entry: 0x70685,
        line: 0x70687,
        keys: 0x706C4,
        alpha_lock: 0x70793,
        program: 0x70794,
        message: 0x7068B,
        message_box: false,
        chars_position: None,
    };
    /// 48GX (ROM R).
    pub const HP48GX: EditorLayout = EditorLayout {
        text_end_ptr: 0x80702,
        stack_end_ptr: 0x806FD,
        cursor: 0x80882,
        entry: 0x80803,
        line: 0x80805,
        keys: 0x80842,
        alpha_lock: 0x80911,
        program: 0x80912,
        message: 0x80809,
        message_box: false,
        chars_position: None,
    };
    /// 49G (ROM 2.10).
    pub const HP49G: EditorLayout = EditorLayout {
        text_end_ptr: 0x80702,
        stack_end_ptr: 0x806FD,
        cursor: 0x80F61,
        entry: 0x80EC2,
        line: 0x80EC4,
        keys: 0x80F01,
        alpha_lock: 0x80FF0,
        program: 0x80FF1,
        message: 0x80EC8,
        message_box: true,
        chars_position: Some(0x818CF),
    };

    /// The layout of `model`, or `None` for the aplet models, the Pioneers (42S, 27S,
    /// 17BII, 17B), the 28S (read by [`read_hp28`]) and the 19BII.
    pub fn of(model: Model) -> Option<EditorLayout> {
        match model {
            Model::Hp48sx => Some(Self::HP48SX),
            Model::Hp48gx => Some(Self::HP48GX),
            Model::Hp49g => Some(Self::HP49G),
            Model::Hp38g
            | Model::Hp39g
            | Model::Hp40g
            | Model::Hp42s
            | Model::Hp27s
            | Model::Hp17bii
            | Model::Hp17b
            | Model::Hp28s
            | Model::Hp19bii => None,
        }
    }

    /// The layout of `model` or [`Error::NoCommandLine`], which names what
    /// the model lacks.
    pub fn require(model: Model) -> Result<EditorLayout> {
        Self::of(model).ok_or(Error::NoCommandLine(model))
    }
}

/// Where the 28S's ROM (2BB, its only revision) keeps its command line
/// (wiki: hardware/hp28s "Command line"). The text is kept as on the
/// 48, reversed below a pointer, and zeroed when the line closes; the
/// line closes when it empties, so an open line always has text.
#[derive(Clone, Copy, Debug)]
pub struct Hp28;

impl Hp28 {
    /// Pointer just past the text's first character.
    pub const TEXT_END_PTR: u32 = 0xC006E;
    /// Pointer never above the byte under the text.
    pub const FLOOR_PTR: u32 = 0xC0069;
    /// The cursor, 5 nibbles, in characters from the start.
    pub const CURSOR: u32 = 0xC0126;
    /// Bit 0: a command line is open.
    pub const OPEN: u32 = 0xC015D;
    /// Bit 1 insert mode (the ROM starts in replace mode), bit 2
    /// algebraic entry.
    pub const ENTRY: u32 = 0xC00EE;
    /// Bit 0: alpha entry mode (α, `«`, EDIT).
    pub const ALPHA_ENTRY: u32 = 0xC00ED;
    /// Bit 2: lowercase.
    pub const LOWERCASE: u32 = 0xC00F0;
}

/// The editor as the ROM left it.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Editor {
    /// A command line is open (also an empty one, and in `EDIT`).
    pub active: bool,
    /// The text as HP bytes, empty when no line is open.
    pub text: Vec<u8>,
    /// The cursor in characters, 0 before the first.
    pub cursor: usize,
    /// Insert mode (off: typing replaces the character at the cursor).
    pub insert: bool,
    /// Algebraic entry mode (after `'`).
    pub algebraic: bool,
    /// Program entry mode (after `«`, or ENTRY); on the 28S its alpha
    /// entry mode (α, `«`, EDIT).
    pub program: bool,
    /// Lowercase lock.
    pub lowercase: bool,
    /// Alpha is on (for one key, or locked).
    pub alpha: bool,
    /// Alpha is locked.
    pub alpha_lock: bool,
    /// The left shift is pending.
    pub left_shift: bool,
    /// The right shift is pending.
    pub right_shift: bool,
    /// The ROM shows an error: in the header (48) or in a box (49G).
    pub message: bool,
}

/// The `commandLine` protocol answer.
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct CommandLine {
    /// A command line is open.
    pub active: bool,
    /// Its text (empty when none is open).
    pub text: String,
    /// The cursor in calculator characters (0 before the first).
    pub cursor: usize,
}

fn nibble(mem: &dyn Memory, addr: u32) -> Result<u8> {
    mem.nibble(addr).ok_or(Error::Unreadable(addr))
}

fn field(mem: &dyn Memory, addr: u32, len: u32) -> Result<u32> {
    let mut v = 0;
    for i in (0..len).rev() {
        v = (v << 4) | u32::from(nibble(mem, addr + i)?);
    }
    Ok(v)
}

fn bit(mem: &dyn Memory, addr: u32, b: u8) -> Result<bool> {
    Ok(nibble(mem, addr)? & (1 << b) != 0)
}

/// The text kept reversed and NUL-terminated below the pointer at
/// `end_ptr`, reaching down to the pointer at `floor_ptr` at most.
fn reversed_text(mem: &dyn Memory, end_ptr: u32, floor_ptr: u32) -> Result<Vec<u8>> {
    let end = field(mem, end_ptr, 5)?;
    let floor = field(mem, floor_ptr, 5)?;
    if floor >= end {
        return Err(Error::Memory(format!(
            "the command line pointers (#{floor:05X}, #{end:05X}) are not the ROM's"
        )));
    }
    let mut text = Vec::new();
    let mut a = end;
    while a >= floor + 2 {
        a -= 2;
        let b = field(mem, a, 2)? as u8;
        if b == 0 {
            break;
        }
        if text.len() >= MAX_CHARS {
            return Err(Error::Memory(format!(
                "the command line is longer than {MAX_CHARS} characters"
            )));
        }
        text.push(b);
    }
    Ok(text)
}

/// Read the editor through `layout`.
pub fn read(mem: &dyn Memory, layout: &EditorLayout) -> Result<Editor> {
    let active = bit(mem, layout.line, 1)?;
    let text = if active {
        reversed_text(mem, layout.text_end_ptr, layout.stack_end_ptr)?
    } else {
        Vec::new()
    };
    let cursor = field(mem, layout.cursor, 5)? as usize;
    let keys = nibble(mem, layout.keys)?;
    let message = if layout.message_box {
        !active && (nibble(mem, layout.message)? == 0xF || nibble(mem, layout.message + 1)? == 0xF)
    } else {
        bit(mem, layout.message, 0)?
    };
    Ok(Editor {
        message,
        active,
        cursor: if active { cursor.min(text.len()) } else { 0 },
        text,
        insert: bit(mem, layout.entry, 1)?,
        algebraic: bit(mem, layout.entry, 2)?,
        program: bit(mem, layout.program, 0)?,
        lowercase: bit(mem, layout.line, 2)?,
        alpha: keys & 4 != 0,
        alpha_lock: bit(mem, layout.alpha_lock, 0)?,
        left_shift: keys & 1 != 0,
        right_shift: keys & 2 != 0,
    })
}

/// Read the 28S's editor ([`Hp28`]). Its shift and α show on the
/// annunciators, so `left_shift` and `alpha` stay false here, as do the
/// fields it has no counterpart for.
pub fn read_hp28(mem: &dyn Memory) -> Result<Editor> {
    let active = bit(mem, Hp28::OPEN, 0)?;
    let text = if active {
        reversed_text(mem, Hp28::TEXT_END_PTR, Hp28::FLOOR_PTR)?
    } else {
        Vec::new()
    };
    let cursor = field(mem, Hp28::CURSOR, 5)? as usize;
    Ok(Editor {
        active,
        cursor: if active { cursor.min(text.len()) } else { 0 },
        text,
        insert: bit(mem, Hp28::ENTRY, 1)?,
        algebraic: bit(mem, Hp28::ENTRY, 2)?,
        program: bit(mem, Hp28::ALPHA_ENTRY, 0)?,
        lowercase: bit(mem, Hp28::LOWERCASE, 2)?,
        ..Editor::default()
    })
}

/// The editor of `machine` (48SX, 48GX, 49G, 28S).
pub fn editor(machine: &Machine) -> Result<Editor> {
    if machine.model() == Model::Hp28s {
        return read_hp28(machine);
    }
    read(machine, &EditorLayout::require(machine.model())?)
}

/// The command line of `machine`: open or not, its text and cursor.
pub fn command_line(machine: &Machine) -> Result<CommandLine> {
    let e = editor(machine)?;
    let text = if machine.model() == Model::Hp28s {
        charset::decode_hp28(&e.text)
    } else {
        charset::decode(&e.text)
    };
    Ok(CommandLine {
        active: e.active,
        text,
        cursor: e.cursor,
    })
}

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

    #[derive(Default)]
    struct Ram(HashMap<u32, u8>);

    impl Memory for Ram {
        fn nibble(&self, addr: u32) -> Option<u8> {
            Some(self.0.get(&addr).copied().unwrap_or(0))
        }
    }

    impl Ram {
        fn put(&mut self, addr: u32, value: u32, len: u32) {
            for i in 0..len {
                self.0.insert(addr + i, ((value >> (4 * i)) & 15) as u8);
            }
        }
    }

    #[test]
    fn reads_the_reversed_text_and_the_flags() {
        let l = EditorLayout::HP48SX;
        let mut ram = Ram::default();
        // "ABCDEF" as the 48SX keeps it (observed: 645444342414 at #7FED7).
        ram.put(l.text_end_ptr, 0x7FEE3, 5);
        ram.put(l.stack_end_ptr, 0x7FEB3, 5);
        for (i, b) in b"FEDCBA".iter().enumerate() {
            ram.put(0x7FED7 + 2 * i as u32, u32::from(*b), 2);
        }
        ram.put(l.cursor, 4, 5);
        ram.put(l.line, 3, 1);
        ram.put(l.entry, 3, 1);
        ram.put(l.keys, 4, 1);
        let e = read(&ram, &l).unwrap();
        assert!(e.active && e.insert && !e.algebraic && e.alpha && !e.alpha_lock);
        assert_eq!(e.text, b"ABCDEF");
        assert_eq!(e.cursor, 4);
        // Closed: the stale text is not reported.
        ram.put(l.line, 1, 1);
        let e = read(&ram, &l).unwrap();
        assert!(!e.active && e.text.is_empty() && e.cursor == 0);
    }

    #[test]
    fn the_text_stops_at_the_stack() {
        let l = EditorLayout::HP48GX;
        let mut ram = Ram::default();
        ram.put(l.text_end_ptr, 0x90010, 5);
        ram.put(l.stack_end_ptr, 0x9000C, 5);
        ram.put(0x9000C, 0x4242, 4);
        ram.put(0x9000E, 0x41, 2);
        ram.put(l.line, 2, 1);
        assert_eq!(read(&ram, &l).unwrap().text, b"AB");
        ram.put(l.stack_end_ptr, 0x90020, 5);
        assert!(read(&ram, &l).is_err());
    }

    #[test]
    fn reads_the_28s_line() {
        let mut ram = Ram::default();
        // "AXC" as the 28S keeps it below #CFF70 (observed: 342414 for
        // "ABC" at #CFF6A), the floor lower, cursor 2, insert mode, open.
        ram.put(Hp28::TEXT_END_PTR, 0xCFF70, 5);
        ram.put(Hp28::FLOOR_PTR, 0xCFF40, 5);
        for (i, b) in b"CXA".iter().enumerate() {
            ram.put(0xCFF6A + 2 * i as u32, u32::from(*b), 2);
        }
        ram.put(Hp28::CURSOR, 2, 5);
        ram.put(Hp28::ENTRY, 2, 1);
        ram.put(Hp28::OPEN, 1, 1);
        let e = read_hp28(&ram).unwrap();
        assert!(e.active && e.insert && !e.algebraic && !e.program);
        assert_eq!(e.text, b"AXC");
        assert_eq!(e.cursor, 2);
        // Closed: nothing reported.
        ram.put(Hp28::OPEN, 0, 1);
        let e = read_hp28(&ram).unwrap();
        assert!(!e.active && e.text.is_empty() && e.cursor == 0);
    }

    #[test]
    fn aplet_models_have_none() {
        assert!(EditorLayout::of(Model::Hp38g).is_none());
        let err = EditorLayout::require(Model::Hp42s).unwrap_err();
        assert!(err.to_string().contains("42S has no RPL command line"));
    }
}