inkferro-core 0.1.0

Layout, text measurement, ANSI render, and frame-diff engine for inkferro — a Rust-backed, byte-for-byte drop-in for the ink terminal UI library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
//! Op-buffer decoder: flat byte buffer -> [`Vec<Op>`].
//!
//! This is the FFI wire format for M3: the JS reconciler (M3-G) emits a flat
//! `Buffer` of `[opcode, id, payload...]` records, napi (M3-D) hands the bytes
//! through here as `&[u8]`, and the result drives [`apply`](super::apply). This
//! module is the **decode** half only — Rust never emits this format at runtime
//! (JS is the sole emitter), so there is intentionally no `pub` encoder here. A
//! test-only encoder lives in the test submodule for round-tripping. The
//! cross-language contract M3-G's JS emitter targets is the wire-format table
//! documented below — there is no persisted byte artifact; the inline
//! literal-byte fixtures in the test submodule pin that table Rust-side.
//!
//! # Trust boundary
//!
//! The input is attacker-shaped (a JS `Buffer` of arbitrary bytes). Decoding
//! therefore **never panics**: every read is bounds-checked through [`Reader`]
//! and every malformed input returns a typed [`DecodeError`]. This is distinct
//! from [`apply`](super::apply), which is *total over semantics* (unknown ids
//! are silent no-ops, mirroring ink's JS guards). The decoder rejects malformed
//! *bytes*; `apply` tolerates malformed *meaning*. Keep the two boundaries
//! separate: a truncated buffer is a decode error, an op referencing a dead id
//! is not.
//!
//! # Wire format (v1) — the cross-language contract
//!
//! A buffer is a flat sequence of op records decoded until end-of-input. There
//! is no outer length/count prefix and no version byte; the buffer is exactly
//! the concatenation of `encode_op(op)` for each op in order. Mid-record
//! truncation yields [`DecodeError::UnexpectedEof`].
//!
//! ## Primitives
//!
//! * **u8**  — 1 byte. Used for opcodes, enum tags, and field ids.
//! * **u32** — 4 bytes, **little-endian**. Used for every node id and for
//!   string length prefixes.
//! * **f32** — 4 bytes, little-endian IEEE-754. Used for every `Style` float
//!   (`flex_grow`, `flex_shrink`, `aspect_ratio`, `gap`, `column_gap`,
//!   `row_gap`) and for the inner value of `Dim::Points`/`Dim::Percent`,
//!   `Lp::Points`/`Lp::Percent`.
//! * **f64** — 8 bytes, little-endian IEEE-754. Used for exactly one thing:
//!   `AttrValue::Number` (JS numbers are f64).
//! * **bool** — 1 byte: `0x00` = false, `0x01` = true. Any other value is
//!   [`DecodeError::InvalidBool`].
//! * **string** — a u32 length prefix (LE) followed by that many bytes of
//!   UTF-8. Invalid UTF-8 is [`DecodeError::InvalidUtf8`].
//!
//! ## Opcodes (record = `[opcode:u8][fields...]`)
//!
//! | opcode | variant       | fields after opcode                                |
//! |--------|---------------|----------------------------------------------------|
//! | `0x00` | Create        | `id:u32`, `kind:u8`                                 |
//! | `0x01` | AppendChild   | `parent:u32`, `child:u32`                          |
//! | `0x02` | InsertBefore  | `parent:u32`, `child:u32`, `before:u32`           |
//! | `0x03` | RemoveChild   | `parent:u32`, `child:u32`                          |
//! | `0x04` | SetText       | `id:u32`, `text:string`                            |
//! | `0x05` | SetStyle      | `id:u32`, `style` (see below)                      |
//! | `0x06` | SetAttribute  | `id:u32`, `key:string`, `value:AttrValue`         |
//! | `0x07` | SetTransform  | `id:u32`, `has:bool`                               |
//! | `0x08` | SetStatic     | `id:u32`, `value:bool`                            |
//! | `0x09` | Hide          | `id:u32`                                           |
//! | `0x0A` | Unhide        | `id:u32`                                           |
//! | `0x0B` | Free          | `id:u32`                                           |
//! | `0x0C` | SetTextStyle  | `id:u32`, `TextStyle` (see below)                  |
//! | `0x0D` | ClearTextStyle| `id:u32`                                           |
//!
//! Any other opcode is [`DecodeError::UnknownOpcode`].
//!
//! ## `TextStyle` — tagged field-id scheme (P5.1 SET_TEXT_STYLE)
//!
//! Same self-describing scheme as `Style`:
//!
//! ```text
//! [field_count:u32]  then field_count repetitions of:
//!   [field_id:u8][typed value for that field]
//! ```
//!
//! The decoder starts from `TextStyle::default()` and writes each decoded field.
//!
//! | id  | field            | value encoding |
//! |-----|------------------|----------------|
//! | `0` | color            | `string`       |
//! | `1` | background_color | `string`       |
//! | `2` | bold             | `bool`         |
//! | `3` | italic           | `bool`         |
//! | `4` | underline        | `bool`         |
//! | `5` | strikethrough    | `bool`         |
//! | `6` | inverse          | `bool`         |
//! | `7` | dim_color        | `bool`         |
//!
//! Any other field id is [`DecodeError::UnknownFieldId`].
//!
//! ## `Kind` tag (u8)
//!
//! `0x00` Root, `0x01` Box, `0x02` Text, `0x03` VirtualText. Other =
//! [`DecodeError::UnknownTag`].
//!
//! ## `AttrValue`  (`[tag:u8][payload]`)
//!
//! * `0x00` Bool — payload `bool` (1 byte).
//! * `0x01` Str  — payload `string`.
//! * `0x02` Number — payload `f64` (8 bytes, LE).
//!
//! ## `Style` — tagged field-id scheme
//!
//! `Style` has ~60 optional fields. Rather than make JS know the Rust struct
//! layout (a fixed 60-slot record), the style payload is **self-describing**:
//!
//! ```text
//! [field_count:u32]  then field_count repetitions of:
//!   [field_id:u8][typed value for that field]
//! ```
//!
//! Only fields that are `Some` (or, for the non-`Option` visual strings, set)
//! are emitted; the decoder starts from `Style::default()` and writes each
//! decoded field. A field id present in the buffer means the field is `Some`;
//! its absence means `None`. This was chosen over a positional fixed-layout
//! record because (1) it decouples the JS emitter from the exact Rust field
//! order and count — M3-G writes `[id][value]` pairs from the doc table alone,
//! never mirroring `struct Style`; (2) it is compact for the common sparse case
//! (a Box usually sets a handful of props); and (3) adding a future style field
//! is a backward-compatible new field-id, not a breaking width change.
//!
//! ### Style field ids and their value encodings
//!
//! | id   | field                 | value encoding                              |
//! |------|-----------------------|---------------------------------------------|
//! | `0`  | position              | `Position` tag (u8)                         |
//! | `1`  | top                   | `Dim`                                       |
//! | `2`  | right                 | `Dim`                                       |
//! | `3`  | bottom                | `Dim`                                       |
//! | `4`  | left                  | `Dim`                                       |
//! | `5`  | margin                | `Lp`                                        |
//! | `6`  | margin_x              | `Lp`                                        |
//! | `7`  | margin_y              | `Lp`                                        |
//! | `8`  | margin_top            | `Lp`                                        |
//! | `9`  | margin_right          | `Lp`                                        |
//! | `10` | margin_bottom         | `Lp`                                        |
//! | `11` | margin_left           | `Lp`                                        |
//! | `12` | padding               | `Lp`                                        |
//! | `13` | padding_x             | `Lp`                                        |
//! | `14` | padding_y             | `Lp`                                        |
//! | `15` | padding_top           | `Lp`                                        |
//! | `16` | padding_right         | `Lp`                                        |
//! | `17` | padding_bottom        | `Lp`                                        |
//! | `18` | padding_left          | `Lp`                                        |
//! | `19` | flex_direction        | `FlexDir` tag (u8)                         |
//! | `20` | flex_wrap             | `FlexWrap` tag (u8)                        |
//! | `21` | flex_grow             | `f32`                                       |
//! | `22` | flex_shrink           | `f32`                                       |
//! | `23` | flex_basis            | `Dim`                                       |
//! | `24` | align_items           | `Align` tag (u8)                           |
//! | `25` | align_self            | `Align` tag (u8)                           |
//! | `26` | align_content         | `ContentAlign` tag (u8)                    |
//! | `27` | justify_content       | `ContentAlign` tag (u8)                    |
//! | `28` | width                 | `Dim`                                       |
//! | `29` | height                | `Dim`                                       |
//! | `30` | min_width             | `Dim`                                       |
//! | `31` | min_height            | `Dim`                                       |
//! | `32` | max_width             | `Dim`                                       |
//! | `33` | max_height            | `Dim`                                       |
//! | `34` | aspect_ratio          | `f32`                                       |
//! | `35` | display               | `Display` tag (u8)                         |
//! | `36` | border_style          | `BorderStyle`                               |
//! | `37` | border_top            | `bool`                                      |
//! | `38` | border_right          | `bool`                                      |
//! | `39` | border_bottom         | `bool`                                      |
//! | `40` | border_left           | `bool`                                      |
//! | `41` | gap                   | `f32`                                       |
//! | `42` | column_gap            | `f32`                                       |
//! | `43` | row_gap               | `f32`                                       |
//! | `44` | text_wrap             | `TextWrap` tag (u8)                        |
//! | `45` | overflow_x            | `Overflow` tag (u8)                        |
//! | `46` | overflow_y            | `Overflow` tag (u8)                        |
//! | `47` | background_color      | `string`                                    |
//! | `48` | border_color          | `string`                                    |
//! | `49` | border_top_color      | `string`                                    |
//! | `50` | border_right_color    | `string`                                    |
//! | `51` | border_bottom_color   | `string`                                    |
//! | `52` | border_left_color     | `string`                                    |
//! | `53` | border_background_color        | `string`                           |
//! | `54` | border_top_background_color    | `string`                           |
//! | `55` | border_right_background_color  | `string`                           |
//! | `56` | border_bottom_background_color | `string`                           |
//! | `57` | border_left_background_color   | `string`                           |
//! | `58` | border_dim_color               | `bool`                             |
//! | `59` | border_top_dim_color           | `bool`                             |
//! | `60` | border_right_dim_color         | `bool`                             |
//! | `61` | border_bottom_dim_color        | `bool`                             |
//! | `62` | border_left_dim_color          | `bool`                             |
//!
//! Any other field id is [`DecodeError::UnknownFieldId`].
//!
//! ### Nested enum encodings
//!
//! * **`Dim`** — `[tag:u8]` then: `0x00` Points → `f32`; `0x01` Percent → `f32`;
//!   `0x02` Auto → (no payload).
//! * **`Lp`** — `[tag:u8]` then: `0x00` Points → `f32`; `0x01` Percent → `f32`.
//! * **`Position`** — `0x00` Relative, `0x01` Absolute, `0x02` Static.
//! * **`FlexDir`** — `0x00` Row, `0x01` Column, `0x02` RowReverse, `0x03`
//!   ColumnReverse.
//! * **`FlexWrap`** — `0x00` NoWrap, `0x01` Wrap, `0x02` WrapReverse.
//! * **`Align`** — `0x00` Stretch, `0x01` FlexStart, `0x02` Center, `0x03`
//!   FlexEnd, `0x04` Baseline.
//! * **`ContentAlign`** — `0x00` FlexStart, `0x01` Center, `0x02` FlexEnd,
//!   `0x03` SpaceBetween, `0x04` SpaceAround, `0x05` SpaceEvenly, `0x06`
//!   Stretch.
//! * **`Display`** — `0x00` Flex, `0x01` None.
//! * **`TextWrap`** — `0x00` Wrap, `0x01` Hard, `0x02` TruncateEnd, `0x03`
//!   TruncateMiddle, `0x04` TruncateStart.
//! * **`Overflow`** — `0x00` Visible, `0x01` Hidden.
//! * **`BorderStyle`** — `[tag:u8]` then: `0x00` Named → `string`; `0x01`
//!   Custom → eight `string`s in order `top_left, top, top_right, right,
//!   bottom_right, bottom, bottom_left, left`.
//!
//! Any out-of-range nested tag is [`DecodeError::UnknownTag`].

