Skip to main content

Crate odx_rs

Crate odx_rs 

Source
Expand description

§odx-rs

A parser for ASAM MCD-2 D (ODX) diagnostic descriptions and the PDX containers that carry them, written in Rust.

ODX describes how a diagnostic tester talks to an ECU: the services it offers, the byte layout of every request and response, the meaning of each value and the trouble codes it can report. A .pdx file is a ZIP archive of those XML documents. odx-rs opens the archive, reads the documents and hands back one navigable model.

The crate is plain Rust with no platform assumptions — it powers a browser viewer through WebAssembly, and works just as well in a command line tool.

§Install

[dependencies]
odx-rs = "0.39"

§0.39.0

  • Six new Annex B rules over the flash data model — ordered address ranges (B.71–B.74), one TYPE per EXPECTED-IDENT (B.69), and typed flash values that parse as what they declare (B.75) — taking the audited profile to 56 numbered rules.
  • The rule table below is complete again: it had drifted 19 rules behind the implementation, and now carries one row per identifier validation_rule_ids() reports.

§0.38.0

  • The workspace viewer uses inspect_pdx to show the model and validation findings from one parse, with a Validation tab and status counts.
  • The two-pane viewer now remains operable without horizontal overflow at a 303 px viewport.

No library parsing or validation behaviour changed.

§0.37.0

  • odx rules exposes the validation inventory as newline-delimited text or a 63-item JSON array, without requiring a container.
  • Corrected the conformance record to identify the three numbered warning rules rather than describing all 50 as errors.

§0.36.0

  • validation_rule_ids() exposes the complete validation-profile inventory; the WebAssembly module exports the same list for browser consumers.
  • The viewer displays the inventory supplied by its bundled core instead of a copied count.
  • The production viewer build now uses the size-optimised wasm-release profile and stays inside the project’s 650 KB module budget.

§0.27.0–0.35.0

These releases expanded the audited Annex B profile to 50 numbered rules, corrected B.50 and B.223 edge cases, measured the coverage denominator, and reconstructed missing registry history and source provenance. The complete per-version record is the registry-audited CHANGELOG, including the two tagged versions that were never published.

§0.26.0

  • New rule B.139: a LOGICAL-LINK names one of the four layer combinations the clause enumerates, and each reference resolves to the kind it names — a BASE-VARIANT-REF pointing at an ECU-VARIANT selects the wrong layer on the vehicle.
  • New rule C.SDG-CAPTION-ID: an SDG-CAPTION without the identifier Annex C makes mandatory. The reference implementation refuses to load such a file while this reader reported it clean.
  • OdxService::audience keeps a stated denial apart from silence. ODX defaults an omitted IS-… to true, so IS-SUPPLIER="false" denies while omitting grants — reading only the "true" flags inverted that, and lost 64 stated denials in the committed fixture alone.
  • A byte layout the parse bounds cut short says so, with a ROWS-TRUNCATED or DEPTH-TRUNCATED row. It used to stop silently, so “nothing more” and “not shown” looked identical. No real container produces either marker.
  • A deserialize feature reads the model back from its own JSON, so a parse result can be archived and a stored baseline diffed against a fresh container. Off by default; the WebAssembly module is byte-identical without it.

§0.25.0

  • B.38 fires when a DTC-DOP states no physical type at all. The clause says the base type “shall be set”; comparing only a stated value let the document furthest from conformant pass.
  • B.51 follows §7.3.5: a parameter without a BYTE-POSITION is packed at the byte edge after the previous one, not placed at byte 0 — which reported the layout the clause describes as correct.

§0.24.0

  • Annex B rule 156: a STRUCTURE’s stated BYTE-SIZE must cover its parameters, and must be absent where the structure has a component whose length is decided at run time. A size stated there contradicts the data, and a decoder that trusts it misplaces everything after the structure.
  • tests/hostile_shapes.rs pins that reference cycles, self- and mutually-inheriting layers and dangling references all terminate — one of them on the 1 MiB stack the browser build gets.

§0.23.0

  • Lists a MUX, STATIC-FIELD, END-OF-PDU-FIELD or DYNAMIC-LENGTH-FIELD that no parameter references. These were collected only where a parameter pointed at one — which covers every use, and not a definition standing on its own, which a dictionary is allowed to hold. Counts move: the demo fixture goes from 12 DOPs to 14.

    Found by the first foreign container this crate has been run against (odxtools’ somersault.pdx), which defines one multiplexer and references it nowhere.

