git clone https://garage44.eu/jeroen/pinnacle.git.. /records/src/lib.rs
//! Typed output instead of a byte stream: what a program sends the
//! terminal (`docs/terminal-and-agent.md`).
//!
//! A record is one channel message: [`MARK`], its kind, two bytes of
//! padding, then its body. [`MARK`] never occurs in UTF-8, so one channel
//! carries both a record-speaking program's records and a plain program's
//! text: [`Output::of`] tells them apart. Strings in a body are a u32 length
//! (little-endian) and their bytes; numbers are little-endian. A file or an
//! image travels as the message's handle, not in its body.
//!
//! [`start`] writes and reads the start message a command is given, the one
//! Rust's std on Pinnacle reads (`std/README.md`).
#![no_std]
extern crate alloc;
pub mod log;
pub mod pipe;
pub mod start;
pub mod verbs;
use alloc::string::String;
use alloc::vec::Vec;
/// The first byte of every record: not UTF-8, so never the start of text.
pub const MARK: u8 = 0xFE;
/// The largest record, as the kernel's largest message.
pub const MAX: usize = 4096;
/// Record kinds (the second byte).
pub mod kind {
pub const TEXT: u8 = 1;
pub const TABLE: u8 = 2;
pub const PROGRESS: u8 = 3;
pub const FILE: u8 = 4;
pub const IMAGE: u8 = 5;
pub const ASK: u8 = 6;
pub const STATUS: u8 = 7;
/// Terminal → program: the answer to an [`ASK`].
pub const ANSWER: u8 = 0x81;
}
/// What an [`Record::Ask`] wants.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AskKind {
/// A line of text.
Text = 1,
/// One of the options.
Choice = 2,
/// Yes or no.
YesNo = 3,
/// A file, which comes as a handle with the answer.
File = 4,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Record {
/// Running text; the terminal wraps it. Line ends start new lines.
Text(String),
/// Rows of cells under named columns; the terminal picks the widths.
Table {
columns: Vec<String>,
rows: Vec<Vec<String>>,
},
/// How far a piece of work is; sent again with the same `id` to update.
Progress {
id: u32,
done: u64,
total: u64,
label: String,
},
/// A file, whose handle the message carries.
File { name: String, size: u64 },
/// An image of 32-bit pixels, whose shared memory the message carries.
Image { width: u32, height: u32 },
/// A question for whoever is at the terminal, person or agent.
Ask {
id: u32,
kind: AskKind,
prompt: String,
options: Vec<String>,
},
/// How the command ended: 0 for success, and a line saying what it did.
Status { code: u64, summary: String },
/// The answer to the [`Record::Ask`] `id` (terminal → program).
Answer { id: u32, text: String },
}
impl Record {
pub fn text(body: &str) -> Record {
Record::Text(body.into())
}
fn kind(&self) -> u8 {
match self {
Record::Text(_) => kind::TEXT,
Record::Table { .. } => kind::TABLE,
Record::Progress { .. } => kind::PROGRESS,
Record::File { .. } => kind::FILE,
Record::Image { .. } => kind::IMAGE,
Record::Ask { .. } => kind::ASK,
Record::Status { .. } => kind::STATUS,
Record::Answer { .. } => kind::ANSWER,
}
}
/// The record as one message, or `None` when it is larger than one
/// ([`MAX`]): a long text or table is sent as several records.
pub fn encode(&self) -> Option<Vec<u8>> {
let mut out = alloc::vec![MARK, self.kind(), 0, 0];
let w = &mut out;
match self {
Record::Text(body) => put_str(w, body),
Record::Table { columns, rows } => {
put_list(w, columns);
put_u32(w, rows.len() as u32);
for row in rows {
put_list(w, row);
}
}
Record::Progress {
id,
done,
total,
label,
} => {
put_u32(w, *id);
put_u64(w, *done);
put_u64(w, *total);
put_str(w, label);
}
Record::File { name, size } => {
put_str(w, name);
put_u64(w, *size);
}
Record::Image { width, height } => {
put_u32(w, *width);
put_u32(w, *height);
}
Record::Ask {
id,
kind,
prompt,
options,
} => {
put_u32(w, *id);
w.push(*kind as u8);
put_str(w, prompt);
put_list(w, options);
}
Record::Status { code, summary } => {
put_u64(w, *code);
put_str(w, summary);
}
Record::Answer { id, text } => {
put_u32(w, *id);
put_str(w, text);
}
}
(out.len() <= MAX).then_some(out)
}
/// The record a message holds, or `None` for one that is not a record
/// or does not parse.
pub fn decode(message: &[u8]) -> Option<Record> {
let (&[MARK, kind, _, _], body) = message.split_first_chunk::<4>()? else {
return None;
};
let r = &mut Reader(body);
let record = match kind {
kind::TEXT => Record::Text(r.string()?),
kind::TABLE => {
let columns = r.list()?;
let count = r.u32()?;
let mut rows = Vec::new();
for _ in 0..count {
rows.push(r.list()?);
}
Record::Table { columns, rows }
}
kind::PROGRESS => Record::Progress {
id: r.u32()?,
done: r.u64()?,
total: r.u64()?,
label: r.string()?,
},
kind::FILE => Record::File {
name: r.string()?,
size: r.u64()?,
},
kind::IMAGE => Record::Image {
width: r.u32()?,
height: r.u32()?,
},
kind::ASK => Record::Ask {
id: r.u32()?,
kind: match r.take(1)?[0] {
1 => AskKind::Text,
2 => AskKind::Choice,
3 => AskKind::YesNo,
4 => AskKind::File,
_ => return None,
},
prompt: r.string()?,
options: r.list()?,
},
kind::STATUS => Record::Status {
code: r.u64()?,
summary: r.string()?,
},
kind::ANSWER => Record::Answer {
id: r.u32()?,
text: r.string()?,
},
_ => return None,
};
r.0.is_empty().then_some(record)
}
}
/// What one message on a command's output is.
#[derive(Debug, PartialEq, Eq)]
pub enum Output<'a> {
Record(Record),
/// Bytes from a program that does not speak records (a `println!`):
/// shown as text.
Bytes(&'a [u8]),
/// It starts as a record but is not one: shown as an error.
Malformed,
}
impl Output<'_> {
pub fn of(message: &[u8]) -> Output<'_> {
match message.first() {
Some(&MARK) => Record::decode(message).map_or(Output::Malformed, Output::Record),
_ => Output::Bytes(message),
}
}
}
/// `rows` under `columns`, as as few tables as fit a message each.
pub fn tables(columns: &[&str], rows: &[Vec<String>]) -> Vec<Record> {
let columns: Vec<String> = columns.iter().map(|&c| c.into()).collect();
let mut out = Vec::new();
let mut batch: Vec<Vec<String>> = Vec::new();
for row in rows {
batch.push(row.clone());
let table = Record::Table {
columns: columns.clone(),
rows: batch.clone(),
};
if table.encode().is_none() {
let row = batch.pop().unwrap();
if !batch.is_empty() {
out.push(Record::Table {
columns: columns.clone(),
rows: core::mem::take(&mut batch),
});
}
// A row too large on its own is cut to what fits.
batch.push(row.iter().map(|cell| String::from(clip(cell, 256))).collect());
}
}
if !batch.is_empty() || out.is_empty() {
out.push(Record::Table { columns, rows: batch });
}
out
}
/// `text` as as few text records as fit a message each, split at line ends
/// where it can and otherwise at a character's edge.
pub fn texts(text: &str) -> Vec<Record> {
let room = MAX - 8;
let mut out = Vec::new();
let mut rest = text;
while rest.len() > room {
let cut = clip(rest, room);
let at = cut.rfind('\n').map_or(cut.len(), |i| i + 1);
let part = &rest[..at];
out.push(Record::Text(part.strip_suffix('\n').unwrap_or(part).into()));
rest = &rest[at..];
}
out.push(Record::Text(rest.into()));
out
}
/// `text` cut, at a character's edge, to at most `max` bytes.
pub fn clip(text: &str, max: usize) -> &str {
let mut end = text.len().min(max);
while !text.is_char_boundary(end) {
end -= 1;
}
&text[..end]
}
fn put_u32(out: &mut Vec<u8>, v: u32) {
out.extend_from_slice(&v.to_le_bytes());
}
fn put_u64(out: &mut Vec<u8>, v: u64) {
out.extend_from_slice(&v.to_le_bytes());
}
pub(crate) fn put_str(out: &mut Vec<u8>, s: &str) {
put_bytes(out, s.as_bytes());
}
pub(crate) fn put_bytes(out: &mut Vec<u8>, b: &[u8]) {
put_u32(out, b.len() as u32);
out.extend_from_slice(b);
}
fn put_list(out: &mut Vec<u8>, items: &[String]) {
put_u32(out, items.len() as u32);
for item in items {
put_str(out, item);
}
}
/// Reads a body front to back; every read fails past its end.
pub(crate) struct Reader<'a>(pub(crate) &'a [u8]);
impl<'a> Reader<'a> {
pub(crate) fn take(&mut self, n: usize) -> Option<&'a [u8]> {
let (bytes, rest) = self.0.split_at_checked(n)?;
self.0 = rest;
Some(bytes)
}
pub(crate) fn u32(&mut self) -> Option<u32> {
Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?))
}
fn u64(&mut self) -> Option<u64> {
Some(u64::from_le_bytes(self.take(8)?.try_into().ok()?))
}
pub(crate) fn bytes(&mut self) -> Option<&'a [u8]> {
let n = self.u32()? as usize;
self.take(n)
}
pub(crate) fn string(&mut self) -> Option<String> {
Some(core::str::from_utf8(self.bytes()?).ok()?.into())
}
fn list(&mut self) -> Option<Vec<String>> {
let count = self.u32()?;
// Each item takes at least its length's four bytes: a count larger
// than the body could hold is a lie, not a reason to allocate.
if count as usize > self.0.len() / 4 {
return None;
}
(0..count).map(|_| self.string()).collect()
}
}
#[cfg(test)]
mod tests {
extern crate std;
use super::*;
use alloc::vec;
fn s(v: &str) -> String {
v.into()
}
#[test]
fn every_kind_round_trips() {
let all = [
Record::text("hello, wereld"),
Record::Table {
columns: vec![s("class"), s("driver")],
rows: vec![vec![s("storage"), s("virtio-blk")], vec![s("-"), s("")]],
},
Record::Progress {
id: 3,
done: 10,
total: 40,
label: s("copying"),
},
Record::File {
name: s("note.txt"),
size: 1 << 33,
},
Record::Image {
width: 64,
height: 48,
},
Record::Ask {
id: 9,
kind: AskKind::Choice,
prompt: s("Which?"),
options: vec![s("this"), s("that")],
},
Record::Status {
code: 0,
summary: s("done"),
},
Record::Answer {
id: 9,
text: s("that"),
},
];
for record in all {
let bytes = record.encode().unwrap();
assert_eq!(bytes[0], MARK);
assert_eq!(Record::decode(&bytes), Some(record.clone()));
assert_eq!(Output::of(&bytes), Output::Record(record));
}
}
#[test]
fn text_from_a_plain_program_is_bytes() {
assert_eq!(Output::of(b"std ok\n"), Output::Bytes(b"std ok\n"));
// Any UTF-8 at all: its first byte is never the mark.
for c in ['a', 'é', '€', '😀'] {
let mut b = [0; 4];
assert_ne!(c.encode_utf8(&mut b).as_bytes()[0], MARK);
}
}
#[test]
fn broken_records_are_refused() {
let good = Record::text("abc").encode().unwrap();
// Cut short, a byte too many, an unknown kind, a lying count.
assert_eq!(Output::of(&good[..good.len() - 1]), Output::Malformed);
let mut long = good.clone();
long.push(0);
assert_eq!(Record::decode(&long), None);
assert_eq!(Record::decode(&[MARK, 0x55, 0, 0]), None);
let mut lie = vec![MARK, kind::TABLE, 0, 0];
lie.extend_from_slice(&u32::MAX.to_le_bytes());
assert_eq!(Record::decode(&lie), None);
assert_eq!(Record::decode(&[MARK]), None);
}
#[test]
fn too_large_is_not_encoded_and_splits() {
let big = "regel\n".repeat(2000);
assert!(Record::text(&big).encode().is_none());
let parts = texts(&big);
assert!(parts.len() > 1);
let lines: Vec<&str> = parts
.iter()
.map(|p| {
assert!(p.encode().is_some());
let Record::Text(t) = p else { panic!() };
t.as_str()
})
.collect();
assert_eq!(lines.join("\n"), big);
let rows: Vec<Vec<String>> = (0..500)
.map(|i| vec![alloc::format!("{i}"), s("virtio")])
.collect();
let parts = tables(&["n", "driver"], &rows);
assert!(parts.len() > 1);
let mut count = 0;
for p in &parts {
assert!(p.encode().is_some());
let Record::Table { rows, .. } = p else { panic!() };
count += rows.len();
}
assert_eq!(count, 500);
}
}