use super::node::{
    Align, AttrValue, BorderStyle, ContentAlign, Dim, Display, FlexDir, FlexWrap, Kind, Lp,
    Overflow, Position, Style, TextStyle, TextWrap,
};
use super::op::Op;

/// A typed decode failure. No variant is reachable by a *valid* buffer; every
/// one corresponds to a specific malformation at the FFI trust boundary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DecodeError {
    /// The buffer ended in the middle of a record/primitive. Carries the number
    /// of bytes that were still required.
    UnexpectedEof,
    /// An opcode byte that does not map to any [`Op`] variant.
    UnknownOpcode(u8),
    /// An enum tag byte (Kind, Dim, AttrValue, a Style sub-enum, …) out of
    /// range for its position.
    UnknownTag(u8),
    /// A `Style` field id with no assigned meaning.
    UnknownFieldId(u8),
    /// A `bool` byte that was neither `0x00` nor `0x01`.
    InvalidBool(u8),
    /// A length-prefixed string whose bytes were not valid UTF-8.
    InvalidUtf8,
}

impl core::fmt::Display for DecodeError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            DecodeError::UnexpectedEof => write!(f, "unexpected end of op buffer"),
            DecodeError::UnknownOpcode(b) => write!(f, "unknown opcode 0x{b:02X}"),
            DecodeError::UnknownTag(b) => write!(f, "unknown enum tag 0x{b:02X}"),
            DecodeError::UnknownFieldId(b) => write!(f, "unknown style field id {b}"),
            DecodeError::InvalidBool(b) => write!(f, "invalid bool byte 0x{b:02X}"),
            DecodeError::InvalidUtf8 => write!(f, "invalid utf-8 in length-prefixed string"),
        }
    }
}