§0.22.0

  • OdxParam::dop_kind says what a parameter’s DOP-REF points at. A DOP-REF may name any DOP-BASE while document.dops holds DATA-OBJECT-PROP alone, so joining the two found nothing for a structure, mux or field — and could not tell that from a dangling reference.

§0.21.0

  • Seven Annex C grammar rules: identifiers only where the schema declares them, NRC-CONST’s mandatory CODED-VALUES wrapper, a comparam’s required CPUSAGE, the data dictionary’s declared child order, the parameter that selects a snapshot’s trouble code, and a vehicle link’s pins. The schema states each; a reader that does not run the schema accepts the file and the next tool in the chain rejects it. Two ship as warnings — see the CHANGELOG for why. These can flip a previously-clean archive to exit 1.

§0.20.0

  • inspect returns the model and the findings from one read of the container — measured 23-27% faster than calling parse then validate, which each inflate the archive and parse every document in it. Both existing functions are unchanged; a test asserts the answers are identical.

§0.19.0

  • New rule NRC-CONST-SET, error level: a negative response’s codes belong to one NRC-CONST (ISO 22901-1 §7.3.6.10, and CODED-VALUE is maxOccurs="unbounded"), not to one parameter per code. Several of them on one byte each demand the byte hold their own value, so the message matches nothing. This can flip a previously-clean archive to exit 1.
  • New warning: a package holding no ODX document at all. 0 error(s), 0 warning(s) on an archive with nothing in it read exactly like a clean verdict, which is the answer a caller acts on.
  • OdxParam::coded_values gives every code a parameter accepts as numbers, so reading an NRC-CONST’s set no longer means parsing the "0x13, 0x31" display string.
  • odx tree --format json prints the model as data — short names, parameter positions, coded values — instead of accepting the flag and printing the indented list anyway. tree and summary now reject --format sarif.
  • Every public model type implements Clone.

§0.18.0

  • Reads loose ODX documents without a PDX around them, via parse_documents / validate_documents and odx validate <dir>. Both take a document set, since a layer’s references into the subset beside it are ordinary and only resolve when the documents that travel together are supplied.

§0.17.0

  • The public model types are #[non_exhaustive], so the field additions this crate makes every release stop being source-breaking. Reading is unchanged; constructing one needs ..Default::default().
  • A skipped archive entry reports why — damaged, over the per-document limit, or over what the archive budget had left.

§0.16.0

  • Adds OdxDocument::services: every service each layer offers, with its numeric identifier, references, functional classes and precondition states — and the layer that declared it, so “what does this variant answer to” and “how many services exist” stay separable.

§0.15.1

  • Security. Refuses a document nested deeper than 256 elements. Recursive passes over the parsed tree overflowed the stack on deeply nested input and aborted the process — from a 400-byte archive on the browser’s 1 MiB stack, where panic = "abort" takes the page with it. The 0.14.0 size bounds do not cover this: such a document is a few kilobytes. Real ODX nests 14 deep.

§0.15.0

  • Adds a fixture generated by an independent producer (udsdoc) with tests pinning the invariant that this reader reports nothing on real-world output — previously checked only by a CI job needing network and Python.

§0.14.1

  • Restores the release notes for 0.12.0-0.14.0, which had been lost from this file, and documents the machine-readable indexes and the input bounds in the body rather than only in the changelog.

§0.14.0

  • Bounds what is inflated from an archive: 64 MiB per document, 256 MiB per archive, 65,536 entries, and no pre-allocation on the header’s unverified say-so. The reader takes arbitrary uploads in the browser, where an allocation failure aborts the page — a crafted archive under 1 MB could previously drive a 4.6 exabyte allocation. An oversized document is reported as skipped rather than silently dropped.

§0.13.0

  • OdxDop gains physical_base_data_type, coded_type_kind and high_low_byte_order — the facts a decoder needs beyond the bit length, with the byte order reported as its effective value rather than as written.

