Skip to main content

justerm_core/
serialize.rs

1//! Issue #6 — binary, reference-based wire format for a damage frame.
2//!
3//! `encode` a [`Frame`] to bytes, `decode` them back; the round-trip is the
4//! contract. Reference-based (colour refs, Unicode scalars — never resolved RGB
5//! or atlas ids) so the engine stays theme- and font-agnostic; the consumer's
6//! adapter resolves references before handing cells to the renderer. Format spec
7//! and rationale: `docs/architecture.md` §Serialization + ADR-0005.
8
9use crate::cell::{Cell, CellFlags};
10use crate::color::Color;
11use crate::cursor::CursorShape;
12use crate::damage::ScrollOp;
13use crate::input::MouseEvents;
14use crate::selection::SelectionSpan;
15use core::num::NonZeroU32;
16use std::collections::BTreeMap;
17
18/// Wire magic ("juSTerm") + format version. A new feature bumps `VERSION`.
19const MAGIC: [u8; 2] = *b"JT";
20const VERSION: u8 = 12; // v12 adds a fifth overlay group: the consumer-designated active search match's spans (#428); v11 adds a fourth overlay group: every live marker's absolute buffer line for the overview ruler (#120 S3); v10 adds a marker kind discriminant + optional i32 exit to the overlay marker group (#159); v9 adds the alt-screen flag in the header (#149); v8 adds the mouse wanted-events mask in the header (#129/ADR-0016); v7 overlay marker group (#118/ADR-0015); v6 overlay selection + search-match spans (#108/ADR-0014); v5 scroll position (#112/ADR-0013); v4 cursor shape+blink (#81); v3 cursor row/col/visibility (#38)
21
22/// The wire-format version (the gating `VERSION` byte), exposed so a binding can
23/// assert at load that its decoder matches the backend encoder (#34/ADR-0008).
24pub const WIRE_VERSION: u8 = VERSION;
25
26/// Whether a frame redraws everything or just its spans.
27#[derive(Clone, Copy, PartialEq, Eq, Debug)]
28pub enum FrameKind {
29    /// Every row is present (resize / alt-screen clear).
30    Full,
31    /// Only the listed spans changed since the consumer's ack.
32    Partial,
33}
34
35/// A damaged column run on one line, with its cells.
36///
37/// `combining` and `links` map a span-relative column to its frame-local index
38/// (1-based) — `combining` into [`Frame::side_table`], `links` into
39/// [`Frame::link_table`]. These are the per-cell `extra`/`link` references lifted
40/// out of the cell now that combining clusters (#45) and hyperlinks (#46) live in
41/// per-row maps. A column is present iff its cell carries the matching bit; on the
42/// wire they are the cell record's `extra`/`link` fields, so the bytes are
43/// unchanged.
44#[derive(Clone, PartialEq, Eq, Debug)]
45pub struct Span {
46    pub line: u16,
47    pub left: u16,
48    pub right: u16,
49    pub cells: Vec<Cell>,
50    pub combining: BTreeMap<usize, NonZeroU32>,
51    pub links: BTreeMap<usize, NonZeroU32>,
52}
53
54/// A stable handle to a buffer line, handed out by `Engine::add_marker` (#118).
55/// Monotonic per engine. The consumer attaches a decoration to the id; the frame
56/// reports where the marker currently sits, and `TermEvent::MarkerDisposed`
57/// signals when its line has left the buffer.
58#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
59pub struct MarkerId(pub u32);
60
61/// What a marker means (#158). A plain `add_marker` decoration carries no
62/// semantics ([`MarkerKind::Plain`]); OSC 133 shell-integration marks carry the
63/// command-boundary role (prompt/command/output start, or command finished with
64/// its optional exit code). The engine only *parses and anchors* these — the
65/// success/failure colour, earcon and prompt-to-prompt navigation are consumer
66/// policy (ADR-0017), driven off the kind + exit the wire (#159) carries.
67#[derive(Clone, Copy, PartialEq, Eq, Debug)]
68pub enum MarkerKind {
69    /// A `add_marker` decoration anchor (#118) — no OSC-133 semantics.
70    Plain,
71    /// OSC `133;A` — the shell prompt begins here.
72    PromptStart,
73    /// OSC `133;B` — the typed command begins here (the prompt ended).
74    CommandStart,
75    /// OSC `133;C` — the command was submitted; its output begins here.
76    OutputStart,
77    /// OSC `133;D[;exit]` — the command finished, with its exit code if reported
78    /// (absent, empty or non-numeric → `None`).
79    CommandFinished(Option<i32>),
80}
81
82/// A marker projected onto the viewport (#118): its id, the row it sits on, and
83/// its kind (#159). Only markers visible in the current viewport are reported; an
84/// off-screen marker is omitted but still alive (death comes via `MarkerDisposed`,
85/// not absence — so the consumer can tell "scrolled away" from "gone"). The kind
86/// carries the OSC 133 command-boundary role + exit code so the consumer can drive
87/// prompt-to-prompt navigation and success/fail signals (#160).
88#[derive(Clone, Copy, PartialEq, Eq, Debug)]
89pub struct MarkerPosition {
90    pub id: MarkerId,
91    pub row: usize,
92    pub kind: MarkerKind,
93}
94
95/// A marker's absolute buffer line (#120 S3, v11). Unlike [`MarkerPosition`],
96/// this is reported for EVERY live marker — on-screen or not — so a frame-mode
97/// consumer can place overview-ruler marks buffer-relatively (dividing by
98/// `scrollback + rows`), the whole point of a ruler being to show off-viewport
99/// anchors. The consumer joins `id` with its decoration registry; the ruler mark's
100/// colour is the consumer's (theme-agnostic), so no kind/exit rides here.
101#[derive(Clone, Copy, PartialEq, Eq, Debug)]
102pub struct MarkerLine {
103    pub id: MarkerId,
104    /// Absolute buffer line, in the same `[0, scrollback_len + rows)` frame the
105    /// header's `scrollback_len`/`display_offset` use.
106    pub line: u32,
107}
108
109/// Interaction overlays projected onto the viewport (#108): highlight spans the
110/// engine carries on the frame so a frame-mode consumer can paint them without
111/// an in-process model query. Positions only — highlight colour is the
112/// consumer's (theme-agnostic). Coordinates are viewport rows/cols, re-projected
113/// by `frame()` against the scroll offset so the engine stays the single
114/// anchoring authority.
115#[derive(Clone, PartialEq, Eq, Debug, Default)]
116pub struct Overlay {
117    /// The live selection projected onto visible rows (`selection_range`).
118    pub selection: Vec<SelectionSpan>,
119    /// The search highlights projected onto visible rows. Search matches
120    /// are consumer-owned (next/prev navigation holds the `Vec<Match>`), so the
121    /// consumer hands the highlight set back via `set_search_highlights` and the
122    /// engine projects it here — mirroring how the engine-owned selection rides.
123    pub matches: Vec<SelectionSpan>,
124    /// Engine-owned markers visible in this viewport (#118): persistent line
125    /// anchors for decorations. Unlike the selection (cleared on a screen swap)
126    /// and search highlights (invalidated on output), markers re-anchor through
127    /// buffer mutation and survive an alt-screen excursion; only their viewport
128    /// position rides here.
129    pub markers: Vec<MarkerPosition>,
130    /// Every live marker's absolute buffer line (#120 S3, v11), on-screen or not —
131    /// the overview ruler needs off-viewport anchors, which `markers` (viewport-
132    /// only) can't supply. A superset of `markers` by id; different frame of
133    /// reference (absolute line, not viewport row).
134    pub marker_lines: Vec<MarkerLine>,
135    /// The *active* (current) search match's spans (#428, v12): the member of
136    /// `matches` the consumer designated via `set_active_search_highlight`
137    /// (which match is active is consumer policy — next/prev navigation).
138    /// Projected by the same mechanism as `matches`, and *also* present there —
139    /// the renderer's highlight ranking resolves the overlap (#424), not
140    /// exclusion here. Empty when nothing is designated.
141    pub active_match: Vec<SelectionSpan>,
142}
143
144/// One serialized damage cycle: the decoded logical form that `encode`/`decode`
145/// round-trip. `side_table` holds this frame's grapheme clusters (referenced by
146/// each cell's frame-local `extra`); `link_table` holds its OSC 8 hyperlink URIs
147/// (referenced by each cell's frame-local `link`).
148#[derive(Clone, PartialEq, Eq, Debug)]
149pub struct Frame {
150    pub cols: u16,
151    pub rows: u16,
152    pub kind: FrameKind,
153    /// Cursor row/col in screen coordinates (0-based), and whether the engine
154    /// shows it (DECTCEM). Rides in the header because the cursor moves with
155    /// almost every frame (#38). *Drawing* the cursor — cell-invert / overlay —
156    /// stays the consumer's renderer adapter; the engine only reports state.
157    pub cursor_row: u16,
158    pub cursor_col: u16,
159    pub cursor_visible: bool,
160    /// The caret shape (DECSCUSR #89) and whether it blinks (att610 ?12, #81).
161    /// Reported for the renderer; drawing/animation stays the consumer's.
162    pub cursor_shape: CursorShape,
163    pub cursor_blink: bool,
164    /// Viewport scroll position (#112 / ADR-0013), for the consumer's scrollbar.
165    /// `display_offset` = lines scrolled up from the bottom (0 = following the
166    /// live screen); `scrollback_len` = history lines (total = `+ rows`). Ride in
167    /// the header like the cursor — per-frame viewport state, not cell content.
168    pub display_offset: u32,
169    pub scrollback_len: u32,
170    /// The mouse tracking mode as a *wanted-events* mask (#129): which mouse
171    /// event categories the app asked to receive, so the consumer routes an event
172    /// to the app (bit set) or keeps it local. `empty()` = no reporting. Rides the
173    /// header like the cursor — per-frame mode state the consumer reads, not cell
174    /// content. Positions/encoding never cross; the backend encodes via
175    /// `encode_mouse`.
176    pub mouse_events: MouseEvents,
177    /// Whether the alternate screen (`?1049`/`?47`) is active (#149). Buffer-global
178    /// state a frame-mode consumer can't derive from viewport damage — the
179    /// accessibility announce policy (#119) gates on it (suppress TUI repaints).
180    /// Rides the header like the cursor scalars (ADR-0014).
181    pub alt_screen: bool,
182    pub scroll: Option<ScrollOp>,
183    pub spans: Vec<Span>,
184    pub side_table: Vec<Vec<char>>,
185    pub link_table: Vec<String>,
186    /// Interaction overlays for this viewport (#108): selection, search
187    /// highlights, the active match, and markers — see [`Overlay`].
188    pub overlay: Overlay,
189}
190
191/// Why a byte buffer could not be decoded into a [`Frame`].
192#[derive(Clone, Copy, PartialEq, Eq, Debug)]
193pub enum DecodeError {
194    /// Ran out of bytes mid-field.
195    Truncated,
196    /// First two bytes are not the wire magic.
197    BadMagic,
198    /// Unsupported format version.
199    BadVersion(u8),
200    /// A tag/kind byte held a value outside its defined set.
201    BadTag,
202    /// A span's `left` was past its `right` (would underflow the cell count).
203    BadSpan,
204}
205
206/// Serialize a frame to the binary wire format.
207pub fn encode(frame: &Frame) -> Vec<u8> {
208    let mut out = Vec::new();
209    out.extend_from_slice(&MAGIC);
210    out.push(VERSION);
211    out.push(frame.scroll.is_some() as u8);
212    out.push(match frame.kind {
213        FrameKind::Full => 0,
214        FrameKind::Partial => 1,
215    });
216    out.extend_from_slice(&frame.cols.to_le_bytes());
217    out.extend_from_slice(&frame.rows.to_le_bytes());
218    out.extend_from_slice(&frame.cursor_row.to_le_bytes());
219    out.extend_from_slice(&frame.cursor_col.to_le_bytes());
220    out.push(frame.cursor_visible as u8);
221    out.push(match frame.cursor_shape {
222        CursorShape::Block => 0,
223        CursorShape::Underline => 1,
224        CursorShape::Bar => 2,
225    });
226    out.push(frame.cursor_blink as u8);
227    out.extend_from_slice(&frame.display_offset.to_le_bytes());
228    out.extend_from_slice(&frame.scrollback_len.to_le_bytes());
229    // Mouse wanted-events mask (#129): one byte in the header, like the cursor
230    // scalars. Off = 0.
231    out.push(frame.mouse_events.bits());
232    // Alt-screen flag (#149): one byte in the header, like the cursor scalars.
233    out.push(frame.alt_screen as u8);
234    if let Some(s) = frame.scroll {
235        out.extend_from_slice(&(s.top as u16).to_le_bytes());
236        out.extend_from_slice(&(s.bottom as u16).to_le_bytes());
237        out.extend_from_slice(&(s.count as i16).to_le_bytes());
238    }
239    out.extend_from_slice(&(frame.spans.len() as u16).to_le_bytes());
240    for span in &frame.spans {
241        out.extend_from_slice(&span.line.to_le_bytes());
242        out.extend_from_slice(&span.left.to_le_bytes());
243        out.extend_from_slice(&span.right.to_le_bytes());
244        for (col, cell) in span.cells.iter().enumerate() {
245            // The grapheme and hyperlink indices now ride on the span (per
246            // column), not the cell.
247            let extra = span.combining.get(&col).map_or(0, |n| n.get() as u16);
248            let link = span.links.get(&col).map_or(0, |n| n.get() as u16);
249            out.extend_from_slice(&encode_cell_record(cell, extra, link));
250        }
251    }
252    out.extend_from_slice(&(frame.side_table.len() as u16).to_le_bytes());
253    for cluster in &frame.side_table {
254        out.extend_from_slice(&(cluster.len() as u16).to_le_bytes());
255        for &ch in cluster {
256            out.extend_from_slice(&(ch as u32).to_le_bytes());
257        }
258    }
259    // Hyperlink side-table: each URI as a length-prefixed UTF-8 byte run (#26).
260    out.extend_from_slice(&(frame.link_table.len() as u16).to_le_bytes());
261    for uri in &frame.link_table {
262        out.extend_from_slice(&(uri.len() as u16).to_le_bytes());
263        out.extend_from_slice(uri.as_bytes());
264    }
265    // Overlay section (#108): each group is a u16 count then that many
266    // `(row, left, right)` u16 viewport triples. Selection first, then search
267    // matches. Append-only, version-gated — a future group (markers, #118) adds
268    // a third count here at the next version bump.
269    encode_overlay_spans(&mut out, &frame.overlay.selection);
270    encode_overlay_spans(&mut out, &frame.overlay.matches);
271    // Third overlay group (#118): markers as `(id u32, row u16)` pairs — a
272    // different record shape from the span groups (a marker is a line anchor,
273    // not a column run). v10 (#159) appends a kind discriminant (u8, like
274    // `cursor_shape`), and — only for `CommandFinished` — a presence byte + i32
275    // exit code (the presence pattern mirrors the header's `scroll` option).
276    out.extend_from_slice(&(frame.overlay.markers.len() as u16).to_le_bytes());
277    for m in &frame.overlay.markers {
278        out.extend_from_slice(&m.id.0.to_le_bytes());
279        out.extend_from_slice(&(m.row as u16).to_le_bytes());
280        out.push(match m.kind {
281            MarkerKind::Plain => 0,
282            MarkerKind::PromptStart => 1,
283            MarkerKind::CommandStart => 2,
284            MarkerKind::OutputStart => 3,
285            MarkerKind::CommandFinished(_) => 4,
286        });
287        if let MarkerKind::CommandFinished(exit) = m.kind {
288            out.push(exit.is_some() as u8);
289            out.extend_from_slice(&exit.unwrap_or(0).to_le_bytes());
290        }
291    }
292    // Fourth overlay group (#120 S3, v11): every live marker's absolute buffer
293    // line as `(id u32, line u32)` pairs — a superset of the viewport marker group
294    // above, for placing overview-ruler marks off-viewport. Count-prefixed like the
295    // others.
296    out.extend_from_slice(&(frame.overlay.marker_lines.len() as u16).to_le_bytes());
297    for m in &frame.overlay.marker_lines {
298        out.extend_from_slice(&m.id.0.to_le_bytes());
299        out.extend_from_slice(&m.line.to_le_bytes());
300    }
301    // Fifth overlay group (#428, v12): the active search match's spans, same
302    // count + `(row, left, right)` shape as the selection/match groups. Appended
303    // at the tail so the section stays append-only.
304    encode_overlay_spans(&mut out, &frame.overlay.active_match);
305    out
306}
307
308/// Encode one overlay group: a u16 span count, then each span as three u16s
309/// (`row`, `left`, `right`) in viewport coordinates.
310fn encode_overlay_spans(out: &mut Vec<u8>, spans: &[SelectionSpan]) {
311    out.extend_from_slice(&(spans.len() as u16).to_le_bytes());
312    for s in spans {
313        out.extend_from_slice(&(s.row as u16).to_le_bytes());
314        out.extend_from_slice(&(s.left as u16).to_le_bytes());
315        out.extend_from_slice(&(s.right as u16).to_le_bytes());
316    }
317}
318
319/// Length in bytes of one fixed-width wire cell record (see
320/// [`encode_cell_record`]).
321pub const CELL_RECORD_LEN: usize = 18;
322
323/// Encode one [`Cell`] to its fixed 18-byte little-endian record:
324/// `c` u32 (Unicode scalar) · `fg` u32 · `bg` u32 · `flags` u16 · `extra` u16
325/// (frame-local grapheme index, 0 = none) · `link` u16 (frame-local hyperlink
326/// index, 0 = none). Width derives from `flags`.
327///
328/// `extra` and `link` are passed in rather than read from the cell: combining
329/// clusters (#45) and hyperlinks (#46) now live in per-row maps, so both indices
330/// ride on the [`Span`], not the cell. The wire bytes are unchanged.
331///
332/// This is the single definition of the cell record layout — [`encode`] writes
333/// it per span cell, and an alternate consumer (the WASM decoder, #34/ADR-0008)
334/// reuses it to lay decoded cells out flat without re-implementing the layout,
335/// so the two cannot drift.
336pub fn encode_cell_record(cell: &Cell, extra: u16, link: u16) -> [u8; CELL_RECORD_LEN] {
337    let mut r = [0u8; CELL_RECORD_LEN];
338    r[0..4].copy_from_slice(&(cell.c() as u32).to_le_bytes());
339    r[4..8].copy_from_slice(&encode_color(cell.fg()).to_le_bytes());
340    r[8..12].copy_from_slice(&encode_color(cell.bg()).to_le_bytes());
341    r[12..14].copy_from_slice(&cell.flags().bits().to_le_bytes());
342    r[14..16].copy_from_slice(&extra.to_le_bytes());
343    r[16..18].copy_from_slice(&link.to_le_bytes());
344    r
345}
346
347/// A colour reference as a tagged u32: high byte = tag
348/// (0 = Default, 1 = Indexed, 2 = Rgb), low 24 bits = payload. The tag is
349/// mandatory so `Default`, `Indexed(0)`, and `Rgb(0,0,0)` stay distinct.
350///
351/// Public so an alternate consumer (the WASM decoder's structure-of-arrays
352/// `fg`/`bg` columns, #35) reuses this single definition of the colour-ref
353/// encoding instead of re-implementing the tag packing — no drift.
354pub fn encode_color(c: Color) -> u32 {
355    match c {
356        Color::Default => 0,
357        Color::Indexed(i) => (1 << 24) | i as u32,
358        Color::Rgb(r, g, b) => (2 << 24) | (r as u32) << 16 | (g as u32) << 8 | b as u32,
359    }
360}
361
362/// Deserialize the binary wire format back into a [`Frame`].
363pub fn decode(bytes: &[u8]) -> Result<Frame, DecodeError> {
364    let mut r = Reader::new(bytes);
365    if r.take(2)? != MAGIC {
366        return Err(DecodeError::BadMagic);
367    }
368    let version = r.u8()?;
369    if version != VERSION {
370        return Err(DecodeError::BadVersion(version));
371    }
372    let has_scroll = r.u8()? != 0;
373    let kind = match r.u8()? {
374        0 => FrameKind::Full,
375        1 => FrameKind::Partial,
376        _ => return Err(DecodeError::BadTag),
377    };
378    let cols = r.u16()?;
379    let rows = r.u16()?;
380    let cursor_row = r.u16()?;
381    let cursor_col = r.u16()?;
382    let cursor_visible = r.u8()? != 0;
383    let cursor_shape = match r.u8()? {
384        0 => CursorShape::Block,
385        1 => CursorShape::Underline,
386        2 => CursorShape::Bar,
387        _ => return Err(DecodeError::BadTag),
388    };
389    let cursor_blink = r.u8()? != 0;
390    let display_offset = r.u32()?;
391    let scrollback_len = r.u32()?;
392    let mouse_events = MouseEvents::from_bits_retain(r.u8()?);
393    let alt_screen = r.u8()? != 0;
394    let scroll = if has_scroll {
395        let top = r.u16()? as usize;
396        let bottom = r.u16()? as usize;
397        let count = (r.u16()? as i16) as isize;
398        Some(ScrollOp { top, bottom, count })
399    } else {
400        None
401    };
402    let span_count = r.u16()?;
403    let mut spans = Vec::with_capacity(span_count as usize);
404    for _ in 0..span_count {
405        let line = r.u16()?;
406        let left = r.u16()?;
407        let right = r.u16()?;
408        if right < left {
409            return Err(DecodeError::BadSpan);
410        }
411        // Widen before the arithmetic: `right - left + 1` in `u16` overflows
412        // when `right == u16::MAX` (e.g. left=0, right=65535), panicking under
413        // overflow checks. `right >= left` is enforced just above, so the
414        // subtraction in `usize` cannot underflow.
415        let n = right as usize - left as usize + 1;
416        let mut cells = Vec::with_capacity(n);
417        let mut combining = BTreeMap::new();
418        let mut links = BTreeMap::new();
419        for col in 0..n {
420            let (cell, extra, link) = decode_cell(&mut r)?;
421            if let Some(idx) = NonZeroU32::new(extra as u32) {
422                combining.insert(col, idx);
423            }
424            if let Some(idx) = NonZeroU32::new(link as u32) {
425                links.insert(col, idx);
426            }
427            cells.push(cell);
428        }
429        spans.push(Span {
430            line,
431            left,
432            right,
433            cells,
434            combining,
435            links,
436        });
437    }
438    let side_table_count = r.u16()?;
439    let mut side_table = Vec::with_capacity(side_table_count as usize);
440    for _ in 0..side_table_count {
441        let len = r.u16()?;
442        let mut cluster = Vec::with_capacity(len as usize);
443        for _ in 0..len {
444            cluster.push(char::from_u32(r.u32()?).ok_or(DecodeError::BadTag)?);
445        }
446        side_table.push(cluster);
447    }
448    let link_count = r.u16()?;
449    let mut link_table = Vec::with_capacity(link_count as usize);
450    for _ in 0..link_count {
451        let len = r.u16()? as usize;
452        let bytes = r.take(len)?;
453        link_table.push(String::from_utf8_lossy(bytes).into_owned());
454    }
455    // Overlay section (#108): selection group then match group, each a count +
456    // `(row, left, right)` triples (inverse of `encode_overlay_spans`).
457    let selection = decode_overlay_spans(&mut r)?;
458    let matches = decode_overlay_spans(&mut r)?;
459    // Third group (#118): marker `(id u32, row u16)` records, each followed by a
460    // kind discriminant (v10, #159) and — for `CommandFinished` — a presence byte
461    // + i32 exit (inverse of the marker encode loop).
462    let marker_count = r.u16()?;
463    let mut markers = Vec::with_capacity(marker_count as usize);
464    for _ in 0..marker_count {
465        let id = MarkerId(r.u32()?);
466        let row = r.u16()? as usize;
467        let kind = match r.u8()? {
468            0 => MarkerKind::Plain,
469            1 => MarkerKind::PromptStart,
470            2 => MarkerKind::CommandStart,
471            3 => MarkerKind::OutputStart,
472            4 => {
473                // Always read presence + i32 (the encoder writes both); a 0
474                // presence means the exit bytes are padding to discard.
475                let present = r.u8()? != 0;
476                let exit = r.u32()? as i32;
477                MarkerKind::CommandFinished(present.then_some(exit))
478            }
479            _ => return Err(DecodeError::BadTag),
480        };
481        markers.push(MarkerPosition { id, row, kind });
482    }
483    // Fourth group (#120 S3, v11): every live marker's `(id u32, line u32)` — the
484    // absolute-line superset for the overview ruler (inverse of the encode loop).
485    let marker_line_count = r.u16()?;
486    let mut marker_lines = Vec::with_capacity(marker_line_count as usize);
487    for _ in 0..marker_line_count {
488        let id = MarkerId(r.u32()?);
489        let line = r.u32()?;
490        marker_lines.push(MarkerLine { id, line });
491    }
492    // Fifth group (#428, v12): the active search match's spans (inverse of the
493    // tail `encode_overlay_spans` call).
494    let active_match = decode_overlay_spans(&mut r)?;
495    let overlay = Overlay {
496        selection,
497        matches,
498        markers,
499        marker_lines,
500        active_match,
501    };
502    Ok(Frame {
503        cols,
504        rows,
505        kind,
506        cursor_row,
507        cursor_col,
508        cursor_visible,
509        cursor_shape,
510        cursor_blink,
511        display_offset,
512        scrollback_len,
513        mouse_events,
514        alt_screen,
515        scroll,
516        spans,
517        side_table,
518        link_table,
519        overlay,
520    })
521}
522
523/// Decode one overlay group: a u16 span count, then that many `(row, left,
524/// right)` u16 triples back into viewport [`SelectionSpan`]s (inverse of
525/// [`encode_overlay_spans`]).
526fn decode_overlay_spans(r: &mut Reader) -> Result<Vec<SelectionSpan>, DecodeError> {
527    let count = r.u16()?;
528    let mut spans = Vec::with_capacity(count as usize);
529    for _ in 0..count {
530        let row = r.u16()? as usize;
531        let left = r.u16()? as usize;
532        let right = r.u16()? as usize;
533        spans.push(SelectionSpan { row, left, right });
534    }
535    Ok(spans)
536}
537
538/// Decode one 18-byte cell record (inverse of [`encode_cell_record`]), returning
539/// the cell and its raw `extra` grapheme index and `link` index (0 = none). A
540/// non-zero index sets the corresponding presence bit; the caller records the
541/// indices on the span.
542fn decode_cell(r: &mut Reader) -> Result<(Cell, u16, u16), DecodeError> {
543    let c = char::from_u32(r.u32()?).ok_or(DecodeError::BadTag)?;
544    let fg = decode_color(r.u32()?)?;
545    let bg = decode_color(r.u32()?)?;
546    let flags = CellFlags::from_bits_retain(r.u16()?);
547    let extra = r.u16()?;
548    let link = r.u16()?;
549    let mut cell = Cell::from_parts(c, fg, bg, flags);
550    cell.set_combined(extra != 0);
551    cell.set_linked(link != 0);
552    Ok((cell, extra, link))
553}
554
555/// Decode a tagged-u32 colour reference (inverse of [`encode_color`]).
556fn decode_color(v: u32) -> Result<Color, DecodeError> {
557    let payload = v & 0x00FF_FFFF;
558    match v >> 24 {
559        0 => Ok(Color::Default),
560        1 => Ok(Color::Indexed(payload as u8)),
561        2 => Ok(Color::Rgb(
562            (payload >> 16) as u8,
563            (payload >> 8) as u8,
564            payload as u8,
565        )),
566        _ => Err(DecodeError::BadTag),
567    }
568}
569
570/// A little-endian cursor over the wire bytes.
571struct Reader<'a> {
572    bytes: &'a [u8],
573    pos: usize,
574}
575
576impl<'a> Reader<'a> {
577    fn new(bytes: &'a [u8]) -> Self {
578        Reader { bytes, pos: 0 }
579    }
580
581    fn take(&mut self, n: usize) -> Result<&'a [u8], DecodeError> {
582        let end = self.pos.checked_add(n).ok_or(DecodeError::Truncated)?;
583        let slice = self
584            .bytes
585            .get(self.pos..end)
586            .ok_or(DecodeError::Truncated)?;
587        self.pos = end;
588        Ok(slice)
589    }
590
591    fn u8(&mut self) -> Result<u8, DecodeError> {
592        Ok(self.take(1)?[0])
593    }
594
595    fn u16(&mut self) -> Result<u16, DecodeError> {
596        let b = self.take(2)?;
597        Ok(u16::from_le_bytes([b[0], b[1]]))
598    }
599
600    fn u32(&mut self) -> Result<u32, DecodeError> {
601        let b = self.take(4)?;
602        Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
603    }
604}