edifact โก
EDIFACT (ISO 9735) for Rust โ zero-copy parsing, typed derive macros, layered validation, and a writer that cannot forge an envelope. Bounded by default against hostile input.
๐ Guides ยท ๐ฆ API reference ยท ๐ Threat model ยท ๐ฆ crates.io
Install
derive is on by default. Optional features:
Quick start
Parsing borrows from the input; a value is copied only where a release escape was resolved:
use ;
let input = b"UNA:+.? 'UNH+1+ORDERS:D:11A:UN'BGM+220+PO-4711+9'NAD+BY+4000001::9'UNT+4+1'";
let segments: = from_bytes.?;
let bgm = segments.first_tag.expect;
assert_eq!; // document code
assert_eq!; // document number
// Look up by tag and qualifier (element 0).
assert_eq!;
# Ok::
Map segments and whole messages onto structs, dispatching repeated segments by their qualifier:
use ;
let input = b"UNH+1+ORDERS:D:11A:UN'BGM+220+PO-4711+9'\
NAD+BY+4000001000002::9'NAD+SU+4000001000001::9'UNT+5+1'";
let segments: = from_bytes.?;
let msg = edifact_deserialize?;
assert_eq!;
# Ok::
Write it back out with delimiters escaped for you:
use to_edifact_string;
# use EdifactSerialize;
#
#
#
let wire = to_edifact_string?;
assert_eq!;
# Ok::
What makes it different
Where hand-rolled EDIFACT code usually goes wrong, edifact takes a position
(clauses refer to ISO 9735-1:2002):
| One segment type, borrowed or owned | Segment<'a> holds Cow text: from_bytes borrows, from_reader owns (OwnedSegment = Segment<'static>). One API serves both. |
| Zero-copy by default | from_bytes allocates each segment's element vector once and copies a value only where a release escape was resolved. The allocation budget is enforced by tests. |
| Refuses to guess | The slice and reader paths return the same Result for every input, however it is chunked. The decoding paths read the repertoire from UNB and refuse an unknown one instead of assuming UTF-8. |
| Bounded by default | 64 KiB per segment, 16 MiB per message, 256 MiB per input; a message window holds at most 128 ร its bytes. A limit is an error (E036), never a quiet end of input. ReaderConfig::unbounded() opts out for trusted input. Error text escapes control and bidi characters. |
| Interchanges are built, not assembled | One typed InterchangeHeader is parsed and written. InterchangeBuilder and Writer compute UNZ; MessageBuilder and MessageWriter compute UNT. No trailing empty element or component is written. |
| An honest writer | A message dropped without finish() gets no UNT; after a failed write the writer is poisoned and every later call returns E072. Refusals write nothing. |
| The envelope is checked against the standard | Structure, reference pairing and all control counts; every service-segment value against its ISO 9735-10 representation for syntax versions 1โ4; S004 as a real date and time; interactive, security and trailing segments refused by name. |
CONTRL from the report |
The acknowledgement is built from the validation report, so it cannot disagree with what you found. Each finding lands at the lowest level that can locate it and carry its code (ISO 9735-4 Annex A). |
| Layered validation | Envelope, syntax, charset, structure, code-list and profile checks write into one report with stable codes, byte spans and rule IDs. |
| Representations enforced | an..35, n8, a1: length in characters, not bytes (ยง6); a numeric length excludes sign, decimal mark and exponent (ยง10). Version-dependent positions (S004 DE 0017 n6/n8) are checked per version. |
| Identifiers, not indices | Address a field by its data element identifier. The derive resolves it at compile time, so a stale identifier fails the build. SegmentLayout::audit checks a hand-written layout against a corpus. |
| Repetitions survive the round trip | The repetition separator splits an element into occurrences (ยง8.7), from UNA or the UNB syntax version; #[edifact(repeat)] maps them onto a Vec<T>. |
| Dates by format code | Feature dtm: decode, compare and build DTM values for 17 UNCL 2379 codes; dtm-time converts to time. |
| Character sets decoded, not assumed | decode_interchange reads the repertoire from UNB S001 and transcodes UNOAโUNOK/UNOY, borrowing when the payload is ASCII. |
No unsafe |
#![deny(unsafe_code)]; property and fuzz tests over parse, write and validate. A threat model lists each threat with its test evidence. |
Addressing a field by identifier
A transposed positional index reads the wrong data element and still validates clean. Addressed by identifier, a wrong reference is an error:
use ;
static C082: & = &;
static NAD_ELEMENTS: & = &;
static NAD: SegmentDefinition = new;
let segs: = from_bytes.?;
assert_eq!;
assert_eq!;
assert!; // DE 2380 belongs to DTM
# Ok::
The derive performs the same resolution at compile time โ see Typed Derive.
Documentation
Guides: hupe1980.github.io/edifact.
Their Rust snippets are doctests: compiled and run, except no_run blocks
(file and network I/O), which are compiled only, and one ignored fragment.
| Guide | |
|---|---|
| Getting Started | Install, first parse, feature flags |
| Core Concepts | Wire format, UNA, release characters, repetitions, Rust type mapping |
| Character Sets | UNOAโUNOK/UNOY decoding, encoding, and repertoire validation |
| Parsing | Entry points, byte spans, and the ReaderConfig budgets |
| Writing | Writer, interchange and message builders, escaping, custom UNA, repeating elements |
| Dates and Times | DTM values by UNCL 2379 format code: decode, compare, build, validate, time conversions |
| Typed Derive | Every derive attribute, including identifier-addressed fields |
| Streaming | Reader iterators, message windows, typed extraction |
| Validation | Validator, ValidationContext, the validation layers (envelope, syntax, charset, structure, code list, profile) |
| Segment Groups | Group trees, ordered groups, placements, group-scoped rules |
| CONTRL | Acknowledgements and rejections from a validation report |
| Profile Packs | Authoring, composing, and filtering business rules |
| Diagnostics | miette integration |
| Async Integration | Bridging to tokio |
| Error Reference | Every stable code: E001โE061, E066โE072 |
| Performance | Allocation budget, memory bounds, benchmarks, tuning |
The threat model covers hostile input, structure injection on write and false acknowledgements, each with status and test evidence. Report vulnerabilities as described in SECURITY.md.
Runnable cookbooks: crates/edifact/examples/, e.g.
cargo run --example cookbook_parse_map_validate_write.
Scope
edifact is the engine, not a directory distribution.
It ships the parser, writer, validation pipeline, the table types for segment
definitions, and the batch service segments of ISO 9735 as layouts in
edifact::service: UNB, UNG, UNH, UNT, UNE, UNZ, UNS, UNO,
UNP, UGH, UGT, and the CONTRL segments UCI, UCM, UCF, UCS,
UCD. The syntax standard fixes them, so there is no version to pick:
use ;
let segments: = from_bytes
.?;
// DE 0020 by name, not by counting to element 4.
assert_eq!;
# Ok::
An interchange is built from a typed header, with the counts computed:
use ;
let header = new;
let mut msg = new?;
msg.write_simple?;
let bytes = new.message_segments.build?;
assert_eq!;
# Ok::
It also ships CONTRL (ISO 9735-4), generated from a validation report:
use ;
let raw = b"UNB+UNOC:3+SENDER+RECEIVER+260101:0900+IC4711'\
UNH+MSG1+ORDERS:D:96A:UN'BGM+220+PO-1+9'UNT+3+MSG1'\
UNZ+1+IC4711'";
let segments: = from_bytes.?;
let validated = validate_envelope?;
let wire = acknowledgement
.to_interchange_string?;
// Its own interchange, addressed back the way it came.
assert!;
assert!;
# Ok::
It does not ship UN/EDIFACT directory data (BGM, DTM, NAD, C507, โฆ):
the UN UNTDID licence
forbids distributing modified copies without UNECE's written permission, and
this crate reads derived tables as such. Supply the subset you use as static
tables or load it with DirectoryValidatorBuilder, then check it with
SegmentLayout::audit.
Not covered: interactive EDI (ISO 9735-3), the security segments and messages
(parts 5, 6, 7, 9). Packages (ยง7.10) are recognised, not parsed: the UNO
header gives the object's length and the bytes are yours.
Development
The justfile mirrors CI, so a green just ci means a green build:
A breaking change to edifact's public API (cargo-semver-checks against the
last release) needs the next minor version and a CHANGELOG migration note.
edifact-derive is covered by its UI suite.
MSRV and edition
Rust 1.88, edition 2024, checked by CI. Raising the MSRV is a breaking change.
License
Dual-licensed under either of
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT license (LICENSE-MIT)
at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this work shall be dual-licensed as above, without any additional terms or conditions.