§0.12.0

  • Adds OdxDocument::dtcs (trouble codes as data, with numeric codes), OdxDocument::summary (the counts parser_info renders, as numbers), and OdxParam::kind / OdxParam::coded_value, so a program no longer has to parse display strings whose format is a presentation choice.
  • Builds the browser module with a wasm-release profile that is 13.4% smaller than release, without slowing the odx command.

§0.11.0

  • Reads communication-parameter overrides attached directly to a diagnostic service, resolving the referenced ODX-CS definition and preserving its ODX 2.2 SIMPLE-VALUE in the service tree. Legacy VALUE input remains readable.

§0.10.0

  • Ships an installable odx command (cargo install odx-rs) with validate, tree, summary and dops, text/JSON/SARIF output, and an exit-code contract a CI job can gate on. See “The odx command” below.
  • Adds a cli feature (default on) so the library and the WebAssembly build do not carry the command’s serde_json dependency.
  • Declares an MSRV of 1.88 and starts a CHANGELOG.

§0.9.0

  • Reads ENV-DATA-DESC through the ENV-DATA-REFS list the ISO schema makes mandatory, so the snapshot records kept with a trouble code are reachable. An inline ENV-DATAS wrapper is still accepted.
  • Reads ECU-VARIANT-PATTERN / BASE-VARIANT-PATTERN: which diagnostic communication to run, which output parameter to read and the value it must match. This is how a tester picks the variant in front of it, and it was invisible.
  • Reads the PROT-STACKs of a COMPARAM-SPEC — the PDU protocol and physical link type a PROTOCOL layer’s communication parameters are meant for.
  • OdxDop carries inverse_scales from COMPU-PHYS-TO-INTERNAL, the conversion back from a physical value to the coded one that an encoder needs.

§0.8.0

  • Reads a COMPLEX-COMPARAM’s members. The ISO schema nests them directly under it as an unbounded choice of COMPARAM and COMPLEX-COMPARAM, with no wrapper; looking only inside a COMPARAMS wrapper found none of them. Its positional COMPLEX-PHYSICAL-DEFAULT-VALUE is reported too.
  • Reads the UNIT-SPEC: each unit with its FACTOR-SI-TO-UNIT, OFFSET-SI-TO-UNIT and physical dimension, and each PHYSICAL-DIMENSION with its SI exponents. Resolving a UNIT-REF to a display name loses the conversion, which exists nowhere else in the container.

§0.7.0

  • Reads the vehicle-information topology: the INFO-COMPONENTs that identify the vehicle (manufacturer, model, model year, VIN) with the value a tester is expected to match, the VEHICLE-CONNECTORs and their pins, the PHYSICAL-VEHICLE-LINKs with the protocol each carries, and whether a logical link reaches its ECU directly or through a gateway.
  • Reads ADMIN-DATA wherever it appears — language, company and the DOC-REVISION trail (label, state, date, tool) — so a delivery says who produced it and at what revision.
  • Reads a flash session’s SECURITY-METHOD and a segment’s SOURCE-END-ADDRESS, which together say how the ECU is unlocked and where the memory range ends.
  • Reads the bounds and TERMINATION of a MIN-MAX-LENGTH-TYPE, so a variable-length payload no longer reads back as a zero-bit row.
  • OdxCompuScale carries the numeric COMPU-CONST/V and the scale’s SHORT-LABEL beside the textual constant it already had.
  • Names the request byte a MATCHING-REQUEST-PARAM echoes, and reports a service’s IS-EXECUTABLE.

§0.6.0

  • Reads TABLE-ROW written directly under TABLE, the shape ODX 2.2.0 specifies, as well as the TABLE-ROWS wrapper some producers emit.
  • Reads the response codes of an NRC-CONST parameter from the mandatory CODED-VALUES list, so negative responses no longer read back without their codes. A parameter offering several codes shows all of them.
  • Surfaces a layer’s GLOBAL-NEG-RESPONSES — the ECU-wide negative-response catalogue, which no service references and which was therefore invisible.
  • Adds an inspect example that reports what a container read back as, per node kind, for spotting constructs a producer writes but the reader drops.

§0.5.2

  • Corrects B.11 to read PHYSICAL-TYPE/PRECISION as a child element and report it on non-floating-point physical types.
  • Exposes schema-correct PRECISION and DISPLAY-RADIX values in the viewer model and corrects the demo PDX fixture.

