Make a device in Go

This driver is the terminal, device 2, in one file of Go with no dependencies: examples/device/go/main.go, 328 lines. It does what programs/hello needs, exactly as the reference does, and no more. gofmt indents with tabs; here they are shown as four spaces.

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. With that the core checks a call before sending it, and for a deferred call, one whose result and charge follow from its arguments, it can work them out itself and send the call later in a batch.

const (
    columns      = 80
    rows         = 30
    cells        = columns * rows
    cellSize     = 4
    grays        = 24
    continuation = 0xffff
)

const (
    write      = 0
    command    = 1
    setCursor  = 2
    setColours = 4
    cellsWrite = 7
)

const (
    clearScreen = 1
    scrollDown  = 3
    clearToEnd  = 4
)

const (
    a0, a1, a2   = 0, 1, 2
    none         = 0xff
    deferred     = 2
    buffered     = 4
    reads        = 1
    inROM        = 4
    failed       = 0xfffffffe
    returnsValue = 1
    returnsArg   = 2
    perFour      = 1
)

type entry struct {
    function, flags, buffer, length byte
    scale, least, most              uint32
    access, checked                 byte
    _                               [2]byte
    checkedMost                     uint32
    lengthResult, placeResult       uint32
    rule, ruleArg                   byte
    _                               [2]byte
    value, value2, charge           uint32
    chargeFlags, chargeArg          byte
    perByte                         uint16
    low, high, add                  uint32
}

var table = []entry{
    {function: write, flags: deferred | buffered, buffer: a0,
        length: a1, scale: 1, most: 4096,
        access: reads | inROM, checked: none,
        lengthResult: failed, placeResult: failed,
        rule: returnsArg, ruleArg: a1, chargeArg: none,
        perByte: 2},
    {function: command, flags: deferred, length: none,
        checked: none, rule: returnsValue, chargeArg: a0,
        low: clearScreen, high: scrollDown, add: 150},
    {function: setCursor, flags: deferred, length: none,
        checked: none, rule: returnsValue, chargeArg: none},
    {function: setColours, flags: deferred, length: none,
        checked: none, rule: returnsValue, chargeArg: none},
    {function: cellsWrite, flags: deferred | buffered,
        buffer: a1, length: a2, scale: cellSize,
        most: cells * cellSize, access: reads | inROM,
        checked: a0, checkedMost: cells - 1,
        lengthResult: failed, placeResult: failed,
        rule: returnsArg, ruleArg: a2, chargeFlags: perFour,
        chargeArg: none},
}

These are the five calls hello makes, by the terminal's numbers, all deferred. write returns a1 and costs 2 units a byte; command costs 150 for commands 1 to 3; cellsWrite returns a2 and costs a unit per 4 bytes.

entry is DEVICES.md section 5's layout, field for field, and binary.Append writes it as it stands: little-endian, the _ fields being reserved zeros. In short:

FieldsMeaning
buffer, lengththe arguments holding its address and length
scale, least, mostbytes per unit of length; its range in bytes
checked, checkedMostan argument and its greatest value
lengthResult, placeResultthe result for a bad length, a bad place
rule, ruleArg, valuea0: value if returnsValue, argument ruleArg if returnsArg
charge, chargeFlags, perBytecharge units, 1 per 4 bytes if perFour, perByte a byte
chargeArg, low, high, addadd if low ≤ the argument ≤ high

none (FFh) is "no argument", and failed (FFFF_FFFEh) the result of a bad buffer.

The terminal

type terminal struct {
    grid                          [cells * cellSize]byte
    col, row, fg, bg, shown, wrap byte
    palette                       []byte
    partial                       [4]byte
}

func newTerminal() *terminal {
    t := &terminal{fg: 7, shown: 1}
    t.palette = slices.Clone(xterm)
    for cell := range cells {
        t.put(cell, ' ')
    }
    levels := []byte{0, 95, 135, 175, 215, 255}
    for _, r := range levels {
        for _, g := range levels {
            for _, b := range levels {
                t.palette = append(t.palette, r, g, b)
            }
        }
    }
    for i := range byte(grays) {
        gray := 8 + 10*i
        t.palette = append(t.palette, gray, gray, gray)
    }
    return t
}

