libtracer 0.12.0

Rust binding for libtracer — a lightweight decentralized graph-based networking protocol.
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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright 2026 avatarsd LLC

/*!
 * @brief libtracer core wire codec — a from-scratch, native Rust port of the C++
 * reference codec in `core/src/frame.cpp` and the TypeScript core in
 * `bindings/typescript/src/codec.mjs`. It must match both byte-for-byte;
 * correctness is gated by the SHARED conformance vectors under
 * `tests/conformance/vectors/v1/` and the cross-core differential fuzzer
 * (`tests/conformance/diff_fuzz.py`).
 *
 * The wire format is documented in `docs/reference/01-data-format.md` and pinned
 * normatively by `docs/spec/v1.md`:
 *
 *   header (4 or 6 bytes) + payload + optional trailer (timestamp then CRC).
 *
 * This is a third, fully independent implementation (no FFI over C++,
 * per ADR-0028) — it compiles `#![no_std]` (it only needs `alloc` for the owned
 * TLV tree) so it can target WASM and bare-metal MCUs.
 */

#![no_std]
// Documentation coverage is a build gate, mirroring the C++ Doxygen WARN_AS_ERROR
// gate (core/Doxyfile / docs.yml): every public item MUST carry a rustdoc comment.
#![deny(missing_docs)]

extern crate alloc;

use alloc::vec::Vec;

// ---------------------------------------------------------------- typed tier ---
// The typed protocol layer built on top of the raw wire codec below. Each module
// produces / parses the exact bytes the shared conformance vectors pin, matching
// the C++ core and the TypeScript client byte-for-byte. See each module's docs.

pub mod error_registry;
pub mod field;
pub mod fwd;
pub mod path;
pub mod structured;
pub mod tlv_builders;

pub use error_registry::{
    error_code, error_raw_code, error_string, parse_error, status_errors, status_ok,
    status_with_errors, Disposition, ErrCode, ErrorId, ParsedError, Severity,
};
pub use field::{
    encode_field, field_tlv, parse_field, parse_field_tlv, FieldLevel, FieldMode, MAX_FIELD_DEPTH,
};
pub use fwd::{
    decode_fwd, encode_fwd, encode_fwd_bytes, parse_fwd_tlv, reply_error_code, reply_error_path,
    FieldSel, FwdRequest, ParsedFwd,
};
pub use tlv_builders::{
    name, path_ref, path_ref_element, subscriber, text_name, validate_segment, value, value_opts,
    value_u16, value_u32, value_u64, value_u8, BuildError, PathRefElement, ValueOptions,
    MAX_PATH_BYTES, MAX_SEGMENTS, MAX_SEGMENT_BYTES,
};

/**
 * @brief Core type-code registry (0x01-0x10). 0x05 is retired (was LIST, ADR-0003).
 * The codec treats every nonzero type generically, so these constants are a
 * convenience, not an exhaustive set — with one exception: 0x14 PATH_REF (RFC-0024 §4)
 * carries a bare fixed-stride 8-byte record array rather than a self-describing body, so
 * the decoder checks its shape by type.
 */