impl std::error::Error for DecodeError {}

type Result<T> = core::result::Result<T, DecodeError>;

/// A bounds-checked cursor over the input bytes. Every primitive read goes
/// through one of these methods, so truncation anywhere is an `UnexpectedEof`
/// rather than a panic.
struct Reader<'a> {
    buf: &'a [u8],
    pos: usize,
}

impl<'a> Reader<'a> {
    fn new(buf: &'a [u8]) -> Self {
        Self { buf, pos: 0 }
    }

    fn at_end(&self) -> bool {
        self.pos >= self.buf.len()
    }

    fn take(&mut self, n: usize) -> Result<&'a [u8]> {
        let end = self.pos.checked_add(n).ok_or(DecodeError::UnexpectedEof)?;
        let slice = self
            .buf
            .get(self.pos..end)
            .ok_or(DecodeError::UnexpectedEof)?;
        self.pos = end;
        Ok(slice)
    }

    fn u8(&mut self) -> Result<u8> {
        Ok(self.take(1)?[0])
    }

    fn u32(&mut self) -> Result<u32> {
        let b = self.take(4)?;
        Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
    }

    fn f32(&mut self) -> Result<f32> {
        let b = self.take(4)?;
        Ok(f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
    }

    fn f64(&mut self) -> Result<f64> {
        let b = self.take(8)?;
        Ok(f64::from_le_bytes([
            b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
        ]))
    }

    fn bool(&mut self) -> Result<bool> {
        match self.u8()? {
            0 => Ok(false),
            1 => Ok(true),
            other => Err(DecodeError::InvalidBool(other)),
        }
    }

    fn string(&mut self) -> Result<String> {
        let len = self.u32()? as usize;
        let bytes = self.take(len)?;
        core::str::from_utf8(bytes)
            .map(str::to_owned)
            .map_err(|_| DecodeError::InvalidUtf8)
    }
}