The grid is cells cells of cellSize bytes: the character (u16), then its foreground and background colours. At reset every cell is a space in colour 7 on 0. The palette is xterm's 256 colours, 3 bytes each: the 16 of xterm's own (the bytes xterm, in the file), a 6 × 6 × 6 cube of levels, and grays grays from 8 in steps of 10.

func (t *terminal) put(cell int, code uint16) {
    bytes := append(le.AppendUint16(nil, code), t.fg, t.bg)
    copy(t.grid[cellSize*cell:], bytes)
}
func (t *terminal) write(text []byte) {
    for _, r := range string(text) {
        if r == '\n' {
            t.newline()
        }
        if r < ' ' || r == '\x7f' {
            continue
        }
        if t.wrap == 1 {
            t.newline()
        }
        code := uint16(r)
        if r >= continuation {
            code = utf8.RuneError
        }
        t.put(int(t.row)*columns+int(t.col), code)
        if t.col == columns-1 {
            t.wrap = 1
        } else {
            t.col++
        }
    }
}

write decodes its bytes as UTF-8 with Go's own decoder (range over a string), 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 utf8.RuneError.

func (t *terminal) call(body []byte) (result, charge uint32) {
    args := body[argsAt:]
    a := func(i int) uint32 { return le.Uint32(args[4*i:]) }
    data := body[dataAt:][:le.Uint32(body[sizeAt:])]
    switch body[functionAt] {
    case write:
        t.write(data)
        return a(1), 2 * a(1)
    case command:
        if a(0) == clearToEnd {
            for col := int(t.col); col < columns; col++ {
                t.put(int(t.row)*columns+col, ' ')
            }
        }
        if a(0) >= clearScreen && a(0) <= scrollDown {
            return 0, 150
        }
    case setCursor:
        t.col = byte(min(a(0), columns-1))
        t.row = byte(min(a(1), rows-1))
        t.wrap = 0
    case setColours:
        if a(0) <= math.MaxUint8 {
            t.fg = byte(a(0))
        }
        if a(1) <= math.MaxUint8 {
            t.bg = byte(a(1))
        }
    case cellsWrite:
        for i, b := range data {
            at := cellSize*int(a(0)) + i
            t.grid[at%len(t.grid)] = b
        }
        return a(2), uint32(len(data)+3) / 4
    }
    return 0, 0
}

func (t *terminal) state() []byte {
    state := append(t.grid[:], t.col, t.row, t.fg, t.bg)
    state = append(state, t.shown, t.wrap)
    state = append(state, t.palette...)
    return append(state, t.partial[:]...)
}

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    = 0x01
    OPEN     = 0x03
    CLOSE    = 0x04
    CALL     = 0x10
    BATCH    = 0x11
    BEGIN    = 0x30
    END      = 0x31
    STATE    = 0x40
    SHUTDOWN = 0x60
    ERROR    = 0x7f
    REPLY    = 0x80
)

const (
    addressSize   = 8
    protocol      = 1
    onSocket      = 0
    took          = 1
    terminalSlot  = 2
    deviceVersion = 0
    slotsAt       = 8
    functionAt    = 1
    argsAt        = 4
    sizeAt        = 36
    dataAt        = 40
    batchCountAt  = 4
    batchCallsAt  = 8
)

func words(b []byte, values ...uint32) []byte {
    for _, v := range values {
        b = le.AppendUint32(b, v)
    }
    return b
}

func hello(body []byte) []byte {
    name := "terminal (Go example)"
    reply := []byte{HELLO | REPLY, protocol, onSocket, 0}
    reply = le.AppendUint16(reply, uint16(len(name)))
    reply = append(reply, name...)
    slots := body[slotsAt+1:][:body[slotsAt]]
    reply = append(reply, 0, 0, 0, 0, byte(len(slots)))
    for _, slot := range slots {
        var entries []entry
        if slot == terminalSlot {
            entries = table
        }
        count := byte(len(entries))
        reply = append(reply, slot, deviceVersion, 0, count)
        reply, _ = binary.Append(reply, le, entries)
    }
    return append(reply, 0, 0, 0)
}