pub mod type_code {
    /** @brief Opaque scalar value. */
    pub const VALUE: u8 = 0x01;
    /** @brief UTF-8 name segment. */
    pub const NAME: u8 = 0x02;
    /** @brief Human-readable description. */
    pub const DESCRIPTION: u8 = 0x03;
    /** @brief Subscriber registration. */
    pub const SUBSCRIBER: u8 = 0x04;
    /** @brief Structured path (sequence of NAME children). */
    pub const PATH: u8 = 0x06;
    /** @brief Point in a path/graph. */
    pub const POINT: u8 = 0x07;
    /** @brief Error report. */
    pub const ERROR: u8 = 0x08;
    /** @brief Status report. */
    pub const STATUS: u8 = 0x09;
    /** @brief Access-control list. */
    pub const ACL: u8 = 0x0a;
    /** @brief QoS settings. */
    pub const SETTINGS: u8 = 0x0b;
    /** @brief Time. */
    pub const TIME: u8 = 0x0c;
    /** @brief Router-wrapped frame. */
    pub const ROUTER: u8 = 0x0d;
    /** @brief In-band vertex-creation spec (structured; opt.PL=1). */
    pub const SPEC: u8 = 0x0e;
    /** @brief Remote-operation forward frame (structured; RFC-0004 §B / ADR-0035). */
    pub const FWD: u8 = 0x0f;
    /** @brief Control-plane `:field` selector (structured; RFC-0004 §C / ADR-0035). */
    pub const FIELD: u8 = 0x10;
    /** @brief Bound path: a bare array of 8-byte node-scoped vertex refs (RFC-0024 §4). */
    pub const PATH_REF: u8 = 0x14;
    /**
     * @brief The REVERSE-direction bound path a mint-flagged request accumulates
     * (RFC-0024 §7.1 amendment 2) — `PATH_REF`'s body grammar exactly, a different role.
     *
     * A distinct code rather than "the only trailing child": every other element of this
     * grammar self-describes by type, and a positional rule mis-reads a mint-flagged WRITE
     * whose payload is itself a raw `PATH_REF`.
     */
    pub const PATH_REF_REVERSE: u8 = 0x15;
}

/**
 * @brief True for either bound-path code — the two types whose body is a fixed-stride 8-byte
 * element array rather than a self-describing payload (RFC-0024 §4.2).
 *
 * `0x15` sits adjacent to `0x14` so this stays one masked compare on the per-TLV parse path.
 */
pub const fn is_path_ref_type(type_b: u8) -> bool {
    type_b & 0xFE == type_code::PATH_REF
}

/**
 * @brief The `PATH_REF` element stride — 8 bytes, `(u32 index, u32 generation)` LE
 * (RFC-0024 §4.4).
 */
pub const PATH_REF_ELEMENT_BYTES: usize = 8;

/**
 * @brief The `PATH_REF` element-count bound — 255 elements / 2040 body bytes (RFC-0024 §4.3).
 */
pub const MAX_PATH_REF_ELEMENTS: usize = 255;

/**
 * @brief The purely STRUCTURAL `PATH_REF` rules of RFC-0024 §4.2/§4.3 — the grammar's only
 * per-type check, and the ONE home of it in this crate: both [`decode`] and [`encode`] call
 * this rather than spelling the four clauses twice.
 *
 * A `PATH_REF` header that fails this is [`Error::FrameInvalid`], exactly as a set reserved
 * bit is. All four clauses are shape, not meaning — what an element MEANS is node-scoped, so
 * no codec can validate one:
 *
 * - **`opt.PL` MUST be 0** — the body is a fixed-stride record array, not child TLVs; a
 *   generic `PL = 1` walker would read the first four body bytes as a TLV header and
 *   mis-frame the whole body.
 * - **`opt.LL` MUST be 0** — the u32 length width buys nothing under a 2040-byte cap, so it
 *   is forbidden rather than merely unused.
 * - **`length % 8 == 0`** — a body that is not a whole number of elements has no reading,
 *   because the element count is not on the wire at all: it IS `length / 8`.
 * - **`length <= 2040`** — the §4.3 element-count bound, in bytes.
 *
 * @p body_len is a `u64` because [`parse_one`] holds the wire length as one, before any
 * `usize` narrowing; [`encode`] widens its `payload.len()`, which is lossless everywhere.
 */
fn path_ref_body_valid(pl: bool, ll: bool, body_len: u64) -> bool {
    !pl && !ll
        && body_len.is_multiple_of(PATH_REF_ELEMENT_BYTES as u64)
        && body_len <= (MAX_PATH_REF_ELEMENTS * PATH_REF_ELEMENT_BYTES) as u64
}

/** @brief Reserved bits 7 and 0; a set reserved bit makes a frame invalid. */
const RESERVED_MASK: u8 = 0b1000_0001;