/// Decode a flat op buffer into a [`Vec<Op>`].
///
/// The bytes are the cross-language wire format documented at the module level:
/// a sequence of `[opcode, id, payload]` records with no outer count, decoded
/// until end-of-input. Returns a typed [`DecodeError`] on any malformation; it
/// never panics, even on truncated or garbage input (FFI trust boundary).
///
/// # Errors
///
/// Returns [`DecodeError`] if the buffer is truncated mid-record
/// ([`DecodeError::UnexpectedEof`]), contains an unknown opcode, enum tag, or
/// style field id, an invalid bool byte, or invalid UTF-8 in a string.
pub fn decode_ops(buf: &[u8]) -> Result<Vec<Op>> {
    let mut r = Reader::new(buf);
    let mut ops = Vec::new();
    while !r.at_end() {
        ops.push(decode_op(&mut r)?);
    }
    Ok(ops)
}

fn decode_op(r: &mut Reader<'_>) -> Result<Op> {
    let opcode = r.u8()?;
    let op = match opcode {
        0x00 => Op::Create {
            id: r.u32()?,
            kind: decode_kind(r)?,
        },
        0x01 => Op::AppendChild {
            parent: r.u32()?,
            child: r.u32()?,
        },
        0x02 => Op::InsertBefore {
            parent: r.u32()?,
            child: r.u32()?,
            before: r.u32()?,
        },
        0x03 => Op::RemoveChild {
            parent: r.u32()?,
            child: r.u32()?,
        },
        0x04 => Op::SetText {
            id: r.u32()?,
            text: r.string()?,
        },
        0x05 => Op::SetStyle {
            id: r.u32()?,
            style: Box::new(decode_style(r)?),
        },
        0x06 => Op::SetAttribute {
            id: r.u32()?,
            key: r.string()?,
            value: decode_attr_value(r)?,
        },
        0x07 => Op::SetTransform {
            id: r.u32()?,
            has: r.bool()?,
        },
        0x08 => Op::SetStatic {
            id: r.u32()?,
            value: r.bool()?,
        },
        0x09 => Op::Hide { id: r.u32()? },
        0x0A => Op::Unhide { id: r.u32()? },
        0x0B => Op::Free { id: r.u32()? },
        0x0C => Op::SetTextStyle {
            id: r.u32()?,
            style: decode_text_style(r)?,
        },
        0x0D => Op::ClearTextStyle { id: r.u32()? },
        other => return Err(DecodeError::UnknownOpcode(other)),
    };
    Ok(op)
}