§0.5.1

  • Makes parser and validator reference resolution consistently document-aware.
  • Corrects imported DOP short-name precedence, zero bit lengths, shared DOP-BASE inheritance namespaces, and deep parent chains.
  • Removes the fixed sniff window for misnamed ODX members.

§0.5.0

  • Resolves ODX links by document, DOCREF, DOCTYPE, and effective layer data pool instead of package-global bare IDs.
  • Hardens B.31, B.50, B.51, B.107, B.165, B.172, B.185, B.186, and B.223 with adversarial cross-document, inheritance, field-layout, and schema-default cases.
  • Aligns catalogue handling with Annex C cardinalities/defaults and all four incremental omission states, including REUSED.
  • Parses supported declared XML encodings and rejects additional well-formedness errors.
  • Defines the partial-profile boundary in CONFORMANCE.md.

§0.4.0

  • Adds PDX catalogue structure and incremental-exchange validation, ODX category-extension, contextual DOCREF, and diagnostic-layer inheritance validation.
  • Expands the Annex B validation profile to 31 rules, including B.11, B.12, B.15, B.31, B.50, B.107, B.158, B.165, B.172, B.186, B.213, B.223, and B.227.
  • Audits all 31 implementations against the normative Annex B table, including effective layer data pools, bounded variable request fields, referenced and linked DTC sets, and complex communication-parameter values.
  • Rejects malformed XML roots and non-UTF-8 ODX documents during validation.
  • Preserves all SDG rows by default; presentation limits are now opt-in.

§Usage

use odx_rs::OdxNode;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let bytes = std::fs::read("DemoVehicle_Diagnostics.pdx")?;
    let document = odx_rs::parse(&bytes, "DemoVehicle_Diagnostics.pdx")?;

    println!("{} ({})", document.file_name, document.parser_info);
    for root in &document.roots {
        print_node(root, 0);
    }
    Ok(())
}

fn print_node(node: &OdxNode, depth: usize) {
    println!("{:width$}{} [{:?}]", "", node.name, node.kind, width = depth * 2);
    for child in &node.children {
        print_node(child, depth + 1);
    }
}

Every node carries the ODX identifiers and attributes it came from, so what you display can be traced back to the source document:

use odx_rs::{OdxNode, OdxNodeKind};

/// Collects every diagnostic service, labelled with its service identifier.
fn services(node: &OdxNode, out: &mut Vec<String>) {
    if node.kind == OdxNodeKind::Service {
        // `badge` holds the service identifier, e.g. "0x22".
        let id = node.badge.as_deref().unwrap_or("--");
        out.push(format!("{id} {}", node.name));
    }
    for child in &node.children {
        services(child, out);
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let bytes = std::fs::read("container.pdx")?;
    let document = odx_rs::parse(&bytes, "container.pdx")?;

    let mut found = Vec::new();
    for root in &document.roots {
        services(root, &mut found);
    }
    println!("{} services", found.len());
    Ok(())
}

Failures say what went wrong, so a malformed upload can be told apart from a bug:

use odx_rs::ErrorKind;

let bytes = b"<?xml version=\"1.0\"?>";
match odx_rs::parse(bytes, "maybe.pdx") {
    Ok(document) => println!("{} roots", document.roots.len()),
    Err(error) => match error.kind() {
        ErrorKind::NotAContainer => eprintln!("not a PDX file: {error}"),
        ErrorKind::UnreadableArchive => eprintln!("damaged archive: {error}"),
    },
}

A document inside the archive that fails to parse does not fail the call: it is collected under a Problems node and counted in parser_info, so a partly broken container still shows everything that could be read.

§Checking a container

Reading a container and judging it are separate questions: parse is deliberately forgiving, while validate applies the crate’s audited, partial ISO 22901-1:2008 ODX/PDX validation profile. It reports malformed XML, selected PDX catalogue/schema conditions, invalid cross-document links, and the Annex B violations listed below:

use odx_rs::Severity;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let bytes = std::fs::read("container.pdx")?;

    for finding in odx_rs::validate(&bytes, "container.pdx")? {
        let mark = match finding.severity {
            Severity::Error => "error",
            Severity::Warning => "warn ",
        };
        println!("{mark} {} {} — {}", finding.rule, finding.location, finding.message);
    }
    Ok(())
}