/**
 * @brief A decode failure. Names mirror the C++ `tr::wire::error_t` enum and the TS
 * `ERROR` codes so the conformance harness can emit identical `ERR:<reason>` text.
 */
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Error {
    /** @brief Ran out of bytes (header/payload/trailer truncated). */
    FrameTruncated,
    /** @brief Reserved bit set, type code 0x00, or trailing bytes after the root TLV. */
    FrameInvalid,
    /** @brief Trailer CRC did not match the recomputed value. */
    FrameCrcFail,
    /**
     * @brief Nesting exceeded the receiver's decode resources (RFC-0006 —
     * depth is resource-bounded, never a constant).
     *
     * This binding's [`decode`] keeps its work stack in a growable `Vec` (the
     * host heap is its resource), so it never produces this itself; the name
     * remains for harness parity and for peers' `ERROR` frames.
     */
    TlvNestingTooDeep,
}

impl Error {
    /** @brief The stable wire name used by the conformance harness (`ERR:<name>`). */
    pub const fn name(self) -> &'static str {
        match self {
            Error::FrameTruncated => "FRAME_TRUNCATED",
            Error::FrameInvalid => "FRAME_INVALID",
            Error::FrameCrcFail => "FRAME_CRC_FAIL",
            Error::TlvNestingTooDeep => "TLV_NESTING_TOO_DEEP",
        }
    }
}

/** @brief The 1-byte `opt` field, unpacked. Bits MSB->LSB: R | PL | TS | CR | LL | CW | TF | R. */
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Opt {
    /** @brief bit 6: payload is structured (children, not opaque bytes). */
    pub pl: bool,
    /** @brief bit 5: trailer carries a timestamp. */
    pub ts: bool,
    /** @brief bit 4: trailer carries a CRC. */
    pub cr: bool,
    /** @brief bit 3: length width (false = u16, true = u32). */
    pub ll: bool,
    /** @brief bit 2: CRC width (false = CRC-32C, true = CRC-16-CCITT). */
    pub cw: bool,
    /** @brief bit 1: timestamp form (false = absolute u64, true = relative i32). */
    pub tf: bool,
}

impl Opt {
    /** @brief Unpack the raw `opt` byte (ignores reserved bits, which are checked separately). */
    pub const fn decode(b: u8) -> Opt {
        Opt {
            pl: b & 0x40 != 0,
            ts: b & 0x20 != 0,
            cr: b & 0x10 != 0,
            ll: b & 0x08 != 0,
            cw: b & 0x04 != 0,
            tf: b & 0x02 != 0,
        }
    }

    /** @brief Pack back into the raw `opt` byte (reserved bits always zero). */
    pub const fn encode(self) -> u8 {
        (if self.pl { 0x40 } else { 0 })
            | (if self.ts { 0x20 } else { 0 })
            | (if self.cr { 0x10 } else { 0 })
            | (if self.ll { 0x08 } else { 0 })
            | (if self.cw { 0x04 } else { 0 })
            | (if self.tf { 0x02 } else { 0 })
    }
}

/**
 * @brief A decoded wire timestamp. Absolute form is a u64 ns count since the Unix epoch;
 * relative form is a signed i32 ns offset. `value` holds the bit pattern as an
 * `i64` (absolute = the u64 reinterpreted) to round-trip the full range exactly.
 */
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Timestamp {
    /** @brief false = absolute u64 ns; true = relative i32 ns. */
    pub relative: bool,
    /** @brief ns; for the absolute form this is the u64 value reinterpreted as i64. */
    pub value: i64,
}

/** @brief The trailer CRC width. */
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CrcWidth {
    /** @brief CRC-32C (Castagnoli). */
    Crc32c,
    /** @brief CRC-16-CCITT (FALSE). */
    Crc16Ccitt,
}

/** @brief A decoded CRC. 16-bit values are zero-extended into `value`. */
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Crc {
    /** @brief Which CRC the trailer carried. */
    pub width: CrcWidth,
    /** @brief The CRC value (16-bit values zero-extended). */
    pub value: u32,
}

/** @brief A decoded trailer: an optional timestamp followed by an optional CRC. */
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Trailer {
    /** @brief Present iff opt.TS. */
    pub ts: Option<Timestamp>,
    /** @brief Present iff opt.CR. */
    pub crc: Option<Crc>,
}