func main() {
    conn, err := net.Dial("unix", os.Getenv("TERSE_BUS_SOCKET"))
    if err != nil {
        panic(err)
    }
    send := func(address, body []byte) {
        message := words(nil, uint32(addressSize+len(body)))
        conn.Write(append(append(message, address...), body...))
    }
    machines := map[uint32]*terminal{}
    for {
        var size [4]byte
        if _, err := io.ReadFull(conn, size[:]); err != nil {
            return
        }
        message := make([]byte, le.Uint32(size[:]))
        if _, err := io.ReadFull(conn, message); err != nil {
            return
        }
        address := message[:addressSize]
        body := message[addressSize:]
        instance := le.Uint32(address)
        t := machines[instance]
        switch body[0] {
        case HELLO:
            send(address, hello(body))
        case OPEN:
            machines[instance] = newTerminal()
            reply := []byte{OPEN | REPLY, took, 0, 0, 0, 0}
            send(address, reply)
        case CLOSE:
            delete(machines, instance)
        case CALL:
            result, charge := t.call(body)
            reply := []byte{CALL | REPLY, 0, 0, 0}
            send(address, words(reply, result, 0, charge, 0))
        case BATCH:
            calls := body[batchCallsAt:]
            for range le.Uint32(body[batchCountAt:]) {
                size := le.Uint32(calls)
                call := calls[4:][:size]
                instance := le.Uint32(call)
                machines[instance].call(call[addressSize:])
                calls = calls[4+size:]
            }
        case BEGIN:
            reply := []byte{BEGIN | REPLY, 0, 0, 0}
            send(address, words(reply, 0, 0, 0, 0))
        case END:
        case STATE:
            state := t.state()
            reply := []byte{STATE | REPLY, 0, 0, 0}
            reply = words(reply, uint32(len(state)))
            send(address, append(reply, state...))
        case SHUTDOWN:
            return
        default:
            reply := append([]byte{ERROR}, "not handled"...)
            send(address, reply)
            return
        }
    }
}

The core starts the driver with the socket's path in TERSE_BUS_SOCKET. Each message is a length, an address of addressSize 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:

BodyFields
HELLO8: the number of slots asked; 9: the slots
its replyprotocol, onSocket, reserved; the name; width, height (0: any); per slot: slot, deviceVersion, layers (0), entries; 0 properties, subscriptions, services
OPEN replytook, 2 reserved, a reason (u16 length, 0)
CALL1: function; 4: a0 to a5; 28: budget; 36: buffer length; 40: the buffer
RESULTflags 0, 2 reserved; a0, a1 (unused), charge, 0 writes
BATCH4: count; 8: the CALLs, each a u32 length, address and body
INPUTS3 reserved; charge, events, writes, record: all 0
STATE reply3 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):

go build -C examples/device/go
target/release/terse-bus programs/hello/hello.terse \
    --frames 30 --hash \
    --driver 2=$PWD/examples/device/go/terminal
819432152b38626f8fc54b43f50d5d4c501dc99e6904315b61dc78b796c611e2

--driver 2= makes the program the driver of slot 2. Without it the reference terminal serves, and the hash is the same; with --hash-every 1 instead of --hash, so are all 30. --dump prints the screen.

The hosts of "Make a host" take it too, the Rust one as well as the Go one: this is a Rust core with a Go driver, from examples/host/rust after cargo build --release:

target/release/step4 ../../../programs/hello/hello.terse 30 \
    ../../device/go/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; replacement characters exactly as the WHATWG decoder gives them (Go's decoder gives one per bad byte). 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, the same driver in Rust: Make a device in Rust. Or mix your parts with the reference's: Swap in your own part.

The rules: The terminal (device 2); DEVICES.md sections 1, 5, 6 (batching) and 13 (a minimal driver).