Every finding carries the path it was found at, so a report can be checked against the source document by hand.

The rules with a B. number come from Annex B of ISO 22901-1; the C. rules enforce declarations of the Annex C schema this reader deliberately does not run; the rest are named after what they check. This table is complete — one row per identifier validation_rule_ids() reports:

RuleWhat it requires
B.5A PROG-CODE’s SYNTAX is one of the strings the standard matches against (warning — the clause says “is matched against”, not “shall be one of”)
B.11DISPLAY-RADIX and PRECISION fit the physical data type
B.12MIN-LENGTH does not exceed MAX-LENGTH
B.14SCALE-CONSTR ranges do not overlap one another
B.15End-of-PDU minimum item count does not exceed its maximum
B.16A CASE’s LOWER-LIMIT does not exceed its UPPER-LIMIT
B.17An item-count DATA-OBJECT-PROP converts to A_UINT32
B.31Each ID-REF resolves through its stated document context to a target in the current layer data pool
B.38A DTC-DOP states A_UINT32 as its physical base type — absent counts as a violation, not a pass
B.41A message carries at most one SERVICE-ID parameter
B.42Byte and string coded types declare no byte order, except for a leading-length field
B.43INTERNAL-CONSTR uses an ordered coded type
B.44A SWITCH-KEY’s DOP has a STANDARD-LENGTH-TYPE, so its width is knowable before the case it selects
B.46A MUX without CASES has a DEFAULT-CASE
B.50Diagnostic-layer parent relationships follow the ODX hierarchy
B.51Parameters of one request must not claim the same bits — unpositioned parameters follow the §7.3.5 packing rule, and bounded variable-length fields count
B.52A TAB-INTP COMPU-SCALE has exactly one LOWER-LIMIT and no UPPER-LIMIT
B.53A COMPUCODE direction contains only PROG-CODE
B.54Unit conversion members are specified together
B.56Sibling elements of one wrapper carry distinct SHORT-NAMEs
B.57Each SCALE-CONSTR range fits inside the INTERNAL-CONSTR range
B.59An IDENTICAL conversion keeps the base data type, except ASCII/UTF-8 may widen to Unicode
B.60A computing conversion has numeric types on both sides
B.61A TEXTTABLE converts to A_UNICODE2STRING
B.64Each declared conversion direction has the required COMPU-SCALE count
B.69The IDENT-VALUEs of one EXPECTED-IDENT share one TYPE
B.71A PHYS-SEGMENT’s START-ADDRESS does not exceed its END-ADDRESS
B.72A CHECKSUM stating both source addresses states them in order
B.73A FILTER’s FILTER-START does not exceed its FILTER-END
B.74A SEGMENT stating both source addresses states them in order
B.75Flash ident values are readable as the schema datatype their TYPE names — A_UINT32 as xsd:unsignedInt, A_BYTEFIELD as xsd:hexBinary
B.80A CHECKSUM’s UNCOMPRESSED-SIZE, when present, is greater than zero
B.83PHYS-SEGMENT address ranges of one PHYS-MEM do not overlap
B.96No PROTOCOL-SNREF at a DIAG-COMM inside a PROTOCOL layer
B.99TABLE-ROW/KEY is unique inside a TABLE, referenced rows included
B.104A layer holds at most one STARTCOMM and one STOPCOMM service, inherited and imported ones included
B.105A layer holds at most one DEFAULT-FAULT-READ service (warning)
B.107A session does not reference one data block twice
B.114Numeric coded types use a length-stating encoding
B.116A LENGTH-KEY’s DOP converts to A_UINT32
B.122LOWER-LIMIT does not exceed UPPER-LIMIT, and an equal pair is closed on both ends
B.130Every COMPU-SCALE states a LOWER-LIMIT, except LINEAR and RAT-FUNC
B.139A LOGICAL-LINK names one of the four permitted layer combinations
B.145A float coded type is a correctly sized STANDARD-LENGTH-TYPE
B.151COMPU-SCALEs of one wrapper do not overlap, except under TEXTTABLE
B.156A structure’s stated BYTE-SIZE covers where its parameters end (warning)
B.157DOCREF and DOCTYPE travel together or not at all
B.158An ODX category agrees with its lowercase file extension
B.161A PHYSICAL-DEFAULT-VALUE exists only where the referenced DOP can convert it
B.165Rational coefficient counts fit their conversion category
B.172A scale with no upper limit has a closed lower limit
B.185TROUBLE-CODE and SHORT-NAME map one-to-one across local, referenced, and linked DTCs after exclusions
B.186A COMPARAM-REF carries the value shape required by its target
B.213CONDENSED=true carries a BIT-MASK
B.223A DATABLOCK’s referenced flash format has USER-SELECTION exactly for USER-DEFINED
B.227No OID is handed out twice in the PDX data pool
C.PARAM-IDOnly a TABLE-KEY parameter carries an xsd:ID (warning)
C.NRC-CONSTNRC-CONST states its codes inside the mandatory CODED-VALUES wrapper
C.CPUSAGEA BASE-COMPARAM declares the required CPUSAGE
C.DDDS-ORDERDIAG-DATA-DICTIONARY-SPEC children keep the schema’s sequence order
C.ENV-DATA-DESCAn ENV-DATA-DESC carries the parameter that selects the trouble code
C.VEHICLE-INFO-IDVEHICLE-INFORMATION declares OID, not ID (warning)
C.PVL-PIN-REFSA PHYSICAL-VEHICLE-LINK names the pins it is wired to
C.SDG-CAPTION-IDAn SDG-CAPTION carries the identifier the schema makes mandatory
NRC-CONST-SETA negative response position carries its codes in one NRC-CONST, not a stack of them
ID-UNIQUENo ID is handed out twice within one XML document
BIT-LENGTH-REQUIREDA fixed-length coded type states its BIT-LENGTH
DOCUMENT-READABLEEvery document of the archive parses
PDX-CATALOGEnforced catalogue subset: fixed version, required names, non-empty present wrappers, valid update states, and incremental omission rules