/**
 * @brief A decoded TLV. For opaque TLVs (opt.PL=0) `payload` holds the bytes and
 * `children` is empty; for structured TLVs (opt.PL=1) `children` holds the parsed
 * sub-TLVs and `payload` is empty.
 */
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Tlv {
    /** @brief A [`type_code`] value (or a user/unknown nonzero code). */
    pub type_code: u8,
    /** @brief The unpacked option bits. */
    pub opt: Opt,
    /** @brief Opaque payload bytes (empty when `opt.pl`). */
    pub payload: Vec<u8>,
    /** @brief Parsed sub-TLVs (empty unless `opt.pl`). */
    pub children: Vec<Tlv>,
    /** @brief Optional trailer (present iff `opt.ts || opt.cr`). */
    pub trailer: Option<Trailer>,
}

/* ------------------------------------------------------------------ crc --- */

/** @brief CRC-32C (Castagnoli): reflected poly 0x82F63B78, init/xor 0xFFFFFFFF. */
pub fn crc32c(data: &[u8]) -> u32 {
    let mut c: u32 = 0xFFFF_FFFF;
    for &b in data {
        let mut x = (c ^ b as u32) & 0xFF;
        for _ in 0..8 {
            x = if x & 1 != 0 {
                0x82F6_3B78 ^ (x >> 1)
            } else {
                x >> 1
            };
        }
        c = x ^ (c >> 8);
    }
    c ^ 0xFFFF_FFFF
}

/** @brief CRC-16-CCITT (FALSE): poly 0x1021, MSB-first, init 0xFFFF, no final xor. */
pub fn crc16_ccitt(data: &[u8]) -> u16 {
    let mut c: u16 = 0xFFFF;
    for &b in data {
        let idx = (((c >> 8) as u8) ^ b) as u16;
        let mut t = idx << 8;
        for _ in 0..8 {
            t = if t & 0x8000 != 0 {
                (t << 1) ^ 0x1021
            } else {
                t << 1
            };
        }
        c = t ^ (c << 8);
    }
    c
}

/* --------------------------------------------------------------- endian --- */

/** @brief Read `n` (<= 8) little-endian bytes at `off` as an unsigned `u64`. */
fn read_le(b: &[u8], off: usize, n: usize) -> u64 {
    let mut v: u64 = 0;
    let mut i = 0;
    while i < n {
        v |= (b[off + i] as u64) << (8 * i);
        i += 1;
    }
    v
}

/** @brief Append `n` (<= 8) little-endian bytes of unsigned `v`. */
fn write_le(out: &mut Vec<u8>, v: u64, n: usize) {
    let mut i = 0;
    while i < n {
        out.push(((v >> (8 * i)) & 0xFF) as u8);
        i += 1;
    }
}

/* --------------------------------------------------------------- decode --- */

/**
 * @brief One TLV parsed in isolation — NO recursion into children. Mirrors `parse_one`
 * in `frame.cpp`. For a structured TLV (`opt.pl`) the returned slice is the PL
 * payload region, left for [`decode`] to walk iteratively; for an opaque TLV the
 * bytes are copied into `tlv.payload` and the slice is empty. The returned
 * `usize` is the full encoded size (header + length + trailer).
 */
