Skip to main content

Error

Enum Error 

Source
pub enum Error {
    FrameTruncated,
    FrameInvalid,
    FrameCrcFail,
    TlvNestingTooDeep,
}
Expand description

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

Variants§

§

FrameTruncated

@brief Ran out of bytes (header/payload/trailer truncated).

§

FrameInvalid

@brief Reserved bit set, type code 0x00, or trailing bytes after the root TLV.

§

FrameCrcFail

@brief Trailer CRC did not match the recomputed value.

§

TlvNestingTooDeep

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

Implementations§

Source§

impl Error

Source

pub const fn name(self) -> &'static str

@brief The stable wire name used by the conformance harness (ERR:<name>).

Examples found in repository?
examples/conformance.rs (line 92)
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}
More examples
Hide additional examples
examples/value_crc.rs (line 43)
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}

Trait Implementations§

Source§

impl Clone for Error

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for Error

Source§

impl Debug for Error

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for Error

Source§

impl PartialEq for Error

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Error

Auto Trait Implementations§

§

impl Freeze for Error

§

impl RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl UnsafeUnpin for Error

§

impl UnwindSafe for Error

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.