The profile does not run the complete Annex C XML Schema and does not implement the complete Annex B checker table. Concretely: 56 of at least 181 real Annex B rules, roughly 31% — and because 30 further table rows resist extraction, 181 is a lower bound on the denominator and 31% an upper bound on the coverage. An empty finding list is not an ISO conformance certificate.

The overlapping rules are cross-checked against an independent Python implementation (udsdoc); a disagreement fails CI in both repositories. B.31 and B.51 are deliberately excluded because the two implementations have different resolution and sizing reach, and PDX-CATALOG is archive-scoped on this side. The exact overlap is derived from both sources in CI rather than copied here. This is a strong guarantee over a narrow slice: it says nothing about the 125 rules neither implementation enforces, and where both share a misreading it says nothing at all. That has happened once here, in NRC-CONST. See CONFORMANCE.md for the audit basis, exact boundary, and required complementary checks. A packaged member absent from the catalogue is not reported by this profile. An incremental ABLOCK may intentionally list a file omitted from the archive when UPD is UNCHANGED, UNUSED, REUSED, or DELETED.

§The odx command

The crate ships an installable command, so a container can be checked without writing any Rust:

cargo install odx-rs

odx validate container.pdx                    # every finding, then a count
odx validate container.pdx --format json      # the findings array, nothing else
odx validate container.pdx --format sarif     # for GitHub code scanning
odx validate container.pdx --strict           # warnings fail the run too

odx validate loose-odx-dir/                   # a directory of loose .odx-*
                                              # documents, e.g. what an
                                              # authoring tool leaves behind

odx tree    container.pdx --depth 3           # the parsed structure
odx tree    container.pdx --format json       # the same, as data
odx summary container.pdx --format json       # counts per node kind
odx dops    container.pdx                     # the machine-readable DOP index
odx rules   --format json                     # validation profile IDs

Exit codes are the part a CI job depends on:

CodeMeaning
0the container was read, and nothing was reported at the failing level
1findings were reported at the failing level
2the container could not be read at all, or the arguments were wrong

The gap between 1 and 2 is deliberate: a pipeline that produced no file must not be mistaken for one that produced a good file.

The binary lives behind the cli feature, which is on by default. A dependent that only wants the library takes it out:

[dependencies]
odx-rs = { version = "0.38", default-features = false }

cargo run --example validate -- container.pdx remains as a minimal, readable example of calling validate yourself.