fn decode_kind(r: &mut Reader<'_>) -> Result<Kind> {
    match r.u8()? {
        0x00 => Ok(Kind::Root),
        0x01 => Ok(Kind::Box),
        0x02 => Ok(Kind::Text),
        0x03 => Ok(Kind::VirtualText),
        other => Err(DecodeError::UnknownTag(other)),
    }
}

fn decode_attr_value(r: &mut Reader<'_>) -> Result<AttrValue> {
    match r.u8()? {
        0x00 => Ok(AttrValue::Bool(r.bool()?)),
        0x01 => Ok(AttrValue::Str(r.string()?)),
        0x02 => Ok(AttrValue::Number(r.f64()?)),
        other => Err(DecodeError::UnknownTag(other)),
    }
}

fn decode_dim(r: &mut Reader<'_>) -> Result<Dim> {
    match r.u8()? {
        0x00 => Ok(Dim::Points(r.f32()?)),
        0x01 => Ok(Dim::Percent(r.f32()?)),
        0x02 => Ok(Dim::Auto),
        other => Err(DecodeError::UnknownTag(other)),
    }
}

fn decode_lp(r: &mut Reader<'_>) -> Result<Lp> {
    match r.u8()? {
        0x00 => Ok(Lp::Points(r.f32()?)),
        0x01 => Ok(Lp::Percent(r.f32()?)),
        other => Err(DecodeError::UnknownTag(other)),
    }
}

fn decode_position(r: &mut Reader<'_>) -> Result<Position> {
    match r.u8()? {
        0x00 => Ok(Position::Relative),
        0x01 => Ok(Position::Absolute),
        0x02 => Ok(Position::Static),
        other => Err(DecodeError::UnknownTag(other)),
    }
}

fn decode_flex_dir(r: &mut Reader<'_>) -> Result<FlexDir> {
    match r.u8()? {
        0x00 => Ok(FlexDir::Row),
        0x01 => Ok(FlexDir::Column),
        0x02 => Ok(FlexDir::RowReverse),
        0x03 => Ok(FlexDir::ColumnReverse),
        other => Err(DecodeError::UnknownTag(other)),
    }
}