fn parse_one(buf: &[u8]) -> Result<(Tlv, usize, &[u8]), Error> {
    if buf.len() < 4 {
        return Err(Error::FrameTruncated);
    }
    let type_b = buf[0];
    let opt_b = buf[1];
    if type_b == 0x00 {
        return Err(Error::FrameInvalid);
    }
    if opt_b & RESERVED_MASK != 0 {
        return Err(Error::FrameInvalid);
    }

    let opt = Opt::decode(opt_b);
    let header = if opt.ll { 6 } else { 4 };
    if buf.len() < header {
        return Err(Error::FrameTruncated);
    }

    let length = read_le(buf, 2, if opt.ll { 4 } else { 2 });
    // The one per-type structural rule (RFC-0024 §4.2/§4.3), through the single predicate
    // `encode` now shares — see `path_ref_body_valid` for the four clauses and why they are
    // shape rather than meaning.
    if is_path_ref_type(type_b) && !path_ref_body_valid(opt.pl, opt.ll, length) {
        return Err(Error::FrameInvalid);
    }
    let ts_size = if opt.ts {
        if opt.tf {
            4u64
        } else {
            8u64
        }
    } else {
        0
    };
    let crc_size = if opt.cr {
        if opt.cw {
            2u64
        } else {
            4u64
        }
    } else {
        0
    };
    // u64 math: `length` is at most a u32, so this sum can never overflow u64 and
    // an over-long length on a short buffer fails the bounds check below rather
    // than wrapping into an out-of-bounds slice.
    let total = header as u64 + length + ts_size + crc_size;
    if (buf.len() as u64) < total {
        return Err(Error::FrameTruncated);
    }
    let length = length as usize;
    let ts_size = ts_size as usize;
    let total = total as usize;

    let mut tlv = Tlv {
        type_code: type_b,
        opt,
        ..Tlv::default()
    };

    let payload = &buf[header..header + length];

    if opt.ts || opt.cr {
        let mut trailer = Trailer::default();
        if opt.ts {
            let value = if opt.tf {
                (read_le(buf, header + length, 4) as u32) as i32 as i64
            } else {
                read_le(buf, header + length, 8) as i64
            };
            trailer.ts = Some(Timestamp {
                relative: opt.tf,
                value,
            });
        }
        if opt.cr {
            // The CRC covers the payload bytes followed by the timestamp bytes
            // (NOT the header); they are contiguous in `buf`.
            let covered = &buf[header..header + length + ts_size];
            let crc_off = header + length + ts_size;
            if opt.cw {
                let value = read_le(buf, crc_off, 2) as u16;
                if crc16_ccitt(covered) != value {
                    return Err(Error::FrameCrcFail);
                }
                trailer.crc = Some(Crc {
                    width: CrcWidth::Crc16Ccitt,
                    value: value as u32,
                });
            } else {
                let value = read_le(buf, crc_off, 4) as u32;
                if crc32c(covered) != value {
                    return Err(Error::FrameCrcFail);
                }
                trailer.crc = Some(Crc {
                    width: CrcWidth::Crc32c,
                    value,
                });
            }
        }
        tlv.trailer = Some(trailer);
    }

    let children: &[u8] = if opt.pl {
        payload // walked iteratively by decode(), not here
    } else {
        tlv.payload.extend_from_slice(payload);
        &[]
    };
    Ok((tlv, total, children))
}

/**
 * @brief An open structured node whose children are still being parsed. `pos` is the
 * cursor within `payload`; `total` advances the parent's cursor when it closes.
 */
struct Open<'a> {
    node: Tlv,
    payload: &'a [u8],
    pos: usize,
    total: usize,
}

/**
 * @brief Decode exactly one TLV that fills `input` into a TLV tree.
 *
 * Nesting is parsed ITERATIVELY with an explicit stack (recursion is forbidden
 * so a maliciously deep frame cannot overflow a small MCU call stack); the
 * stack is a growable `Vec`, so nesting depth is bounded only by this
 * receiver's memory (RFC-0006 — no depth constant). Trailing bytes after the
 * root make the frame [`Error::FrameInvalid`].
 */
pub fn decode(input: &[u8]) -> Result<Tlv, Error> {
    let (root_node, root_total, root_children) = parse_one(input)?;
    if root_total != input.len() {
        return Err(Error::FrameInvalid); // trailing bytes
    }
    if !root_node.opt.pl {
        return Ok(root_node); // opaque root: done
    }

    let mut stack: Vec<Open> = Vec::new();
    stack.push(Open {
        node: root_node,
        payload: root_children,
        pos: 0,
        total: root_total,
    });

    loop {
        let top = stack.last().unwrap();
        if top.pos == top.payload.len() {
            // Node complete — pop and graft onto its parent (or return if root).
            let done = stack.pop().unwrap();
            match stack.last_mut() {
                None => return Ok(done.node),
                Some(parent) => {
                    parent.pos += done.total;
                    parent.node.children.push(done.node);
                }
            }
            continue;
        }
        // Copy out the slice/cursor before mutating the stack (the returned refs
        // borrow `input`, not the stack).
        let (payload, pos) = {
            let top = stack.last().unwrap();
            (top.payload, top.pos)
        };
        let (child_node, child_total, child_children) = parse_one(&payload[pos..])?;
        if child_node.opt.pl {
            stack.push(Open {
                node: child_node,
                payload: child_children,
                pos: 0,
                total: child_total,
            });
        } else {
            let parent = stack.last_mut().unwrap();
            parent.pos += child_total;
            parent.node.children.push(child_node);
        }
    }
}