§Options

parse_with_options puts the limits that keep the model small under the caller’s control. SDGS is where tools park data of their own, and a container may carry more of it than a property table can usefully show:

use odx_rs::ParseOptions;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let bytes = std::fs::read("container.pdx")?;
    let options = ParseOptions { max_sdg_rows: None };
    let document = odx_rs::parse_with_options(&bytes, "container.pdx", options)?;

    println!("{} roots", document.roots.len());
    Ok(())
}

The default retains every SDG row. Set max_sdg_rows to Some(limit) only when a presentation layer needs an explicit bound; whenever rows are then dropped, the element gains an SDG-TRUNCATED property holding the number left out.

§What is read

  • Catalogue (index.xml) and vehicle information (.odx-v).
  • Diagnostic layers (.odx-d) — protocols, functional groups, shared data, base variants and ECU variants, with their services, single ECU jobs, requests and responses, data object properties, structures, tables, environment data, state charts, function classes and communication parameters.
    • Inheritance follows PARENT-REF in the order ODX ranks layers, honours NOT-INHERITED-DIAG-COMM / NOT-INHERITED-DOP, and reports both where an element was inherited from and what a local definition overrides.
    • Complex parameters — a parameter pointing at a structure, a repeating field (END-OF-PDU-FIELD, STATIC-FIELD, DYNAMIC-LENGTH-FIELD) or a multiplexer is expanded into nested rows with byte positions rebased onto the parent.
  • Multiple ECU jobs (.odx-m), the function dictionary (.odx-fd), comparam specs (.odx-c), comparam subsets (.odx-cs) and flash containers (.odx-f).
  • SDGS special data wherever it appears, with nested groups keeping their path.

§Reading the model as data

The tree renders for a person: badges and property rows are display strings whose format is a presentation choice, not an interface. Beside it are flat indexes meant for a program, so nothing has to be parsed back out of prose.

The tree itself serialises too — odx tree --format json, or serde_json on an OdxDocument. Every node keeps its shortName, and every parameter its bytePosition, bitPosition, bitLength, kind, codedValue and codedValues, and dopKind names what its DOP-REF points at so a join against dops can tell “a kind that index does not hold” from “nothing at all”. That is what a generator needs to assert its own output came back unchanged: udsdoc’s browser edition compares each message’s byte template, its exact per-parameter layout and its set of negative-response codes against what this reader made of the archive it just wrote.

document.dops lists every DATA-OBJECT-PROP once. Besides its conversion — the scales of a COMPU-METHOD with their rational coefficients, limits and COMPU-CONST text, plus inverse_scales for the COMPU-PHYS-TO-INTERNAL direction an encoder needs — each entry carries what it takes to actually decode a value:

FieldWhy it is not enough to have the bit length
base_data_typehow the bytes on the wire are read
physical_base_data_typewhat the value becomes; differs whenever the conversion does anything
coded_type_kindthe DIAG-CODED-TYPE xsi:type — a MIN-MAX-LENGTH-TYPE has no bit length at all
high_low_byte_orderreported as its effective value: ODX defaults it to true, and guessing gives a plausible wrong number rather than an error

document.services is the same idea for services, with one difference that matters: it records the layer each entry belongs to and, when the layer inherited rather than declared it, the layer that defined it. “What does this ECU variant answer to” and “how many services exist” are different questions — the first counts entries, the second counts entries with no inherited_from — and a list that forgot the layer answers neither. Each entry carries the numeric service identifier, the request and response IDs, the functional classes it is filed under, and the states a PRE-CONDITION-STATE-REF requires, resolved to names.

document.dtcs is the same idea for trouble codes: the numeric TROUBLE-CODE, the display form a technician reads, the text, the level and the DTC-DOP that declared it.

document.summary carries the counts parser_info renders as prose — layers, services, DOPs, DTCs, jobs, environment data, flash blocks, and how many archive entries failed to parse. Both are built from one set of values so they cannot drift. It counts what the tree shows, each definition once and diagnostic layers only, which is deliberately narrower than dops; the doc comments say so on both sides.

A parameter row names the DOP it uses in dop_ref and keeps its bit_position, so two four-bit values sharing a byte stay distinguishable. It also carries kind (the xsi:type, which semantic silently falls back to) and coded_value (the number, where it has exactly one) — so telling a CODED-CONST from a VALUE, or comparing against an expected byte, does not mean reading "0x22" back out of a string whose width depends on the bit length.