fn decode_flex_wrap(r: &mut Reader<'_>) -> Result<FlexWrap> {
    match r.u8()? {
        0x00 => Ok(FlexWrap::NoWrap),
        0x01 => Ok(FlexWrap::Wrap),
        0x02 => Ok(FlexWrap::WrapReverse),
        other => Err(DecodeError::UnknownTag(other)),
    }
}

fn decode_align(r: &mut Reader<'_>) -> Result<Align> {
    match r.u8()? {
        0x00 => Ok(Align::Stretch),
        0x01 => Ok(Align::FlexStart),
        0x02 => Ok(Align::Center),
        0x03 => Ok(Align::FlexEnd),
        0x04 => Ok(Align::Baseline),
        other => Err(DecodeError::UnknownTag(other)),
    }
}

fn decode_content_align(r: &mut Reader<'_>) -> Result<ContentAlign> {
    match r.u8()? {
        0x00 => Ok(ContentAlign::FlexStart),
        0x01 => Ok(ContentAlign::Center),
        0x02 => Ok(ContentAlign::FlexEnd),
        0x03 => Ok(ContentAlign::SpaceBetween),
        0x04 => Ok(ContentAlign::SpaceAround),
        0x05 => Ok(ContentAlign::SpaceEvenly),
        0x06 => Ok(ContentAlign::Stretch),
        other => Err(DecodeError::UnknownTag(other)),
    }
}

fn decode_display(r: &mut Reader<'_>) -> Result<Display> {
    match r.u8()? {
        0x00 => Ok(Display::Flex),
        0x01 => Ok(Display::None),
        other => Err(DecodeError::UnknownTag(other)),
    }
}

fn decode_text_wrap(r: &mut Reader<'_>) -> Result<TextWrap> {
    match r.u8()? {
        0x00 => Ok(TextWrap::Wrap),
        0x01 => Ok(TextWrap::Hard),
        0x02 => Ok(TextWrap::TruncateEnd),
        0x03 => Ok(TextWrap::TruncateMiddle),
        0x04 => Ok(TextWrap::TruncateStart),
        other => Err(DecodeError::UnknownTag(other)),
    }
}

fn decode_overflow(r: &mut Reader<'_>) -> Result<Overflow> {
    match r.u8()? {
        0x00 => Ok(Overflow::Visible),
        0x01 => Ok(Overflow::Hidden),
        other => Err(DecodeError::UnknownTag(other)),
    }
}

fn decode_border_style(r: &mut Reader<'_>) -> Result<BorderStyle> {
    match r.u8()? {
        0x00 => Ok(BorderStyle::Named(r.string()?)),
        0x01 => Ok(BorderStyle::Custom {
            top_left: r.string()?,
            top: r.string()?,
            top_right: r.string()?,
            right: r.string()?,
            bottom_right: r.string()?,
            bottom: r.string()?,
            bottom_left: r.string()?,
            left: r.string()?,
        }),
        other => Err(DecodeError::UnknownTag(other)),
    }
}

