edifact_rs/lib.rs
1#![cfg_attr(docsrs, feature(doc_cfg))]
2
3//! `edifact-rs` — zero-copy EDIFACT tokenizer, parser, writer, serde traits,
4//! validation engine, and extensible directory support.
5//!
6//! `edifact-rs` is the main entry point of this workspace. The core parsing,
7//! writing, and validation infrastructure is always available. Custom directory
8//! validators can be implemented by downstream crates or generated through
9//! external build tooling.
10//!
11//! # Quick start
12//! ```
13//! use edifact_rs::from_bytes;
14//! let input = b"UNB+UNOA:1+SENDER+RECEIVER+200101:0900+1'UNZ+0+1'";
15//! let segments: Vec<_> = from_bytes(input).collect::<Result<_, _>>().unwrap();
16//! assert_eq!(segments[0].tag, "UNB");
17//! ```
18//!
19//! # Crate features
20//!
21//! - `derive` (enabled by default): re-exports the derive macros from
22//! `edifact-rs-derive`.
23//! - `diagnostics` (disabled by default): enables rich diagnostic output via `miette`.
24//! When enabled, errors implement `miette::Diagnostic` for enhanced error reporting.
25//! This feature adds an optional dependency and has no impact on parsing performance.
26//!
27//! The crate is expected to compile both with defaults and with
28//! `--no-default-features` for consumers who only want the core parsing and
29//! writing functionality.
30//!
31//! ## Feature matrix workflows
32//!
33//! - default features:
34//! `cargo test -p edifact-rs`
35//! - no default features:
36//! `cargo test -p edifact-rs --no-default-features`
37//! - all features:
38//! `cargo test -p edifact-rs --all-features`
39//!
40//! # Diagnostic Feature
41//!
42//! When the `diagnostics` feature is enabled, [`EdifactError`] gains additional
43//! traits and methods that enable rich, human-readable error output:
44//!
45//! ```text
46//! Error: invalid delimiter byte 0xAB at offset 42
47//!
48//! ╭─ input.edi:2:3
49//! │
50//! 2 │ UNB+UNOA:1+....[invalid]...
51//! │ ^^^ invalid byte here
52//! │
53//! Error Code: E002
54//! Help: The byte 0xAB is not a valid delimiter. Check UNA configuration
55//! ```
56//!
57//! This feature is useful for CLI tools and error reporting, but is not required
58//! for applications that handle errors programmatically.
59//!
60//! # Parse And Text Contracts
61//!
62//! Parsing in `edifact-rs` is strict and deterministic:
63//!
64//! - Segment and element text must decode as UTF-8 (`E003` on failure).
65//! - Release characters must escape exactly one following byte.
66//! A trailing `?` at end-of-input is rejected (`E019`).
67//! - Malformed delimiters and truncated segments are reported with stable
68//! error codes rather than panicking.
69//!
70//! These contracts apply to both slice-based parsing (`from_bytes`) and
71//! reader-based parsing (`from_reader`).
72//!
73//! ```
74//! use edifact_rs::from_reader;
75//! use std::io::Cursor;
76//!
77//! let input = b"UNA:;.? 'BGM;220;test?;value'";
78//! let segments = from_reader(Cursor::new(&input[..])).unwrap();
79//! assert_eq!(segments.len(), 1);
80//! assert_eq!(segments[0].tag, "BGM");
81//! assert_eq!(segments[0].elements[0].components[0], "220");
82//! assert_eq!(segments[0].elements[1].components[0], "test;value");
83//! ```
84//!
85//! # Validation Quick Start
86//!
87//! The `Validator` trait and `ValidationContext` provide a flexible framework
88//! for building custom validators. Users can generate validators from official
89//! UNECE sources or implement their own.
90//!
91//! See the [`Validator`] trait documentation and the `cookbook_fixture_validation.rs`
92//! example for details on creating custom validators.
93//!
94//! # Custom Profile Packs
95//!
96//! `ProfileRulePack` is the extension point for downstream MIG/profile crates.
97//! Packs can be authored with public APIs only and plugged into a
98//! [`ValidationContext`]:
99//!
100//! ```
101//! use edifact_rs::{
102//! from_bytes, ProfileRulePack, ValidationContext, ValidationIssue, ValidationSeverity,
103//! };
104//!
105//! let segments: Vec<_> = from_bytes(b"UNH+1+ORDERS:D:96A:UN'BGM+220+PO123+9'UNT+3+1'")
106//! .collect::<Result<_, _>>()?;
107//!
108//! let pack = ProfileRulePack::builder("ORDERS-DEMO")
109//! .for_message_type("ORDERS")
110//! .with_rule_fn(|segments| {
111//! let bgm = segments.iter().find(|segment| segment.tag == "BGM")?;
112//! let document_code = bgm.get_element(0)?.get_component(0)?;
113//! (document_code == "220").then(|| {
114//! ValidationIssue::new(
115//! ValidationSeverity::Warning,
116//! "demo pack rejects BGM 220 for illustration",
117//! )
118//! .with_rule_id("DEMO-P001")
119//! .with_segment("BGM")
120//! .with_element_index(0)
121//! })
122//! });
123//!
124//! let report = ValidationContext::builder()
125//! .with_profile_pack(pack)
126//! .build()
127//! .validate_lenient(&segments);
128//!
129//! assert!(report.has_warnings());
130//! let partner_report = report.filter_by_rule_prefix("DEMO-");
131//! assert!(partner_report.total_issues() >= 1);
132//! # Ok::<(), edifact_rs::EdifactError>(())
133//! ```
134//!
135//! # Async Usage
136//!
137//! `edifact-rs` does not provide a native `async` API. All parsing is
138//! synchronous and driven by the standard `std::io::Read` / `std::io::BufRead`
139//! traits. The recommended integration pattern with async runtimes is:
140//!
141//! 1. Use your async runtime's read utilities to read the entire message into a
142//! `Vec<u8>` (e.g. `tokio::io::AsyncReadExt::read_to_end`).
143//! 2. Parse the in-memory slice with [`from_bytes`].
144//!
145//! ```rust,no_run
146//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
147//! // With tokio:
148//! // let mut buf = Vec::new();
149//! // reader.read_to_end(&mut buf).await?;
150//! // let segments: Vec<_> = edifact_rs::from_bytes(&buf).collect::<Result<_, _>>()?;
151//! # Ok(())
152//! # }
153//! ```
154//!
155//! A native zero-copy streaming async API is tracked as a future roadmap item.
156// ── core modules ──────────────────────────────────────────────────────────────
157pub mod directory_validator;
158pub(crate) mod envelope;
159/// Error types and validation reporting primitives.
160pub(crate) mod error;
161/// Core zero-copy and owned EDIFACT data model types.
162pub(crate) mod model;
163pub(crate) mod parser;
164pub(crate) mod tokenizer;
165pub(crate) mod validator;
166pub(crate) mod writer;
167
168// ── typed serialization layer ─────────────────────────────────────────────────
169pub mod de;
170pub(crate) mod event;
171pub mod ser;
172
173// ── flat re-exports: core ─────────────────────────────────────────────────────
174pub use envelope::validate_envelope;
175pub use error::{EdifactError, IoError, ValidationIssue, ValidationReport, ValidationSeverity};
176pub use model::{BorrowedElement, BorrowedSegment, Element, OwnedElement, OwnedSegment, Segment, Span};
177pub use parser::{
178 Parser, ReaderConfig, from_bufread, from_bufread_stream, from_bufread_stream_with_config,
179 from_reader_with_config,
180};
181pub use tokenizer::{ServiceStringAdvice, Tokenizer};
182pub use validator::{
183 ProfileRule, ProfileRulePack, ValidationContext, ValidationContextBuilder, ValidationLayer,
184 Validator, validate_each,
185};
186pub use writer::Writer;
187
188// ── flat re-exports: serde ────────────────────────────────────────────────────
189
190/// User-facing deserialization API.
191pub use de::{
192 CompositeElement, EdifactCompositeDeserialize, EdifactDeserialize, EdifactSegmentTag,
193 MessageWindowsIter, MessageWindowsSliceIter, SegmentAccessor,
194 deserialize, deserialize_all_from_reader,
195 deserialize_all_streaming, deserialize_first_from_reader, deserialize_first_streaming,
196 deserialize_messages_bytes, deserialize_messages_from_reader, deserialize_str,
197 groups_are_contiguous_by_qualifier,
198 message_windows_bytes, message_windows_from_reader,
199};
200
201/// Low-level helper functions for working with raw segments.
202///
203/// These are also used internally by `#[derive(EdifactDeserialize)]` generated code.
204pub mod helpers {
205 pub use crate::de::{
206 composite_element, contiguous_groups_by_qualifier, element_str,
207 find_qualified_segment, find_qualified_segment_owned, find_segment, find_segment_owned,
208 find_segment_typed, find_segments_iter, find_segments_typed, get_components_iter,
209 optional_component, optional_element, qualifier_matches_pattern,
210 required_component, required_element,
211 };
212}
213
214// Re-export helpers at root with doc(hidden) for macro-generated code compatibility.
215#[doc(hidden)]
216pub use de::{
217 composite_element, contiguous_groups_by_qualifier, element_str,
218 find_qualified_segment, find_qualified_segment_owned, find_segment, find_segment_owned,
219 find_segment_typed, find_segments_iter, find_segments_typed, get_components_iter,
220 optional_component, optional_element, qualifier_matches_pattern,
221 required_component, required_element,
222};
223#[cfg(feature = "derive")]
224#[cfg_attr(docsrs, doc(cfg(feature = "derive")))]
225pub use edifact_rs_derive::{EdifactDeserialize, EdifactSerialize};
226pub use event::{EdifactEvent, EventEmitter, OwnedEdifactEvent, VecEmitter, WriterEmitter};
227pub use ser::{EdifactCompositeSerialize, EdifactSerialize, to_bytes, to_edifact_string};
228pub use directory_validator::{DirectoryValidator, ElementRef, SegmentDefinition, Status};
229
230// ── core free functions ───────────────────────────────────────────────────────
231
232use std::io::{Read, Write};
233
234/// Iterator returned by [`from_bytes`].
235pub struct FromBytesIter<'a> {
236 parser: Option<parser::Parser<'a>>,
237 pending_error: Option<EdifactError>,
238}
239
240/// Iterator returned by [`from_reader_iter`].
241pub struct FromReaderIter<R: Read> {
242 inner: parser::OwnedSegmentStream<std::io::BufReader<R>>,
243}
244
245impl<R: Read> Iterator for FromReaderIter<R> {
246 type Item = Result<OwnedSegment, EdifactError>;
247
248 fn next(&mut self) -> Option<Self::Item> {
249 self.inner.next()
250 }
251}
252
253impl<'a> Iterator for FromBytesIter<'a> {
254 type Item = Result<Segment<'a>, EdifactError>;
255
256 fn next(&mut self) -> Option<Self::Item> {
257 if let Some(err) = self.pending_error.take() {
258 return Some(Err(err));
259 }
260 self.parser.as_mut()?.next()
261 }
262}
263
264/// Parse `input` bytes into an iterator of [`Segment`]s.
265///
266/// Borrows directly from `input` — zero allocation for segment data.
267pub fn from_bytes(input: &[u8]) -> FromBytesIter<'_> {
268 match tokenizer::ServiceStringAdvice::from_bytes_strict(input) {
269 Ok(ssa) => {
270 let t = tokenizer::Tokenizer::new(input, ssa);
271 FromBytesIter {
272 parser: Some(parser::Parser::new(t)),
273 pending_error: None,
274 }
275 }
276 Err(error) => FromBytesIter {
277 parser: None,
278 pending_error: Some(error),
279 },
280 }
281}
282
283/// Parse a reader into owned segments.
284///
285/// # Errors
286///
287/// Returns an error if the input contains malformed EDIFACT syntax,
288/// invalid UTF-8 segment text, dangling release sequences, or underlying I/O failures.
289pub fn from_reader<R: Read>(reader: R) -> Result<Vec<OwnedSegment>, EdifactError> {
290 parser::from_reader(reader)
291}
292
293/// Parse a reader into owned segments as a streaming iterator.
294///
295/// This keeps memory bounded by yielding segments incrementally instead of
296/// materializing the full interchange up front.
297pub fn from_reader_iter<R: Read>(reader: R) -> FromReaderIter<R> {
298 FromReaderIter {
299 inner: parser::from_reader_stream(reader),
300 }
301}
302
303/// Serialize `segments` to an [`std::io::Write`] implementation.
304///
305/// # Errors
306///
307/// Returns an error if writing fails or if segment serialization fails.
308pub fn to_writer<'a, 'b, W, I>(w: W, segments: I) -> Result<(), EdifactError>
309where
310 'b: 'a,
311 W: Write,
312 I: IntoIterator<Item = &'a Segment<'b>>,
313{
314 let mut wr = writer::Writer::new(w);
315 for seg in segments {
316 wr.write_segment(seg)?;
317 }
318 wr.finish().map(|_| ())
319}
320
321/// Serialize `segments` to an owned `Vec<u8>`.
322///
323/// # Errors
324///
325/// Returns an error if serialization fails.
326pub fn segments_to_bytes<'a, 'b, I>(segments: I) -> Result<Vec<u8>, EdifactError>
327where
328 'b: 'a,
329 I: IntoIterator<Item = &'a Segment<'b>>,
330{
331 let mut buf = Vec::new();
332 to_writer(&mut buf, segments)?;
333 Ok(buf)
334}
335
336#[cfg(test)]
337mod tests {
338 use super::*;
339
340 #[test]
341 fn from_bytes_rejects_invalid_una() {
342 let err = from_bytes(b"UNA::.? 'BGM:220'")
343 .collect::<Result<Vec<_>, _>>()
344 .expect_err("invalid UNA should fail slice parsing");
345 assert!(matches!(err, EdifactError::InvalidUna));
346 }
347}