The model is serde-serialisable, so it can be handed to another language or written out as JSON directly — which is what odx dops and odx summary --format json do.

§ODX without a PDX

A .odx-d on its own is what comes out of version control, out of an authoring tool, and out of a generator writing loose files. parse_documents and validate_documents read those directly, and the odx command takes a directory:

let layer = std::fs::read("Sample.odx-d")?;
let subset = std::fs::read("ISO_15765_2.odx-cs")?;
let findings = odx_rs::validate_documents(vec![
    ("Sample.odx-d".into(), layer),
    ("ISO_15765_2.odx-cs".into(), subset),
]);

Both take a set rather than one document on purpose. ODX cross-document references are ordinary — a diagnostic layer points at the comparam subset beside it — and a reference whose target was simply not supplied looks exactly like one that is broken. Hand over the documents that travel together and they resolve; hand over one and the rest are reported unresolved, which is true but rarely what you meant.

The PDX catalogue rules do not run here: a loose document never claimed to be a package, so a missing index.xml would be a fact about the call rather than about the data. Everything else is checked exactly as it would be inside a container.

§Limits

The reader takes untrusted input: the browser viewer hands it whatever file is dropped on the page, in a module built with panic = "abort", where a failed allocation ends the page rather than returning an error. Inflation is therefore bounded — 64 MiB per document, 256 MiB across an archive, at most 65,536 entries, never more than 4 MiB reserved on the size an archive claims in its own header, and at most 256 levels of element nesting (real ODX nests 14 deep; the passes over a parsed tree recurse once per level, so a deeper document overflowed the stack). A document over a limit is reported as skipped, so it appears under Problems rather than disappearing from a container that would otherwise look complete.

§Scope

odx-rs reads descriptions; it does not talk to a vehicle and does not decode live ECU responses. See CONFORMANCE.md for the exact validation boundary and ROADMAP.md for every adopted, deferred, and rejected extension considered in the 2026-08-02 audit.

§License

MIT

§Design notes

Reader for ODX diagnostic descriptions.

The subject of this crate is ODX itself: the XML documents that describe how to talk to an ECU. A PDX file is just how they travel, so parse opens that ZIP archive (container), reads every document in it (xml) and maps the result onto a navigable model (odx).

The crate is plain Rust: it has no browser dependency, so it can be used from a command line tool or a test as easily as from WebAssembly. The bindings live in the pdx-wasm crate next to this one.

Re-exports§

pub use model::MessageDirection;
pub use model::OdxCompuScale;
pub use model::OdxDocument;
pub use model::OdxDop;
pub use model::OdxMessage;
pub use model::OdxNode;
pub use model::OdxNodeKind;
pub use model::OdxParam;
pub use model::OdxProperty;

Modules§

model
Serialisable ODX model.

Structs§

Finding
One thing that is wrong with a container. Marked #[non_exhaustive]: this type gains fields as the reader learns to read more of ODX, and every such addition would otherwise be a source- breaking change for anyone constructing it. Build one with ..Default::default() or read it field by field.
ParseError
ParseOptions
Knobs that change how much of a container ends up in the model.

Enums§

ErrorKind
What went wrong, so a caller can react differently per cause.
Severity
How much a finding matters.

Functions§

inspect
The model and the findings, from one read of the container.
inspect_with_options
inspect, with the limits of ParseOptions under the caller’s control.
name
Name of this crate, shown next to the version in the viewer.
parse
Reads a PDX container and returns the model the viewer renders.
parse_documents
Reads loose ODX documents — a .odx-d and the .odx-cs beside it, say — without a PDX archive around them.
parse_documents_with_options
parse_documents, with the limits of ParseOptions under the caller’s control.
parse_with_options
parse, with the limits of ParseOptions under the caller’s control.
validate
Checks a PDX archive against this crate’s Annex B / Annex C profile.
validate_documents
Checks loose ODX documents against the same profile validate applies to an archive, minus the rules that judge the package itself.
validation_rule_ids
Rule identifiers the current validation profile can report.
version
Version of this crate, shown in the viewer’s status bar and About dialog.