fn decode_style(r: &mut Reader<'_>) -> Result<Style> {
    let mut style = Style::default();
    let field_count = r.u32()?;
    for _ in 0..field_count {
        let field_id = r.u8()?;
        match field_id {
            0 => style.position = Some(decode_position(r)?),
            1 => style.top = Some(decode_dim(r)?),
            2 => style.right = Some(decode_dim(r)?),
            3 => style.bottom = Some(decode_dim(r)?),
            4 => style.left = Some(decode_dim(r)?),
            5 => style.margin = Some(decode_lp(r)?),
            6 => style.margin_x = Some(decode_lp(r)?),
            7 => style.margin_y = Some(decode_lp(r)?),
            8 => style.margin_top = Some(decode_lp(r)?),
            9 => style.margin_right = Some(decode_lp(r)?),
            10 => style.margin_bottom = Some(decode_lp(r)?),
            11 => style.margin_left = Some(decode_lp(r)?),
            12 => style.padding = Some(decode_lp(r)?),
            13 => style.padding_x = Some(decode_lp(r)?),
            14 => style.padding_y = Some(decode_lp(r)?),
            15 => style.padding_top = Some(decode_lp(r)?),
            16 => style.padding_right = Some(decode_lp(r)?),
            17 => style.padding_bottom = Some(decode_lp(r)?),
            18 => style.padding_left = Some(decode_lp(r)?),
            19 => style.flex_direction = Some(decode_flex_dir(r)?),
            20 => style.flex_wrap = Some(decode_flex_wrap(r)?),
            21 => style.flex_grow = Some(r.f32()?),
            22 => style.flex_shrink = Some(r.f32()?),
            23 => style.flex_basis = Some(decode_dim(r)?),
            24 => style.align_items = Some(decode_align(r)?),
            25 => style.align_self = Some(decode_align(r)?),
            26 => style.align_content = Some(decode_content_align(r)?),
            27 => style.justify_content = Some(decode_content_align(r)?),
            28 => style.width = Some(decode_dim(r)?),
            29 => style.height = Some(decode_dim(r)?),
            30 => style.min_width = Some(decode_dim(r)?),
            31 => style.min_height = Some(decode_dim(r)?),
            32 => style.max_width = Some(decode_dim(r)?),
            33 => style.max_height = Some(decode_dim(r)?),
            34 => style.aspect_ratio = Some(r.f32()?),
            35 => style.display = Some(decode_display(r)?),
            36 => style.border_style = Some(decode_border_style(r)?),
            37 => style.border_top = Some(r.bool()?),
            38 => style.border_right = Some(r.bool()?),
            39 => style.border_bottom = Some(r.bool()?),
            40 => style.border_left = Some(r.bool()?),
            41 => style.gap = Some(r.f32()?),
            42 => style.column_gap = Some(r.f32()?),
            43 => style.row_gap = Some(r.f32()?),
            44 => style.text_wrap = Some(decode_text_wrap(r)?),
            45 => style.overflow_x = Some(decode_overflow(r)?),
            46 => style.overflow_y = Some(decode_overflow(r)?),
            47 => style.background_color = Some(r.string()?),
            48 => style.border_color = Some(r.string()?),
            49 => style.border_top_color = Some(r.string()?),
            50 => style.border_right_color = Some(r.string()?),
            51 => style.border_bottom_color = Some(r.string()?),
            52 => style.border_left_color = Some(r.string()?),
            53 => style.border_background_color = Some(r.string()?),
            54 => style.border_top_background_color = Some(r.string()?),
            55 => style.border_right_background_color = Some(r.string()?),
            56 => style.border_bottom_background_color = Some(r.string()?),
            57 => style.border_left_background_color = Some(r.string()?),
            58 => style.border_dim_color = Some(r.bool()?),
            59 => style.border_top_dim_color = Some(r.bool()?),
            60 => style.border_right_dim_color = Some(r.bool()?),
            61 => style.border_bottom_dim_color = Some(r.bool()?),
            62 => style.border_left_dim_color = Some(r.bool()?),
            other => return Err(DecodeError::UnknownFieldId(other)),
        }
    }
    Ok(style)
}

/// Decode a `TextStyle` (P5.1 SET_TEXT_STYLE) from the self-describing tagged
/// field-id scheme.  Mirrors [`decode_style`]: start from default, write each
/// decoded field.  The render walk reads the stored `text_styling` via
/// `resolve_transform` for the native simple-`<Text>` path (P5.1b); a later
/// `ClearTextStyle` (0x0D) resets it to `None` on a styled→plain rerender.
fn decode_text_style(r: &mut Reader<'_>) -> Result<TextStyle> {
    let mut style = TextStyle::default();
    let field_count = r.u32()?;
    for _ in 0..field_count {
        let field_id = r.u8()?;
        match field_id {
            0 => style.color = Some(r.string()?),
            1 => style.background_color = Some(r.string()?),
            2 => style.bold = r.bool()?,
            3 => style.italic = r.bool()?,
            4 => style.underline = r.bool()?,
            5 => style.strikethrough = r.bool()?,
            6 => style.inverse = r.bool()?,
            7 => style.dim_color = r.bool()?,
            other => return Err(DecodeError::UnknownFieldId(other)),
        }
    }
    Ok(style)
}

#[cfg(test)]
#[path = "decode_tests.rs"]
mod decode_tests;