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, 415 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, by the terminal's numbers:
const A0: u8 = 0; const A1: u8 = 1; const A2: u8 = 2; const NONE: u8 = 0xff; const DEFERRED: u8 = 2; const BUFFERED: u8 = 4; const READS: u8 = 1; const IN_ROM: u8 = 4; const FAILED: u32 = 0xffff_fffe; const RETURNS_VALUE: u8 = 1; const RETURNS_ARG: u8 = 2; const PER_FOUR: u8 = 1;
fn table() -> Vec<Entry> { vec![ Entry { function: WRITE, flags: DEFERRED | BUFFERED, buffer: A0, length: A1, scale: 1, most: 4096, access: READS | IN_ROM, length_result: FAILED, place_result: FAILED, rule: RETURNS_ARG, rule_arg: A1, per_byte: 2, ..plain() }, Entry { function: COMMAND, charge_arg: A0, low: CLEAR_SCREEN, high: SCROLL_DOWN, add: 150, ..plain() }, Entry { function: SET_CURSOR, ..plain() }, Entry { function: SET_COLOURS, ..plain() }, Entry { function: CELLS_WRITE, flags: DEFERRED | BUFFERED, buffer: A1, length: A2, scale: CELL_SIZE as u32, most: (CELLS * CELL_SIZE) as u32, access: READS | IN_ROM, checked: A0, checked_most: CELLS as u32 - 1, length_result: FAILED, place_result: FAILED, rule: RETURNS_ARG, rule_arg: A2, charge_flags: PER_FOUR, ..plain() }, ] }
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. write returns a1 and costs 2 units a byte; command costs 150 for commands 1 to 3; cells_write returns a2 and costs a unit per 4 bytes. encode writes an entry, little-endian, the 0s being reserved bytes:
impl Entry { fn encode(&self) -> Vec<u8> { let e = self; let mut b = vec![e.function, e.flags, e.buffer, e.length]; words(&mut b, &[e.scale, e.least, e.most]); b.extend([e.access, e.checked, 0, 0]); words( &mut b, &[e.checked_most, e.length_result, e.place_result], ); b.extend([e.rule, e.rule_arg, 0, 0]); words(&mut b, &[e.value, e.value2, e.charge]); b.extend([e.charge_flags, e.charge_arg]); b.extend(e.per_byte.to_le_bytes()); words(&mut b, &[e.low, e.high, e.add]); b } }
| Fields | Meaning |
|---|---|
buffer, length | the arguments holding its address and length |
scale, least, most | bytes per unit of length; its range in bytes |
checked, checked_most | an argument and its greatest value |
length_result, place_result | the result for a bad length, a bad place |
rule, rule_arg, value | a0: value if RETURNS_VALUE, argument rule_arg if RETURNS_ARG |
charge, charge_flags, per_byte | charge units, 1 per 4 bytes if PER_FOUR, per_byte a byte |
charge_arg, low, high, add | add if low ≤ the argument ≤ high |
NONE (FFh) is "no argument", and FAILED (FFFF_FFFEh) the result of a bad buffer.
The terminal
const COLUMNS: usize = 80; const ROWS: usize = 30; const CELLS: usize = COLUMNS * ROWS; const CELL_SIZE: usize = 4; const GRAYS: u8 = 24; const CONTINUATION: u16 = 0xffff;
Terminal holds the grid, the cursor, the colours and the palette. The grid is CELLS cells of CELL_SIZE bytes: the character (u16), then its foreground and background colours. At reset (Terminal::new) every cell is a space in colour 7 on 0. The palette is xterm's 256 colours, 3 bytes each: xterm's own 16 (XTERM), a 6 × 6 × 6 cube, and GRAYS grays from 8 in steps of 10.
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(CONTINUATION) | Err(_) => { char::REPLACEMENT_CHARACTER as u16 } 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). A cell holds a character up to FFFFh, which is the CONTINUATION of a wide character, so that and anything above it is written as the replacement character.
fn call(&mut self, body: &[u8]) -> (u32, u32) { let a = |i: usize| word(body, ARGS_AT + 4 * i); let size = word(body, SIZE_AT) as usize; let data = &body[DATA_AT..DATA_AT + size]; match body[FUNCTION_AT] { WRITE => { self.write(data); return (a(1), 2 * a(1)); } COMMAND => match a(0) { CLEAR_SCREEN..=SCROLL_DOWN => return (0, 150), CLEAR_TO_END => { let line = self.row * COLUMNS; for col in self.col..COLUMNS { self.put(line + col, ' ' as u16); } } _ => {} }, SET_CURSOR => { self.col = (a(0) as usize).min(COLUMNS - 1); self.row = (a(1) as usize).min(ROWS - 1); self.wrap = false; } SET_COLOURS => { self.fg = u8::try_from(a(0)).unwrap_or(self.fg); self.bg = u8::try_from(a(1)).unwrap_or(self.bg); } CELLS_WRITE => { let start = CELL_SIZE * 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(self.partial); 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 partial, a UTF-8 character cut between two writes (a count and 3 bytes; none here).
The messages
const HELLO: u8 = 0x01; const OPEN: u8 = 0x03; const CLOSE: u8 = 0x04; const CALL: u8 = 0x10; const BATCH: u8 = 0x11; const BEGIN: u8 = 0x30; const END: u8 = 0x31; const STATE: u8 = 0x40; const SHUTDOWN: u8 = 0x60; const ERROR: u8 = 0x7f; const REPLY: u8 = 0x80; const ADDRESS_SIZE: usize = 8; const PROTOCOL: u8 = 1; const ON_SOCKET: u8 = 0; const TOOK: u8 = 1; const TERMINAL_SLOT: u8 = 2; const DEVICE_VERSION: u8 = 0; const SLOTS_AT: usize = 8; const FUNCTION_AT: usize = 1; const ARGS_AT: usize = 4; const SIZE_AT: usize = 36; const DATA_AT: usize = 40; const BATCH_COUNT_AT: usize = 4; const BATCH_CALLS_AT: usize = 8; fn hello(body: &[u8]) -> Vec<u8> { let name = "terminal (Rust example)"; let mut reply = vec![HELLO | REPLY, PROTOCOL, ON_SOCKET, 0]; reply.extend((name.len() as u16).to_le_bytes()); reply.extend(name.as_bytes()); let count = body[SLOTS_AT] as usize; let slots = &body[SLOTS_AT + 1..][..count]; reply.extend([0, 0, 0, 0, count as u8]); for &slot in slots { let mut entries = vec![]; if slot == TERMINAL_SLOT { entries = table(); } let count = entries.len() as u8; reply.extend([slot, DEVICE_VERSION, 0, count]); for entry in &entries { 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 size = [0; 4]; if stream.read_exact(&mut size).is_err() { return; } let mut message = vec![0; word(&size, 0) as usize]; if stream.read_exact(&mut message).is_err() { return; } let (address, body) = message.split_at(ADDRESS_SIZE); let instance = word(address, 0); let reply = match body[0] { HELLO => hello(body), OPEN => { machines.insert(instance, Terminal::new()); vec![OPEN | REPLY, TOOK, 0, 0, 0, 0] } CLOSE => { machines.remove(&instance); continue; } CALL => { let t = machines.get_mut(&instance).unwrap(); let (result, charge) = t.call(body); let mut reply = vec![CALL | REPLY, 0, 0, 0]; words(&mut reply, &[result, 0, charge, 0]); reply } BATCH => { let mut calls = &body[BATCH_CALLS_AT..]; for _ in 0..word(body, BATCH_COUNT_AT) { let size = word(calls, 0) as usize; let call = &calls[4..4 + size]; let t = machines.get_mut(&word(call, 0)); t.unwrap().call(&call[ADDRESS_SIZE..]); calls = &calls[4 + size..]; } continue; } BEGIN => { let mut reply = vec![BEGIN | REPLY, 0, 0, 0]; words(&mut reply, &[0, 0, 0, 0]); reply } END => continue, STATE => { let state = machines[&instance].state(); let mut reply = vec![STATE | REPLY, 0, 0, 0]; words(&mut reply, &[state.len() as u32]); reply.extend(state); reply } SHUTDOWN => return, _ => [&[ERROR], &b"not handled"[..]].concat(), }; let mut out = Vec::new(); words(&mut out, &[(ADDRESS_SIZE + reply.len()) as u32]); out.extend(address); out.extend(&reply); let sent = stream.write_all(&out); if sent.is_err() || reply[0] == ERROR { return; } } }
The core starts the driver with the socket's path in TERSE_BUS_SOCKET. Each message is a length, an address of ADDRESS_SIZE bytes (the instance, which machine, then the slot) and a body whose first byte is its type, named as DEVICES.md section 1 names them. A reply carries the address of its request, and its type is the request's with REPLY added. The bodies, after the type, by offset:
| Body | Fields |
|---|---|
| HELLO | 8: the number of slots asked; 9: the slots |
| its reply | PROTOCOL, ON_SOCKET, reserved; the name; width, height (0: any); per slot: slot, DEVICE_VERSION, layers (0), entries; 0 properties, subscriptions, services |
| OPEN reply | TOOK, 2 reserved, a reason (u16 length, 0) |
| CALL | 1: function; 4: a0 to a5; 28: budget; 36: buffer length; 40: the buffer |
| RESULT | flags 0, 2 reserved; a0, a1 (unused), charge, 0 writes |
| BATCH | 4: count; 8: the CALLs, each a u32 length, address and body |
| INPUTS | 3 reserved; charge, events, writes, record: all 0 |
| STATE reply | 3 reserved; the length; the state |
HELLO answers for the slots asked: 2 with its table, 10 (full text) with none. OPEN makes a machine's terminal, CLOSE drops it. BATCH holds deferred calls, carried out in order with no replies. SHUTDOWN, or the socket closed, ends the driver; 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).