Skip to main content

decode

Function decode 

Source
pub fn decode(input: &[u8]) -> Result<Tlv, Error>
Expand description

@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.

Examples found in repository?
examples/perf.rs (line 46)
45fn roundtrip(input: &[u8]) {
46    let tlv = decode(input).expect("conformance vector must decode");
47    black_box(encode(black_box(&tlv)));
48}
More examples
Hide additional examples
examples/conformance.rs (line 90)
70fn run_roundtrip() -> ExitCode {
71    let mut text = String::new();
72    if std::io::stdin().read_to_string(&mut text).is_err() {
73        // Non-UTF-8 stdin is not a valid hex stream; nothing to emit.
74        return ExitCode::SUCCESS;
75    }
76    let mut lines: Vec<&str> = text.split('\n').collect();
77    // A trailing newline yields a final empty element — drop only that one.
78    if lines.last() == Some(&"") {
79        lines.pop();
80    }
81    let mut out: Vec<String> = Vec::with_capacity(lines.len());
82    for raw in lines {
83        let line = raw.trim_end_matches(['\r', '\n']);
84        if line.is_empty() {
85            out.push("ERR:EMPTY_LINE".to_string());
86            continue;
87        }
88        match from_hex(line) {
89            None => out.push("ERR:BAD_HEX".to_string()),
90            Some(bytes) => match decode(&bytes) {
91                Ok(tlv) => out.push(to_hex(&encode(&tlv))),
92                Err(e) => out.push(format!("ERR:{}", e.name())),
93            },
94        }
95    }
96    print!("{}\n", out.join("\n"));
97    ExitCode::SUCCESS
98}
99
100/**
101 * @brief Extract the expected decode-error name from a case's expected.json —
102 * the value of its top-level `"reject"` field (scan-to-quote, mirroring
103 * tests/conformance_vectors.rs `json_str`; the field is machine-written ASCII).
104 */
105fn reject_expectation(case_dir: &Path) -> Option<String> {
106    let text = fs::read_to_string(case_dir.join("expected.json")).ok()?;
107    let key = text.find("\"reject\"")?;
108    let colon = key + text[key..].find(':')?;
109    let q1 = colon + 1 + text[colon + 1..].find('"')?;
110    let q2 = q1 + 1 + text[q1 + 1..].find('"')?;
111    Some(text[q1 + 1..q2].to_string())
112}
113
114/**
115 * @brief One negative case: decode(reject.bin) MUST fail with exactly the
116 * expected error. Returns `(ok, diagnostic)`.
117 */
118fn check_reject(reject_bin: &Path) -> (bool, String) {
119    let Some(want) = reject_bin.parent().and_then(reject_expectation) else {
120        return (
121            false,
122            "reject.bin without a \"reject\" expectation in expected.json".to_string(),
123        );
124    };
125    match fs::read(reject_bin) {
126        Err(e) => (false, e.to_string()),
127        Ok(bytes) => match decode(&bytes) {
128            Ok(_) => (false, format!("decode succeeded, expected {}", want)),
129            Err(e) if e.name() == want => (true, String::new()),
130            Err(e) => (
131                false,
132                format!("decode failed with {}, expected {}", e.name(), want),
133            ),
134        },
135    }
136}
137
138/**
139 * @brief Recursively collect (relative-posix-path, absolute-path) for every
140 * input.bin and reject.bin.
141 */
142fn find_inputs(root: &Path, dir: &Path, out: &mut Vec<(String, PathBuf)>) {
143    let mut entries: Vec<PathBuf> = match fs::read_dir(dir) {
144        Ok(rd) => rd.filter_map(|e| e.ok().map(|e| e.path())).collect(),
145        Err(_) => return,
146    };
147    entries.sort();
148    for p in entries {
149        if p.is_dir() {
150            find_inputs(root, &p, out);
151        } else if p
152            .file_name()
153            .map(|n| n == "input.bin" || n == "reject.bin")
154            .unwrap_or(false)
155        {
156            let rel = p
157                .parent()
158                .unwrap()
159                .strip_prefix(root)
160                .unwrap()
161                .components()
162                .map(|c| c.as_os_str().to_string_lossy())
163                .collect::<Vec<_>>()
164                .join("/");
165            out.push((rel, p));
166        }
167    }
168}
169
170/** @brief Default / `--tap`: emit TAP version 13 for the round-trip of every vector. */
171fn run_tap(vectors_dir: &Path) -> ExitCode {
172    let mut cases: Vec<(String, PathBuf)> = Vec::new();
173    find_inputs(vectors_dir, vectors_dir, &mut cases);
174    // Sort by POSIX relative path so keys match the C++/TS harnesses.
175    cases.sort_by(|a, b| a.0.cmp(&b.0));
176
177    let mut lines: Vec<String> = Vec::new();
178    lines.push("TAP version 13".to_string());
179    lines.push(format!("1..{}", cases.len()));
180    let mut n = 0;
181    let mut fails = 0;
182    for (rel, abs) in &cases {
183        n += 1;
184        let mut ok = false;
185        let mut diag = String::new();
186        if abs.file_name().map(|f| f == "reject.bin").unwrap_or(false) {
187            (ok, diag) = check_reject(abs);
188        } else {
189            match fs::read(abs) {
190                Ok(input) => match decode(&input) {
191                    Ok(tlv) => {
192                        ok = encode(&tlv) == input;
193                        if !ok {
194                            diag = "round-trip differs from input.bin".to_string();
195                        }
196                    }
197                    Err(e) => diag = e.name().to_string(),
198                },
199                Err(e) => diag = e.to_string(),
200            }
201        }
202        lines.push(format!(
203            "{} {} - {}",
204            if ok { "ok" } else { "not ok" },
205            n,
206            rel
207        ));
208        if !ok {
209            lines.push(format!("# {}", diag));
210            fails += 1;
211        }
212    }
213
214    print!("{}\n", lines.join("\n"));
215    if fails == 0 {
216        ExitCode::SUCCESS
217    } else {
218        ExitCode::FAILURE
219    }
220}
examples/path_tlv.rs (line 35)
14fn main() {
15    let tlv = path_to_tlv("/sensor/temp").expect("a rooted, valid path");
16    assert_eq!(tlv.type_code, type_code::PATH);
17
18    // The body: [6]"sensor" [4]"temp". No separators, no terminator.
19    let mut body = vec![6u8];
20    body.extend_from_slice(b"sensor");
21    body.push(4);
22    body.extend_from_slice(b"temp");
23    assert_eq!(tlv.payload, body);
24    println!(
25        "PATH body ({} bytes): {:02x?}",
26        tlv.payload.len(),
27        tlv.payload
28    );
29
30    // On the wire it is an ordinary opaque TLV: 4-byte header + body.
31    let frame = encode(&tlv);
32    assert_eq!(frame.len(), 4 + body.len());
33
34    // Decoding and rendering gives back the one canonical spelling.
35    let back = tlv_to_path(&decode(&frame).unwrap()).unwrap();
36    assert_eq!(back, "/sensor/temp");
37    println!("round trip: {back}");
38
39    // A trailing slash is the same address; a relative one is no address at all.
40    assert_eq!(split_path("/sensor/temp/").unwrap(), ["sensor", "temp"]);
41    assert_eq!(path_to_tlv("sensor/temp"), Err(BuildError::NotRooted));
42    println!("\"sensor/temp\" -> NotRooted");
43}
examples/value_crc.rs (line 27)
13fn main() {
14    // A 4-byte reading, with the opt-in CRC-32C trailer (opt.CR = 1).
15    let reading = 21_500u32.to_le_bytes();
16    let opts = ValueOptions {
17        crc: true,
18        ..ValueOptions::default()
19    };
20    let frame = encode(&value_opts(&reading, &opts));
21
22    // 4-byte header + 4 payload bytes + 4 CRC bytes.
23    println!("frame ({} bytes): {:02x?}", frame.len(), frame);
24    assert_eq!(frame.len(), 4 + 4 + 4);
25
26    // Decoding checks the trailer and hands back the payload unchanged.
27    let tlv = decode(&frame).expect("an intact frame decodes");
28    assert_eq!(tlv.payload, reading);
29    let crc = tlv
30        .trailer
31        .and_then(|t| t.crc)
32        .expect("the trailer carries the CRC");
33    assert_eq!(crc.width, CrcWidth::Crc32c);
34    println!(
35        "decoded payload {:02x?}, crc32c {:#010x}",
36        tlv.payload, crc.value
37    );
38
39    // Flip one payload bit: the frame still parses, but the CRC no longer matches.
40    let mut damaged = frame.clone();
41    damaged[4] ^= 0x01;
42    assert_eq!(decode(&damaged), Err(Error::FrameCrcFail));
43    println!("one flipped bit -> {}", Error::FrameCrcFail.name());
44
45    // Without the trailer the same damage is invisible to the codec.
46    let mut bare = encode(&value_opts(&reading, &ValueOptions::default()));
47    bare[4] ^= 0x01;
48    assert!(decode(&bare).is_ok());
49    println!("same flip without a CRC -> decodes silently");
50}