Make a device in Rust
This driver is the terminal, device 2, in one file of Rust with no dependencies: examples/device/rust/src/main.rs, 347 lines, a crate and workspace of its own. It does what programs/hello needs, exactly as the reference does, and no more.
The call table
A driver tells the core, for each of its device's calls, where the call's buffer is and what the call costs: 64 bytes per function, in DEVICES.md section 5's layout. Entry has a field for each part of it, and PLAIN is a call with no buffer whose result is a constant 0. The table is the five calls hello makes:
const TABLE: [Entry; 5] = [
Entry {
function: 0,
flags: DEFERRED | BUFFERED,
length: 1,
scale: 1,
most: 4096,
access: READS | IN_ROM,
rule: 2,
rule_arg: 1,
per_byte: 2,
..PLAIN
},
Entry {
function: 1,
charge_arg: 0,
low: 1,
high: 3,
add: 150,
..PLAIN
},
Entry { function: 2, ..PLAIN },
Entry { function: 4, ..PLAIN },
Entry {
function: 7,
flags: DEFERRED | BUFFERED,
buffer: 1,
length: 2,
scale: 4,
most: 9600,
access: READS | IN_ROM,
checked: 0,
checked_most: 2399,
rule: 2,
rule_arg: 2,
per_four: 1,
..PLAIN
},
];
write (0) has a buffer at a0 of a1 bytes, at most 4,096, read, which may be in ROM; it returns a1 and costs 2 units a byte. command (1) costs 150 units for commands 1 to 3. set_cursor (2) and set_colours (4) cost nothing. cells_write (7) has a buffer at a1 of a2 cells of 4 bytes, a0, the first cell, at most 2,399; it returns a2 and costs a unit per 4 bytes. All five are deferred: their result and charge follow from their arguments, so the core can work them out itself and send the calls later, in a batch.
The terminal
struct Terminal {
grid: Vec<u8>,
col: usize,
row: usize,
fg: u8,
bg: u8,
shown: u8,
wrap: bool,
palette: Vec<u8>,
}
At reset (Terminal::new) every cell is a space in colour 7 on 0, and the palette is xterm's 256 colours.
fn write(&mut self, text: &[u8]) {
for c in String::from_utf8_lossy(text).chars() {
if c == '\n' {
self.newline();
}
if c < ' ' || c == '\x7f' {
continue;
}
if self.wrap {
self.newline();
}
let code = match u16::try_from(c) {
Ok(0xffff) | Err(_) => 0xfffd,
Ok(code) => code,
};
self.put(self.row * COLUMNS + self.col, code);
if self.col == COLUMNS - 1 {
self.wrap = true;
} else {
self.col += 1;
}
}
}
write decodes its bytes as UTF-8 with the standard library (from_utf8_lossy), prints each character at the cursor and moves on, wrapping at the end of a row and scrolling at the bottom (newline).
fn call(&mut self, body: &[u8]) -> (u32, u32) {
let a = |i: usize| word(body, 4 + 4 * i);
let data = &body[40..40 + word(body, 36) as usize];
match body[1] {
0 => {
self.write(data);
return (a(1), 2 * a(1));
}
1 if a(0) == 4 => {
let line = self.row * COLUMNS;
for col in self.col..COLUMNS {
self.put(line + col, ' ' as u16);
}
}
1 if (1..=3).contains(&a(0)) => return (0, 150),
2 => {
self.col = (a(0) as usize).min(COLUMNS - 1);
self.row = (a(1) as usize).min(ROWS - 1);
self.wrap = false;
}
4 => {
self.fg = u8::try_from(a(0)).unwrap_or(self.fg);
self.bg = u8::try_from(a(1)).unwrap_or(self.bg);
}
7 => {
let start = 4 * a(0) as usize;
let size = self.grid.len();
for (i, &byte) in data.iter().enumerate() {
self.grid[(start + i) % size] = byte;
}
return (a(2), (data.len() as u32).div_ceil(4));
}
_ => {}
}
(0, 0)
}
fn state(&self) -> Vec<u8> {
let mut state = self.grid.clone();
let (col, row) = (self.col as u8, self.row as u8);
state.extend([col, row, self.fg, self.bg, self.shown]);
state.push(self.wrap as u8);
state.extend(&self.palette);
state.extend([0; 4]);
state
}
call carries a call out and returns its result and the charge on top of the base one, which must be what the table's rules say. state is the device's part of the machine's state, the bytes the state hash covers: the cells, the cursor, the colours, cursor shown, a pending wrap, the palette, and 4 bytes for a UTF-8 character cut between two writes (none here).
The messages
fn hello(body: &[u8]) -> Vec<u8> {
let name = "terminal (Rust example)";
let mut reply = vec![0x81, 1, 0, 0, name.len() as u8, 0];
reply.extend(name.as_bytes());
reply.extend([0, 0, 0, 0, body[8]]);
for &slot in &body[9..9 + body[8] as usize] {
if slot != 2 {
reply.extend([slot, 0, 0, 0]);
continue;
}
reply.extend([2, 0, 0, TABLE.len() as u8]);
for entry in &TABLE {
reply.extend(entry.encode());
}
}
reply.extend([0, 0, 0]);
reply
}
fn main() {
let path = env::var("TERSE_BUS_SOCKET").unwrap();
let mut stream = UnixStream::connect(path).unwrap();
let mut machines = HashMap::new();
loop {
let mut length = [0; 4];
if stream.read_exact(&mut length).is_err() {
return;
}
let mut message = vec![0; word(&length, 0) as usize];
if stream.read_exact(&mut message).is_err() {
return;
}
let (address, body) = message.split_at(8);
let instance = word(address, 0);
let reply = match body[0] {
0x01 => hello(body),
0x03 => {
machines.insert(instance, Terminal::new());
vec![0x83, 1, 0, 0, 0, 0]
}
0x04 => {
machines.remove(&instance);
continue;
}
0x10 => {
let t = machines.get_mut(&instance).unwrap();
let (result, charge) = t.call(body);
let mut reply = vec![0x90, 0, 0, 0];
words(&mut reply, &[result, 0, charge, 0]);
reply
}
0x11 => {
let mut at = 8;
for _ in 0..word(body, 4) {
let size = word(body, at) as usize;
let call = &body[at + 4..at + 4 + size];
let t = machines.get_mut(&word(call, 0));
t.unwrap().call(&call[8..]);
at += 4 + size;
}
continue;
}
0x30 => {
let mut inputs = vec![0; 20];
inputs[0] = 0xb0;
inputs
}
0x31 => continue,
0x40 => {
let state = machines[&instance].state();
let mut reply = vec![0xc0, 0, 0, 0];
words(&mut reply, &[state.len() as u32]);
reply.extend(state);
reply
}
0x60 => return,
_ => b"\x7fnot handled".to_vec(),
};
let mut out = Vec::new();
words(&mut out, &[8 + reply.len() as u32]);
out.extend(address);
out.extend(&reply);
if stream.write_all(&out).is_err() || reply[0] == 0x7f {
return;
}
}
}
The core starts the driver with the socket's path in TERSE_BUS_SOCKET. Each message is a length, an address (which machine, which slot) and a body whose first byte is its type; a reply carries the address of its request. HELLO: answer for the slots asked, 2 with its table and 10 (full text) with none. OPEN: a new machine, its terminal at reset; CLOSE drops it. CALL: carry it out and reply RESULT. BATCH: deferred calls, carried out in order, with no replies. BEGIN: no input, no charge. END: nothing. STATE: the state. SHUTDOWN, or the socket closed: exit. Anything else gets an ERROR, and the driver exits.
Run it
Build it, then run hello under the reference core with it, from the top folder of the sources (cargo build --release -p terse-bus -p terse-devices builds the core and the reference drivers):
cargo build --release \
--manifest-path examples/device/rust/Cargo.toml
target/release/terse-bus programs/hello/hello.terse \
--frames 30 --hash \
--driver 2=$PWD/examples/device/rust/target/release/terminal
819432152b38626f8fc54b43f50d5d4c501dc99e6904315b61dc78b796c611e2
the hash the reference terminal gives, and with --hash-every 1, the same 30 hashes. The hosts of "Make a host" take it too: this is a Go core with a Rust driver, from examples/host/go after go build -o bin/ ./...:
bin/step4 ../../../programs/hello/hello.terse 30 \
../../device/rust/target/release/terminal
819432152b38626f8fc54b43f50d5d4c501dc99e6904315b61dc78b796c611e2
What is missing
Enough for hello, not yet a terminal. A complete one also has: the other five calls (get_cursor, get_colours, cells_read, palette_set, size); commands 1 to 3, 5 and 6 (clear, scroll up and down, show and hide the cursor); in write, the control characters backspace, tab, carriage return and form feed, wide characters (two cells), and a UTF-8 character cut between two writes, kept in the state. It does not answer --version or RESTORE, so it cannot be installed or restore a snapshot.
All of that is in native/driver-example/terminal.c, 583 lines of C. The reference terminal is crates/terse-core/src/terminal.rs, served by crates/terse-devices/src/bin/terminal.rs.
What you have now
A device of your own, running under the reference core with the reference's hashes. Next, mix your parts with the reference's: Swap in your own part.
The same driver in Go: "Make a device in Go", the page before this one. The rules: The terminal (device 2); DEVICES.md sections 1, 5, 6 (batching) and 13 (a minimal driver).