/* --------------------------------------------------------------- encode --- */

/**
 * @brief Encode a TLV tree back to wire bytes, recomputing the trailer CRC from the body
 * (+ timestamp bytes) when `opt.cr` is set. Mirrors `encode` in `frame.cpp`.
 *
 * Encoding is SYMMETRIC with [`decode`]: the grammar's one per-type structural rule — a
 * `PATH_REF` body is a fixed-stride 8-byte record array, so `opt.PL` and `opt.LL` are both
 * forbidden and the length is a bounded multiple of 8 (RFC-0024 §4.2/§4.3) — is applied here
 * through the same [`path_ref_body_valid`] the decoder calls, so this core cannot mint a
 * frame it would itself answer with [`Error::FrameInvalid`] (#1004; the C++ core closed the
 * same asymmetry in #886). The guarded [`path_ref`] builder satisfies the rule by
 * construction, so the door this closes is a [`Tlv`] built by struct literal — [`Tlv`]'s
 * fields are public, which is the ordinary way to build one here.
 *
 * # Postcondition
 * This function has no error channel, so refusal is spelled **emits nothing**: an ill-formed
 * `PATH_REF` anywhere in the tree makes the whole call return an EMPTY `Vec`. A refused TLV
 * refuses its ancestors rather than being dropped into a frame that DOES decode, one
 * component short. Empty is unambiguous — an accepted TLV always carries at least its 4-byte
 * header, so no well-formed tree encodes to nothing. Well-formed input is untouched and
 * stays byte-identical to what it produced before.
 */
pub fn encode(tlv: &Tlv) -> Vec<u8> {
    // A PATH_REF body is never structured, so `payload` IS the body length here: an `opt.pl`
    // PATH_REF fails the PL clause before the children branch below ever runs.
    if is_path_ref_type(tlv.type_code)
        && !path_ref_body_valid(tlv.opt.pl, tlv.opt.ll, tlv.payload.len() as u64)
    {
        return Vec::new();
    }

    let mut body: Vec<u8> = Vec::new();
    if tlv.opt.pl {
        for child in &tlv.children {
            let cb = encode(child);
            // A refused child refuses the parent (see the postcondition above).
            if cb.is_empty() {
                return Vec::new();
            }
            body.extend_from_slice(&cb);
        }
    } else {
        body.extend_from_slice(&tlv.payload);
    }

    let mut out: Vec<u8> = Vec::new();
    out.push(tlv.type_code);
    out.push(tlv.opt.encode());
    write_le(&mut out, body.len() as u64, if tlv.opt.ll { 4 } else { 2 });
    out.extend_from_slice(&body);

    let mut ts_bytes: Vec<u8> = Vec::new();
    if tlv.opt.ts {
        let t = match &tlv.trailer {
            Some(tr) if tr.ts.is_some() => tr.ts.unwrap(),
            _ => Timestamp {
                relative: tlv.opt.tf,
                value: 0,
            },
        };
        if tlv.opt.tf {
            write_le(&mut ts_bytes, (t.value as i32 as u32) as u64, 4);
        } else {
            write_le(&mut ts_bytes, t.value as u64, 8);
        }
        out.extend_from_slice(&ts_bytes);
    }
    if tlv.opt.cr {
        let mut covered = body;
        covered.extend_from_slice(&ts_bytes);
        if tlv.opt.cw {
            write_le(&mut out, crc16_ccitt(&covered) as u64, 2);
        } else {
            write_le(&mut out, crc32c(&covered) as u64, 4);
        }
    }
    out
}