Skip to main content

edifact_rs/
de.rs

1//! Custom deserialization trait for EDIFACT.
2//!
3//! [`EdifactDeserialize`] maps a slice of parsed [`Segment`]s to a Rust value.
4//! [`EdifactSegmentTag`] is a companion trait that carries the segment tag and
5//! optional qualifier at the type level, enabling the blanket
6//! `impl EdifactDeserialize for Vec<T>`.
7
8use crate::{EdifactError, Segment};
9use std::borrow::Cow;
10use std::io::Read;
11use std::str::FromStr;
12
13// ── traits ────────────────────────────────────────────────────────────────────
14
15/// Types that can be deserialized from a slice of EDIFACT segments.
16///
17/// Implement manually or derive with `#[derive(EdifactDeserialize)]` from the
18/// `edifact-rs-derive` crate.
19pub trait EdifactDeserialize: Sized {
20    /// Deserialize `Self` from the provided segment slice.
21    ///
22    /// The slice may contain any number of segments; implementations extract
23    /// only the ones they care about and ignore the rest.
24    fn edifact_deserialize(segments: &[Segment<'_>]) -> Result<Self, EdifactError>;
25
26    /// Deserialize `Self` from a slice of owned EDIFACT segments.
27    ///
28    /// # Default implementation
29    ///
30    /// Converts each [`crate::OwnedSegment`] to its borrowed form via
31    /// [`crate::OwnedSegment::as_borrowed`] and delegates to
32    /// [`edifact_deserialize`][Self::edifact_deserialize].  This incurs one
33    /// `Vec<Segment<'_>>` allocation per call.
34    ///
35    /// # Warning: allocation overhead
36    ///
37    /// This default implementation incurs one [`Vec<Segment<'_>>`](Vec)
38    /// allocation per call.  Types generated by `#[derive(EdifactDeserialize)]`
39    /// automatically override this method to work directly on the owned data
40    /// without the intermediate allocation.  Manual implementations should also
41    /// override when used in the high-throughput reader-streaming path
42    /// ([`deserialize_first_from_reader`], [`deserialize_all_from_reader`],
43    /// [`deserialize_messages_from_reader`]) to avoid the per-message allocation.
44    fn edifact_deserialize_owned(segments: &[crate::OwnedSegment]) -> Result<Self, EdifactError> {
45        let borrowed: Vec<Segment<'_>> = segments.iter().map(|s| s.as_borrowed()).collect();
46        Self::edifact_deserialize(&borrowed)
47    }
48}
49
50/// Types that can be deserialized from a composite EDIFACT element.
51///
52/// Implement this for custom composite structs used with
53/// `#[edifact(composite)]` in derive macros.
54pub trait EdifactCompositeDeserialize: Sized {
55    /// Deserialize `Self` from a composite element.
56    fn edifact_deserialize_composite(composite: CompositeElement<'_>)
57    -> Result<Self, EdifactError>;
58}
59
60impl EdifactCompositeDeserialize for Vec<String> {
61    fn edifact_deserialize_composite(
62        composite: CompositeElement<'_>,
63    ) -> Result<Self, EdifactError> {
64        Ok(composite.iter().map(str::to_owned).collect())
65    }
66}
67
68/// Companion trait that declares a type's segment tag (and optional qualifier).
69///
70/// Required for the `Vec<T>` blanket impl and for finding the right segment in
71/// a message-level struct deserialization.
72pub trait EdifactSegmentTag {
73    /// The 3-character EDIFACT segment tag (e.g. `"BGM"`, `"NAD"`).
74    const SEGMENT_TAG: &'static str;
75
76    /// Optional qualifier pattern to further constrain segment matching.
77    ///
78    /// Examples:
79    /// - `Some("MS")` for exact qualifier matching.
80    /// - `Some("M*")` for wildcard prefix matching (matches `"MS"`, `"MR"`, etc.).
81    const QUALIFIER_PATTERN: Option<&'static str> = None;
82
83    /// Return `true` if `seg`'s qualifier matches this type's qualifier pattern.
84    fn matches_qualifier(seg: &Segment<'_>) -> bool {
85        match Self::QUALIFIER_PATTERN {
86            Some(pattern) => seg
87                .element_str(0)
88                .is_some_and(|q| qualifier_matches_pattern(q, pattern)),
89            None => true,
90        }
91    }
92
93    /// Return `true` if `seg` is the segment this type maps to.
94    ///
95    /// Default: `seg.tag == Self::SEGMENT_TAG`.  Override to also match on a
96    /// qualifier (e.g. `NAD+BY` — element 0 = `"BY"`).
97    fn matches_segment(seg: &Segment<'_>) -> bool {
98        seg.tag == Self::SEGMENT_TAG && Self::matches_qualifier(seg)
99    }
100
101    /// Like [`matches_segment`][Self::matches_segment] but works directly on an
102    /// [`crate::OwnedSegment`] without incurring the `Vec` allocation of
103    /// [`crate::OwnedSegment::as_borrowed`].
104    fn matches_owned_segment(seg: &crate::OwnedSegment) -> bool {
105        if seg.tag != Self::SEGMENT_TAG {
106            return false;
107        }
108        match Self::QUALIFIER_PATTERN {
109            None => true,
110            Some(pattern) => {
111                let q = seg
112                    .elements
113                    .first()
114                    .and_then(|e| e.components.first())
115                    .map(|(c, _)| c.as_str())
116                    .unwrap_or("");
117                qualifier_matches_pattern(q, pattern)
118            }
119        }
120    }
121}
122
123// ── blanket impl for Vec<T> ───────────────────────────────────────────────────
124
125/// Deserializes each segment matching `T::matches_segment` as an independent
126/// single-segment slice, collecting the results.
127impl<T> EdifactDeserialize for Vec<T>
128where
129    T: EdifactDeserialize + EdifactSegmentTag,
130{
131    fn edifact_deserialize(segments: &[Segment<'_>]) -> Result<Self, EdifactError> {
132        segments
133            .iter()
134            .filter(|s| T::matches_segment(s))
135            .map(|seg| T::edifact_deserialize(std::slice::from_ref(seg)))
136            .collect()
137    }
138
139    fn edifact_deserialize_owned(segments: &[crate::OwnedSegment]) -> Result<Self, EdifactError> {
140        segments
141            .iter()
142            .filter(|s| T::matches_owned_segment(s))
143            .map(|seg| T::edifact_deserialize_owned(std::slice::from_ref(seg)))
144            .collect()
145    }
146}
147
148// ── public API ────────────────────────────────────────────────────────────────
149
150/// Deserialize a value of type `T` from EDIFACT bytes.
151///
152/// Unlike [`crate::from_bytes`], which parses bytes into raw [`Segment`]s, this
153/// function fully deserializes the payload into a typed Rust value via [`EdifactDeserialize`].
154///
155/// # Memory
156///
157/// This function buffers **all** parsed segments into a `Vec<Segment<'_>>` before
158/// calling `T::edifact_deserialize`.  For large interchanges — or when only the first
159/// matching segment is needed — prefer [`deserialize_first_streaming`] or
160/// [`deserialize_all_streaming`] to avoid holding the entire input in memory.
161/// For reader-based I/O with bounded memory use, see [`deserialize_first_from_reader`]
162/// and [`deserialize_all_from_reader`].
163pub fn deserialize<T: EdifactDeserialize>(input: &[u8]) -> Result<T, EdifactError> {
164    let segments: Vec<Segment<'_>> = crate::from_bytes(input).collect::<Result<_, _>>()?;
165    T::edifact_deserialize(&segments)
166}
167
168/// Stream-parse EDIFACT bytes and deserialize the first matching segment as `T`.
169///
170/// This avoids allocating a full `Vec<Segment>` and is intended for low-memory
171/// extraction of segment-scoped types.
172pub fn deserialize_first_streaming<T>(input: &[u8]) -> Result<T, EdifactError>
173where
174    T: EdifactDeserialize + EdifactSegmentTag,
175{
176    for segment in crate::from_bytes(input) {
177        let segment = segment?;
178        if T::matches_segment(&segment) {
179            return T::edifact_deserialize(std::slice::from_ref(&segment));
180        }
181    }
182
183    Err(EdifactError::MissingSegment {
184        tag: T::SEGMENT_TAG.to_owned(),
185        expected_position: "any position in input".to_owned(),
186    })
187}
188
189/// Stream-parse EDIFACT bytes and deserialize all matching segments as `Vec<T>`.
190///
191/// This avoids buffering non-matching segments in memory.
192pub fn deserialize_all_streaming<T>(input: &[u8]) -> Result<Vec<T>, EdifactError>
193where
194    T: EdifactDeserialize + EdifactSegmentTag,
195{
196    let mut out = Vec::new();
197    for segment in crate::from_bytes(input) {
198        let segment = segment?;
199        if T::matches_segment(&segment) {
200            out.push(T::edifact_deserialize(std::slice::from_ref(&segment))?);
201        }
202    }
203    Ok(out)
204}
205
206/// Stream-parse EDIFACT from a reader and deserialize the first matching segment as `T`.
207///
208/// This is the low-memory typed path for large payloads read from I/O streams.
209pub fn deserialize_first_from_reader<T, R>(reader: R) -> Result<T, EdifactError>
210where
211    T: EdifactDeserialize + EdifactSegmentTag,
212    R: Read,
213{
214    for segment in crate::from_reader(reader) {
215        let segment = segment?;
216        // O(1) tag + qualifier check before paying for as_borrowed().
217        if !T::matches_owned_segment(&segment) {
218            continue;
219        }
220        return T::edifact_deserialize_owned(std::slice::from_ref(&segment));
221    }
222
223    Err(EdifactError::MissingSegment {
224        tag: T::SEGMENT_TAG.to_owned(),
225        expected_position: "any position in input".to_owned(),
226    })
227}
228
229/// Stream-parse EDIFACT from a reader and deserialize all matching segments as `Vec<T>`.
230pub fn deserialize_all_from_reader<T, R>(reader: R) -> Result<Vec<T>, EdifactError>
231where
232    T: EdifactDeserialize + EdifactSegmentTag,
233    R: Read,
234{
235    let mut out = Vec::new();
236    for segment in crate::from_reader(reader) {
237        let segment = segment?;
238        // O(1) tag + qualifier check before paying for as_borrowed().
239        if !T::matches_owned_segment(&segment) {
240            continue;
241        }
242        out.push(T::edifact_deserialize_owned(std::slice::from_ref(
243            &segment,
244        ))?);
245    }
246    Ok(out)
247}
248
249/// Deserialize a value of type `T` from an EDIFACT string.
250pub fn deserialize_str<T: EdifactDeserialize>(input: &str) -> Result<T, EdifactError> {
251    deserialize(input.as_bytes())
252}
253
254// ── helper functions ──────────────────────────────────────────────────────────
255
256/// Find the first segment with the given tag.
257pub fn find_segment<'s, 'd>(segments: &'s [Segment<'d>], tag: &str) -> Option<&'s Segment<'d>> {
258    segments.iter().find(|s| s.tag == tag)
259}
260
261/// Iterate over all segments with the given tag without allocating a `Vec`.
262pub fn find_segments_iter<'s, 'd: 's>(
263    segments: &'s [Segment<'d>],
264    tag: &'s str,
265) -> impl Iterator<Item = &'s Segment<'d>> {
266    segments.iter().filter(move |s| s.tag == tag)
267}
268
269/// Find the first segment matching `tag` whose element 0 equals `qualifier`.
270pub fn find_qualified_segment<'s, 'd>(
271    segments: &'s [Segment<'d>],
272    tag: &str,
273    qualifier: &str,
274) -> Option<&'s Segment<'d>> {
275    segments
276        .iter()
277        .find(|s| s.tag == tag && s.element_str(0).unwrap_or("") == qualifier)
278}
279
280/// Find the first segment by type-level qualifier pattern.
281pub fn find_segment_typed<'s, 'd, T>(segments: &'s [Segment<'d>]) -> Option<&'s Segment<'d>>
282where
283    T: EdifactSegmentTag,
284{
285    segments.iter().find(|s| T::matches_segment(s))
286}
287
288/// Iterate over all segments by type-level qualifier pattern.
289pub fn find_segments_typed<'s, 'd: 's, T>(
290    segments: &'s [Segment<'d>],
291) -> impl Iterator<Item = &'s Segment<'d>>
292where
293    T: EdifactSegmentTag,
294{
295    segments.iter().filter(|s| T::matches_segment(s))
296}
297
298/// Collect contiguous groups of segments that match `T`.
299///
300/// Each group is a borrowed slice of the original `segments` array.
301/// Use [`contiguous_groups_iter`] to avoid the outer `Vec` allocation.
302pub fn contiguous_groups_by_qualifier<'s, 'd, T>(
303    segments: &'s [Segment<'d>],
304) -> Vec<&'s [Segment<'d>]>
305where
306    T: EdifactSegmentTag,
307{
308    let mut groups = Vec::new();
309    let mut idx = 0;
310    while idx < segments.len() {
311        if T::matches_segment(&segments[idx]) {
312            let start = idx;
313            idx += 1;
314            while idx < segments.len() && T::matches_segment(&segments[idx]) {
315                idx += 1;
316            }
317            groups.push(&segments[start..idx]);
318        } else {
319            idx += 1;
320        }
321    }
322    groups
323}
324
325/// Iterate lazily over contiguous groups of segments that match `T`.
326///
327/// Each yielded item is a borrowed slice `&[Segment<'_>]` that forms one
328/// contiguous run of `T`-matching segments.  No outer `Vec` is allocated —
329/// the caller can break early or collect only as many groups as needed.
330///
331/// This function uses separate lifetimes for the slice reference (`'s`) and
332/// the segment data (`'d`), matching the signature of
333/// [`contiguous_groups_by_qualifier`].
334///
335/// # Example
336/// ```rust,ignore
337/// for group in contiguous_groups_iter::<UnaSegment>(&segments) {
338///     process_group(group);
339/// }
340/// ```
341pub fn contiguous_groups_iter<'s, 'd, T>(
342    segments: &'s [Segment<'d>],
343) -> impl Iterator<Item = &'s [Segment<'d>]> + 's
344where
345    T: EdifactSegmentTag,
346{
347    let mut idx = 0;
348    let len = segments.len();
349    std::iter::from_fn(move || {
350        // Skip non-matching segments
351        while idx < len && !T::matches_segment(&segments[idx]) {
352            idx += 1;
353        }
354        if idx >= len {
355            return None;
356        }
357        let start = idx;
358        idx += 1;
359        while idx < len && T::matches_segment(&segments[idx]) {
360            idx += 1;
361        }
362        Some(&segments[start..idx])
363    })
364}
365
366/// Return `true` if all segments matching `T` are in one contiguous block.
367pub fn groups_are_contiguous_by_qualifier<T>(segments: &[Segment<'_>]) -> bool
368where
369    T: EdifactSegmentTag,
370{
371    let mut seen_match = false;
372    let mut seen_gap_after_match = false;
373
374    for seg in segments {
375        if T::matches_segment(seg) {
376            if seen_gap_after_match {
377                return false;
378            }
379            seen_match = true;
380        } else if seen_match {
381            seen_gap_after_match = true;
382        }
383    }
384
385    true
386}
387
388/// Match a qualifier value against an exact or wildcard pattern.
389///
390/// Rules:
391/// - If `pattern` contains `*`, it is treated as a glob wildcard (e.g. `"M*"` matches `"MS"`, `"MR"`).
392/// - If no wildcard is present, exact match is required.
393///
394/// Prefix matching without an explicit `*` was deliberately removed: `"M"` matches only `"M"`,
395/// not `"MS"` or `"MR"`.  Use `"M*"` for prefix semantics.
396///
397/// Patterns with more than 3 wildcard segments (i.e. 4 or more `*` characters) are rejected
398/// immediately with `false` to guard against pathological O(n·m) matching.
399pub fn qualifier_matches_pattern(value: &str, pattern: &str) -> bool {
400    if pattern.is_empty() {
401        return value.is_empty();
402    }
403
404    if !pattern.contains('*') {
405        return value == pattern;
406    }
407
408    // Fast path: single wildcard (dominant case — e.g. "M*" or "*:MS")
409    if let Some((prefix, suffix)) = pattern.split_once('*') {
410        // Only one wildcard — prefix and suffix cannot overlap in a second split.
411        if !pattern[prefix.len() + 1..].contains('*') {
412            return value.len() >= prefix.len() + suffix.len()
413                && value.starts_with(prefix)
414                && value.ends_with(suffix)
415                && {
416                    // Ensure prefix and suffix don't overlap.
417                    let mid_start = prefix.len();
418                    let mid_end = value.len().saturating_sub(suffix.len());
419                    mid_start <= mid_end
420                };
421        }
422    }
423
424    // General multi-wildcard path.
425    let parts: smallvec::SmallVec<[&str; 4]> = pattern.split('*').collect();
426
427    // Guard against pathological O(n·m) matching on adversarial patterns.
428    // EDIFACT qualifier patterns use at most 1–2 wildcards; 4 is a generous
429    // ceiling. Anything beyond is almost certainly a programming error or
430    // adversarial input — reject immediately.
431    if parts.len() > 4 {
432        return false;
433    }
434
435    let prefix = parts[0];
436    let suffix = parts[parts.len() - 1];
437
438    if !value.starts_with(prefix) || !value.ends_with(suffix) {
439        return false;
440    }
441
442    let mid_start = prefix.len();
443    let mid_end = value.len().saturating_sub(suffix.len());
444
445    if mid_start > mid_end {
446        return parts[1..parts.len() - 1].iter().all(|p| p.is_empty());
447    }
448
449    let mut remaining = &value[mid_start..mid_end];
450
451    for part in &parts[1..parts.len() - 1] {
452        if part.is_empty() {
453            continue;
454        }
455        match remaining.find(part) {
456            Some(idx) => remaining = &remaining[idx + part.len()..],
457            None => return false,
458        }
459    }
460
461    true
462}
463
464/// Extract the string value of element `idx` from `seg`, or `""` if absent.
465#[inline]
466pub fn element_str<'s>(seg: &'s Segment<'_>, idx: usize) -> &'s str {
467    seg.element_str(idx).unwrap_or("")
468}
469
470// ── segment accessor helpers ───────────────────────────────────────────────────
471
472/// Extract a required text element from a segment.
473///
474/// Returns the element's first component, or an error if absent or empty.
475///
476/// # Empty-string semantics
477///
478/// EDIFACT allows elements to be syntactically present but carry an empty
479/// string value (e.g., `SEG++'`). This function treats an empty string as
480/// *absent* — it returns [`EdifactError::MissingRequiredElement`] in that
481/// case, matching the EDIFACT rule that mandatory data elements must carry
482/// a non-empty value.
483///
484/// Delegates to [`SegmentAccessor::text_element`].
485pub fn required_element<'a>(seg: &'a Segment<'_>, idx: usize) -> Result<&'a str, EdifactError> {
486    seg.text_element(idx)
487}
488
489/// Extract an optional text element from a segment.
490///
491/// Returns the element's first component, or None if absent or empty.
492///
493/// Delegates to [`SegmentAccessor::optional_element`].
494pub fn optional_element<'a>(seg: &'a Segment<'_>, idx: usize) -> Option<&'a str> {
495    SegmentAccessor::optional_element(seg, idx)
496}
497
498/// Extract a required component from a segment element.
499///
500/// Returns the component value, or an error if the element or component is absent.
501///
502/// # Empty-string semantics
503///
504/// Like [`required_element`], an empty string component value is treated as
505/// *absent*.  A component that is syntactically present as `''` (two
506/// consecutive component separators) will cause this function to return
507/// [`EdifactError::MissingRequiredComponent`].
508///
509/// # Failure modes
510///
511/// - [`EdifactError::MissingRequiredElement`] — element `elem_idx` is absent.
512/// - [`EdifactError::MissingRequiredComponent`] — element is present but component `comp_idx` is absent or empty.
513///
514/// Delegates to [`SegmentAccessor::required_composite`].
515pub fn required_component<'a>(
516    seg: &'a Segment<'_>,
517    elem_idx: usize,
518    comp_idx: usize,
519) -> Result<&'a str, EdifactError> {
520    seg.required_composite(elem_idx, comp_idx)
521}
522
523/// Extract an optional component from a segment element.
524///
525/// Returns the component value, or None if absent or empty.
526///
527/// Delegates to [`SegmentAccessor::get_component`].
528pub fn optional_component<'a>(
529    seg: &'a Segment<'_>,
530    elem_idx: usize,
531    comp_idx: usize,
532) -> Option<&'a str> {
533    SegmentAccessor::get_component(seg, elem_idx, comp_idx)
534}
535
536/// Iterate over all components of an element without allocating a `Vec`.
537///
538/// Yields an empty iterator if the element is absent.
539pub fn get_components_iter<'a>(seg: &'a Segment<'_>, idx: usize) -> impl Iterator<Item = &'a str> {
540    seg.elements
541        .get(idx)
542        .into_iter()
543        .flat_map(|elem| elem.components.iter().map(|(c, _)| c.as_ref()))
544}
545
546/// A composite data element wrapper for clearer ergonomics.
547///
548/// Holds borrowed `&'a str` references to the underlying data — no string
549/// copies are made.  Up to 4 component pointers are stored inline (via
550/// [`SmallVec`]) so the common case is fully allocation-free.
551///
552/// The lifetime `'a` represents the underlying data lifetime.
553///
554/// [`SmallVec`]: smallvec::SmallVec
555pub struct CompositeElement<'a> {
556    components: smallvec::SmallVec<[&'a str; 4]>,
557}
558
559impl<'a> CompositeElement<'a> {
560    /// Create a `CompositeElement` from a pre-existing `Cow` component slice.
561    ///
562    /// Used internally by generated owned-deserialization code.
563    pub fn from_slice(components: &'a [std::borrow::Cow<'a, str>]) -> Self {
564        Self {
565            components: components.iter().map(|c| c.as_ref()).collect(),
566        }
567    }
568
569    /// Crate-private constructor for direct `&str` components.
570    pub(crate) fn from_strs(components: smallvec::SmallVec<[&'a str; 4]>) -> Self {
571        Self { components }
572    }
573
574    /// Get the component at index `i`, or None if absent.
575    pub fn get(&self, i: usize) -> Option<&'a str> {
576        self.components.get(i).copied()
577    }
578
579    /// Get the component at index `i`, or empty string if absent.
580    pub fn get_or_empty(&self, i: usize) -> &'a str {
581        self.get(i).unwrap_or("")
582    }
583
584    /// Get the number of components.
585    pub fn len(&self) -> usize {
586        self.components.len()
587    }
588
589    /// Check if the composite is empty.
590    pub fn is_empty(&self) -> bool {
591        self.components.is_empty()
592    }
593
594    /// Iterate over all component string values.
595    pub fn iter(&self) -> impl Iterator<Item = &'a str> + '_ {
596        self.components.iter().copied()
597    }
598}
599
600/// Get a composite element from a segment with clearer ergonomics.
601pub fn composite_element<'a, 'd: 'a>(
602    seg: &'a Segment<'d>,
603    idx: usize,
604) -> Option<CompositeElement<'a>> {
605    // `.collect()` into `SmallVec<[&str; 4]>` keeps ≤4-component elements
606    // fully on the stack (no heap allocation for the common case).
607    seg.elements.get(idx).map(|elem| {
608        CompositeElement::from_strs(elem.components.iter().map(|(c, _)| c.as_ref()).collect())
609    })
610}
611
612/// Find the first [`OwnedSegment`] with the given tag.
613///
614/// Zero-allocation counterpart of [`find_segment`] for use in
615/// [`EdifactDeserialize::edifact_deserialize_owned`] implementations.
616///
617/// [`OwnedSegment`]: crate::OwnedSegment
618pub fn find_segment_owned<'s>(
619    segments: &'s [crate::OwnedSegment],
620    tag: &str,
621) -> Option<&'s crate::OwnedSegment> {
622    segments.iter().find(|s| s.tag == tag)
623}
624
625/// Find the first [`OwnedSegment`] with the given tag **and** qualifier.
626///
627/// The qualifier is compared against the first component of element 0.
628/// Zero-allocation counterpart of [`find_qualified_segment`] for use in
629/// [`EdifactDeserialize::edifact_deserialize_owned`] implementations.
630///
631/// [`OwnedSegment`]: crate::OwnedSegment
632pub fn find_qualified_segment_owned<'s>(
633    segments: &'s [crate::OwnedSegment],
634    tag: &str,
635    qualifier: &str,
636) -> Option<&'s crate::OwnedSegment> {
637    segments
638        .iter()
639        .find(|s| s.tag == tag && s.element_str(0).unwrap_or("") == qualifier)
640}
641
642/// Segment accessor trait for ergonomic typed extraction.
643pub trait SegmentAccessor<'a> {
644    /// Get non-empty element text at index `idx`.
645    fn get_element(&'a self, idx: usize) -> Option<&'a str>;
646    /// Get non-empty component text at element/component indexes.
647    fn get_component(&'a self, elem: usize, comp: usize) -> Option<&'a str>;
648    /// Get a composite wrapper for element `idx`.
649    fn get_composite(&'a self, idx: usize) -> Option<CompositeElement<'a>>;
650
651    /// Get required non-empty element text.
652    fn text_element(&'a self, idx: usize) -> Result<&'a str, EdifactError>;
653    /// Get optional non-empty element text.
654    fn optional_element(&'a self, idx: usize) -> Option<&'a str>;
655    /// Parse a typed code value from a required element.
656    fn code_element<T: FromStr>(&'a self, idx: usize) -> Result<T, EdifactError>;
657    /// Get required non-empty composite component.
658    fn required_composite(&'a self, elem: usize, comp: usize) -> Result<&'a str, EdifactError>;
659    /// Get `count` required components starting at `start_idx` from element `elem`.
660    ///
661    /// Allocates a `Vec`.  For a zero-alloc alternative, use
662    /// [`repeating_components_iter`][Self::repeating_components_iter] and
663    /// consume the iterator directly without collecting.
664    fn repeating_components(
665        &'a self,
666        elem: usize,
667        start_idx: usize,
668        count: usize,
669    ) -> Result<Vec<&'a str>, EdifactError> {
670        // Default implementation delegates to the zero-alloc iterator and
671        // collects.  Implementors that can do better should override this.
672        self.repeating_components_iter(elem, start_idx, count)
673            .collect()
674    }
675
676    /// Iterate over `count` required components starting at `start_idx` from element `elem`.
677    ///
678    /// Allocation-free alternative to [`repeating_components`][Self::repeating_components];
679    /// the caller supplies the iteration budget and consumes results on the fly.
680    fn repeating_components_iter(
681        &'a self,
682        elem: usize,
683        start_idx: usize,
684        count: usize,
685    ) -> impl Iterator<Item = Result<&'a str, EdifactError>> + 'a;
686}
687
688impl<'s, 'd> SegmentAccessor<'s> for Segment<'d>
689where
690    'd: 's,
691{
692    fn get_element(&'s self, idx: usize) -> Option<&'s str> {
693        self.element_str(idx).filter(|s| !s.is_empty())
694    }
695
696    fn get_component(&'s self, elem: usize, comp: usize) -> Option<&'s str> {
697        self.elements
698            .get(elem)
699            .and_then(|e| e.get_component(comp))
700            .filter(|s| !s.is_empty())
701    }
702
703    fn get_composite(&'s self, idx: usize) -> Option<CompositeElement<'s>> {
704        composite_element(self, idx)
705    }
706
707    fn text_element(&'s self, idx: usize) -> Result<&'s str, EdifactError> {
708        <Self as SegmentAccessor>::get_element(self, idx).ok_or_else(|| {
709            EdifactError::MissingRequiredElement {
710                tag: self.tag.to_owned(),
711                element_index: idx,
712            }
713        })
714    }
715
716    fn optional_element(&'s self, idx: usize) -> Option<&'s str> {
717        <Self as SegmentAccessor>::get_element(self, idx)
718    }
719
720    fn code_element<T: FromStr>(&'s self, idx: usize) -> Result<T, EdifactError> {
721        let raw = self.text_element(idx)?;
722        raw.parse::<T>().map_err(|_| EdifactError::InvalidText {
723            offset: self
724                .element_span(idx)
725                .map(|s| s.start)
726                .unwrap_or(self.span.start),
727        })
728    }
729
730    fn required_composite(&'s self, elem: usize, comp: usize) -> Result<&'s str, EdifactError> {
731        match self.elements.get(elem) {
732            None => Err(EdifactError::MissingRequiredElement {
733                tag: self.tag.to_owned(),
734                element_index: elem,
735            }),
736            Some(e) => e
737                .get_component(comp)
738                .filter(|s| !s.is_empty())
739                .ok_or_else(|| EdifactError::MissingRequiredComponent {
740                    tag: self.tag.to_owned(),
741                    element_index: elem,
742                    component_index: comp,
743                }),
744        }
745    }
746
747    fn repeating_components_iter(
748        &'s self,
749        elem: usize,
750        start_idx: usize,
751        count: usize,
752    ) -> impl Iterator<Item = Result<&'s str, EdifactError>> + 's {
753        let tag = self.tag;
754        let element_exists = self.elements.get(elem).is_some();
755        let components = self
756            .elements
757            .get(elem)
758            .map(|e| e.components.as_slice())
759            .unwrap_or(&[]);
760        (start_idx..start_idx + count).map(move |idx| {
761            components
762                .get(idx)
763                .map(|(c, _)| c.as_ref())
764                .filter(|s| !s.is_empty())
765                .ok_or_else(|| {
766                    if element_exists {
767                        EdifactError::MissingRequiredComponent {
768                            tag: tag.to_owned(),
769                            element_index: elem,
770                            component_index: idx,
771                        }
772                    } else {
773                        EdifactError::MissingRequiredElement {
774                            tag: tag.to_owned(),
775                            element_index: elem,
776                        }
777                    }
778                })
779        })
780    }
781}
782
783// ── message-window streaming ──────────────────────────────────────────────────
784
785/// A complete `UNH..UNT` message window that borrows from the original input.
786///
787/// Produced by [`MessageWindowsSliceIter`] / [`message_windows_bytes`].
788/// The `message_type` and `association_code` fields are extracted from the
789/// `UNH` segment at construction time, so callers do not need to traverse the
790/// segment list themselves.
791///
792/// `segments` contains the full window including the `UNH` and `UNT` service
793/// segments so that envelope-aware consumers have access to them.
794///
795/// # Accessing segments
796///
797/// ```rust,ignore
798/// for window in message_windows_bytes(input) {
799///     let window = window?;
800///     println!("type={:?} code={:?}", window.message_type, window.association_code);
801///     let bgm = window.segments.iter().find(|s| s.tag == "BGM");
802/// }
803/// ```
804#[derive(Debug)]
805pub struct MessageWindow<'a> {
806    /// EDIFACT message type extracted from `UNH` element 1, component 0.
807    ///
808    /// Borrowed when the component can be referenced directly, owned when
809    /// release-character unescaping requires allocation.
810    pub message_type: Option<Cow<'a, str>>,
811    /// Association-assigned code (DE 0057) from `UNH` element 1, component 4.
812    ///
813    /// Borrowed when the component can be referenced directly, owned when
814    /// release-character unescaping requires allocation.
815    pub association_code: Option<Cow<'a, str>>,
816    /// All segments in this window, from `UNH` through `UNT` (inclusive).
817    pub segments: Vec<crate::Segment<'a>>,
818}
819
820impl<'a> MessageWindow<'a> {
821    /// Build a `MessageWindow` from a completed segment buffer.
822    ///
823    /// Extracts `message_type` and `association_code` from the leading `UNH`
824    /// segment.  Metadata extraction is allocation-free for borrowed components;
825    /// release-character unescaping may allocate owned strings when necessary.
826    fn from_segments(segments: Vec<crate::Segment<'a>>) -> Self {
827        let message_type = segments
828            .first()
829            .filter(|s| s.tag == "UNH")
830            .and_then(|unh| unh_component(unh, 0));
831        let association_code = segments
832            .first()
833            .filter(|s| s.tag == "UNH")
834            .and_then(|unh| unh_component(unh, 4));
835        Self {
836            message_type,
837            association_code,
838            segments,
839        }
840    }
841}
842
843/// Extract a non-empty string component from UNH element 1, preserving the
844/// component's borrowed/owned state.
845///
846/// By using two distinct lifetime parameters (`'b` for the borrow of `seg`,
847/// `'a` for the segment data), we tell the borrow checker that the returned
848/// `&'a str` lives independently of how long we hold `&seg`, which lets callers
849/// move `seg` into a containing struct after this call returns.
850fn unh_component<'a, 'b>(seg: &'b crate::Segment<'a>, comp_idx: usize) -> Option<Cow<'a, str>>
851where
852    'a: 'b,
853{
854    seg.elements
855        .get(1)
856        .and_then(|e| e.components.get(comp_idx))
857        .and_then(|(c, _)| if c.is_empty() { None } else { Some(c.clone()) })
858}
859
860/// An owned, heap-allocated `UNH..UNT` message window.
861///
862/// Produced by [`MessageWindowsIter`] / [`message_windows_from_reader`].
863/// Equivalent to [`MessageWindow`] but with all data owned, so it outlives
864/// the original reader.
865///
866/// `segments` contains the full window including the `UNH` and `UNT` service
867/// segments.
868#[derive(Debug, Clone)]
869pub struct OwnedMessageWindow {
870    /// EDIFACT message type extracted from `UNH` element 1, component 0.
871    pub message_type: Option<String>,
872    /// Association-assigned code (DE 0057) from `UNH` element 1, component 4.
873    pub association_code: Option<String>,
874    /// All segments in this window, from `UNH` through `UNT` (inclusive).
875    pub segments: Vec<crate::OwnedSegment>,
876}
877
878impl OwnedMessageWindow {
879    fn from_segments(segments: Vec<crate::OwnedSegment>) -> Self {
880        let unh = segments.first().filter(|s| s.tag == "UNH");
881        let message_type = unh
882            .and_then(|s| s.elements.get(1))
883            .and_then(|e| e.components.first())
884            .map(|(c, _)| c.as_str())
885            .filter(|s| !s.is_empty())
886            .map(str::to_owned);
887        let association_code = unh
888            .and_then(|s| s.elements.get(1))
889            .and_then(|e| e.components.get(4))
890            .map(|(c, _)| c.as_str())
891            .filter(|s| !s.is_empty())
892            .map(str::to_owned);
893        Self {
894            message_type,
895            association_code,
896            segments,
897        }
898    }
899}
900
901/// An iterator that groups borrowed EDIFACT segments into per-message windows.
902///
903/// Zero-copy counterpart to [`MessageWindowsIter`] for in-memory byte slices.
904/// Text content borrows from the original input; segment structure allocates
905/// element vectors during parsing. Release-character unescaping may further
906/// allocate owned strings when escape sequences are present. Envelope segments
907/// outside a `UNH..UNT` pair are silently skipped.
908///
909/// Obtain this via [`message_windows_bytes`].
910pub struct MessageWindowsSliceIter<'a> {
911    inner: crate::FromBytesIter<'a>,
912    buf: Vec<crate::Segment<'a>>,
913    in_message: bool,
914    done: bool,
915}
916
917impl<'a> MessageWindowsSliceIter<'a> {
918    fn new(inner: crate::FromBytesIter<'a>) -> Self {
919        Self {
920            inner,
921            buf: Vec::new(),
922            in_message: false,
923            done: false,
924        }
925    }
926}
927
928impl<'a> Iterator for MessageWindowsSliceIter<'a> {
929    type Item = Result<MessageWindow<'a>, EdifactError>;
930
931    fn next(&mut self) -> Option<Self::Item> {
932        if self.done {
933            return None;
934        }
935        loop {
936            let segment = match self.inner.next() {
937                Some(Ok(s)) => s,
938                Some(Err(e)) => {
939                    self.done = true;
940                    return Some(Err(e));
941                }
942                None => {
943                    self.done = true;
944                    if self.in_message && !self.buf.is_empty() {
945                        self.in_message = false;
946                        let offset = self.buf.last().map(|s| s.span.end).unwrap_or(0);
947                        return Some(Err(EdifactError::UnexpectedEof { offset }));
948                    }
949                    return None;
950                }
951            };
952
953            match segment.tag {
954                "UNH" => {
955                    if self.in_message {
956                        self.buf.clear();
957                        self.in_message = false;
958                        self.done = true;
959                        return Some(Err(EdifactError::InvalidSegmentForMessage {
960                            tag: "UNH".to_owned(),
961                            message_type: "ENVELOPE".to_owned(),
962                            span: segment.span,
963                        }));
964                    }
965                    self.buf.clear();
966                    self.in_message = true;
967                    self.buf.push(segment);
968                }
969                "UNT" if self.in_message => {
970                    self.buf.push(segment);
971                    self.in_message = false;
972                    let segments = std::mem::take(&mut self.buf);
973                    return Some(Ok(MessageWindow::from_segments(segments)));
974                }
975                _ if self.in_message => {
976                    self.buf.push(segment);
977                }
978                _ => {
979                    // Envelope segment outside a window — skip.
980                }
981            }
982        }
983    }
984}
985
986/// An iterator that groups owned EDIFACT segments into per-message windows.
987///
988/// Each yielded item is an [`OwnedMessageWindow`] containing the segments for one
989/// complete `UNH..UNT` message, inclusive of both service segments.
990/// Envelope-level segments (`UNB`, `UNG`, `UNZ`, `UNE`) that sit outside any
991/// `UNH..UNT` pair are silently skipped.
992///
993/// # Errors
994///
995/// - An inner-iterator error is forwarded immediately and iteration stops.
996/// - A `UNH` seen while a prior window is still open (missing `UNT`) is an error.
997/// - Input that ends while a `UNH` window is open (stream truncation) yields
998///   `Err(EdifactError::UnexpectedEof { … })` before returning `None`.
999///
1000/// # Construction
1001///
1002/// Use [`message_windows_from_reader`] or [`message_windows_bytes`] to
1003/// obtain a `MessageWindowsIter` directly.  For fully custom sources, call
1004/// [`MessageWindowsIter::new`] with any `Iterator<Item = Result<OwnedSegment,
1005/// EdifactError>>`.
1006pub struct MessageWindowsIter<I> {
1007    inner: I,
1008    buf: Vec<crate::OwnedSegment>,
1009    in_message: bool,
1010    /// Set to `true` after any terminal condition (error or clean EOF) so that
1011    /// subsequent `next()` calls immediately return `None`.
1012    done: bool,
1013}
1014
1015impl<I: Iterator<Item = Result<crate::OwnedSegment, EdifactError>>> MessageWindowsIter<I> {
1016    /// Wrap any owned-segment iterator as a message-window iterator.
1017    pub fn new(inner: I) -> Self {
1018        Self {
1019            inner,
1020            buf: Vec::new(),
1021            in_message: false,
1022            done: false,
1023        }
1024    }
1025}
1026
1027impl<I: Iterator<Item = Result<crate::OwnedSegment, EdifactError>>> Iterator
1028    for MessageWindowsIter<I>
1029{
1030    type Item = Result<OwnedMessageWindow, EdifactError>;
1031
1032    fn next(&mut self) -> Option<Self::Item> {
1033        if self.done {
1034            return None;
1035        }
1036        loop {
1037            let segment = match self.inner.next() {
1038                Some(Ok(s)) => s,
1039                Some(Err(e)) => {
1040                    self.done = true;
1041                    return Some(Err(e));
1042                }
1043                None => {
1044                    self.done = true;
1045                    // A window that opened (UNH seen) but never closed (no UNT)
1046                    // means the stream was truncated — surface as an error.
1047                    if self.in_message && !self.buf.is_empty() {
1048                        self.in_message = false;
1049                        let offset = self.buf.last().map(|s| s.span.end).unwrap_or(0);
1050                        return Some(Err(EdifactError::UnexpectedEof { offset }));
1051                    }
1052                    return None;
1053                }
1054            };
1055
1056            match segment.tag.as_str() {
1057                "UNH" => {
1058                    if self.in_message {
1059                        // Malformed: new UNH without closing the prior UNT.
1060                        self.buf.clear();
1061                        self.in_message = false;
1062                        self.done = true;
1063                        return Some(Err(EdifactError::InvalidSegmentForMessage {
1064                            tag: "UNH".to_owned(),
1065                            message_type: "ENVELOPE".to_owned(),
1066                            span: segment.span,
1067                        }));
1068                    }
1069                    self.buf.clear();
1070                    self.in_message = true;
1071                    self.buf.push(segment);
1072                }
1073                "UNT" if self.in_message => {
1074                    self.buf.push(segment);
1075                    self.in_message = false;
1076                    let segments = std::mem::take(&mut self.buf);
1077                    return Some(Ok(OwnedMessageWindow::from_segments(segments)));
1078                }
1079                _ if self.in_message => {
1080                    self.buf.push(segment);
1081                }
1082                _ => {
1083                    // Envelope segment outside a window — skip.
1084                }
1085            }
1086        }
1087    }
1088}
1089
1090/// Stream-parse EDIFACT bytes into an iterator of per-message windows.
1091///
1092/// Each yielded [`MessageWindow`] spans one `UNH..UNT` pair, with segments
1093/// borrowing from `input` for their text content. Segment assembly is
1094/// zero-copy for borrowed input bytes; release-character unescaping may
1095/// allocate owned component strings when necessary.
1096/// Envelope segments (`UNB`, `UNZ`, …) are skipped automatically.
1097///
1098/// The `message_type` and `association_code` fields are populated directly from
1099/// the `UNH` segment so that routing logic does not need to traverse `segments`.
1100///
1101/// # Example
1102/// ```
1103/// use edifact_rs::from_bytes_windows;
1104/// let input = b"UNB+UNOA:1+SENDER+RECEIVER+200101:0900+1'\
1105///               UNH+1+ORDERS:D:96A:UN'\
1106///               BGM+220+PO-001+9'\
1107///               UNT+3+1'\
1108///               UNZ+1+1'";
1109///
1110/// let windows: Vec<_> = from_bytes_windows(input)
1111///     .collect::<Result<_, _>>()
1112///     .unwrap();
1113/// assert_eq!(windows.len(), 1);
1114/// assert_eq!(windows[0].message_type.as_deref(), Some("ORDERS"));
1115/// assert_eq!(windows[0].segments[0].tag, "UNH");
1116/// assert_eq!(windows[0].segments.last().unwrap().tag, "UNT");
1117/// ```
1118pub fn message_windows_bytes(input: &[u8]) -> MessageWindowsSliceIter<'_> {
1119    MessageWindowsSliceIter::new(crate::from_bytes(input))
1120}
1121
1122/// Stream-parse EDIFACT from a reader into an iterator of per-message windows.
1123///
1124/// Each yielded [`OwnedMessageWindow`] spans one `UNH..UNT` pair.
1125/// This variant reads lazily — only enough input to complete one window is
1126/// consumed per [`Iterator::next`] call.
1127pub fn message_windows_from_reader<R: Read>(
1128    reader: R,
1129) -> MessageWindowsIter<crate::FromReaderIter<R>> {
1130    MessageWindowsIter::new(crate::from_reader(reader))
1131}
1132
1133/// Stream typed messages from a reader by deserializing each `UNH..UNT` window.
1134///
1135/// This is the highest-level streaming API: it returns one `T` per message,
1136/// reading only as much data as needed to complete each window.
1137///
1138/// Each message window is deserialized via
1139/// [`EdifactDeserialize::edifact_deserialize_owned`], which avoids the
1140/// intermediate `Vec<Segment<'_>>` allocation incurred by the slice-based path.
1141/// Types derived with `#[derive(EdifactDeserialize)]` provide an efficient
1142/// override; manual implementations fall back to [`crate::OwnedSegment::as_borrowed`].
1143///
1144/// # Example
1145/// ```ignore
1146/// // Assuming `OrdersMessage` implements `EdifactDeserialize`:
1147/// let messages: Vec<OrdersMessage> =
1148///     deserialize_messages_from_reader::<OrdersMessage, _>(reader)
1149///         .collect::<Result<_, _>>()?;
1150/// ```
1151pub fn deserialize_messages_from_reader<T, R>(
1152    reader: R,
1153) -> impl Iterator<Item = Result<T, EdifactError>>
1154where
1155    T: EdifactDeserialize,
1156    R: Read,
1157{
1158    message_windows_from_reader(reader).map(|window| {
1159        let window = window?;
1160        T::edifact_deserialize_owned(&window.segments)
1161    })
1162}
1163
1164/// Stream typed messages from a byte slice by deserializing each `UNH..UNT` window.
1165pub fn deserialize_messages_bytes<T>(
1166    input: &[u8],
1167) -> impl Iterator<Item = Result<T, EdifactError>> + '_
1168where
1169    T: EdifactDeserialize,
1170{
1171    message_windows_bytes(input).map(|window| {
1172        let window = window?;
1173        T::edifact_deserialize(&window.segments)
1174    })
1175}
1176
1177// ── MessageDispatch ───────────────────────────────────────────────────────────
1178
1179/// A type-erased deserialized message produced by [`MessageDispatch`].
1180pub struct DispatchedMessage {
1181    /// The EDIFACT message type string extracted from the `UNH` segment.
1182    pub message_type: String,
1183    value: Box<dyn std::any::Any + Send + Sync>,
1184}
1185
1186impl DispatchedMessage {
1187    /// Attempt to downcast the inner value to `T`.
1188    ///
1189    /// Returns `None` if the stored type does not match `T`.
1190    pub fn downcast<T: std::any::Any + Send + Sync + 'static>(&self) -> Option<&T> {
1191        self.value.downcast_ref::<T>()
1192    }
1193}
1194
1195impl std::fmt::Debug for DispatchedMessage {
1196    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1197        f.debug_struct("DispatchedMessage")
1198            .field("message_type", &self.message_type)
1199            .finish_non_exhaustive()
1200    }
1201}
1202
1203type DispatchHandlerFn = Box<
1204    dyn for<'a> Fn(&[Segment<'a>]) -> Result<Box<dyn std::any::Any + Send + Sync>, EdifactError>
1205        + Send
1206        + Sync,
1207>;
1208
1209type FallbackHandlerFn = Box<
1210    dyn for<'a> Fn(
1211            &[Segment<'a>],
1212            &str,
1213        ) -> Result<Box<dyn std::any::Any + Send + Sync>, EdifactError>
1214        + Send
1215        + Sync,
1216>;
1217
1218/// Type-based dispatcher for mixed-message EDIFACT streams.
1219///
1220/// Register one handler per message type with [`on`][Self::on], then call
1221/// [`dispatch`][Self::dispatch] on each message window.  If no handler matches
1222/// and a [`fallback`][Self::fallback] was registered it is invoked instead;
1223/// otherwise an [`EdifactError::UnexpectedMessageType`] is returned.
1224///
1225/// # Example
1226///
1227/// ```rust,ignore
1228/// let dispatch = MessageDispatch::new()
1229///     .on("ORDERS",  |segs| Orders::edifact_deserialize(segs))
1230///     .on("INVOIC",  |segs| Invoice::edifact_deserialize(segs));
1231///
1232/// for window in message_windows_bytes(input) {
1233///     let window = window?;
1234///     let msg = dispatch.dispatch(&window)?;
1235///     match msg.message_type.as_str() {
1236///         "ORDERS"  => { let o = msg.downcast::<Orders>().unwrap(); /* … */ }
1237///         "INVOIC"  => { let i = msg.downcast::<Invoice>().unwrap(); /* … */ }
1238///         _         => unreachable!(),
1239///     }
1240/// }
1241/// ```
1242pub struct MessageDispatch {
1243    handlers: Vec<(String, DispatchHandlerFn)>,
1244    fallback: Option<FallbackHandlerFn>,
1245}
1246
1247impl Default for MessageDispatch {
1248    fn default() -> Self {
1249        Self::new()
1250    }
1251}
1252
1253impl MessageDispatch {
1254    /// Create an empty dispatcher.
1255    pub fn new() -> Self {
1256        Self {
1257            handlers: Vec::new(),
1258            fallback: None,
1259        }
1260    }
1261
1262    /// Register a handler for `message_type`.
1263    ///
1264    /// The closure receives the full message window and returns a typed value
1265    /// that is boxed and stored inside [`DispatchedMessage`].
1266    pub fn on<T, F>(mut self, message_type: &str, handler: F) -> Self
1267    where
1268        T: std::any::Any + Send + Sync + 'static,
1269        F: for<'a> Fn(&[Segment<'a>]) -> Result<T, EdifactError> + Send + Sync + 'static,
1270    {
1271        let erased: DispatchHandlerFn = Box::new(move |segs| {
1272            let val = handler(segs)?;
1273            Ok(Box::new(val) as Box<dyn std::any::Any + Send + Sync>)
1274        });
1275        self.handlers.push((message_type.to_owned(), erased));
1276        self
1277    }
1278
1279    /// Register a fallback handler for unrecognised message types.
1280    ///
1281    /// The closure receives the segment window **and** the unknown message-type
1282    /// string.
1283    pub fn fallback<T, F>(mut self, handler: F) -> Self
1284    where
1285        T: std::any::Any + Send + Sync + 'static,
1286        F: for<'a> Fn(&[Segment<'a>], &str) -> Result<T, EdifactError> + Send + Sync + 'static,
1287    {
1288        let erased: FallbackHandlerFn = Box::new(move |segs, mt| {
1289            let val = handler(segs, mt)?;
1290            Ok(Box::new(val) as Box<dyn std::any::Any + Send + Sync>)
1291        });
1292        self.fallback = Some(erased);
1293        self
1294    }
1295
1296    /// Dispatch a single message window to the appropriate handler.
1297    ///
1298    /// The message type is extracted from the `UNH` segment.  If no `UNH` is
1299    /// present, [`EdifactError::MissingSegment`] is returned.
1300    pub fn dispatch(&self, window: &[Segment<'_>]) -> Result<DispatchedMessage, EdifactError> {
1301        let message_type = window
1302            .iter()
1303            .find(|s| s.tag == "UNH")
1304            .and_then(|unh| unh.get_element(1))
1305            .and_then(|e| e.get_component(0))
1306            .map(|s| s.to_owned())
1307            .ok_or_else(|| EdifactError::MissingSegment {
1308                tag: "UNH".to_owned(),
1309                expected_position: "first segment of message window".to_owned(),
1310            })?;
1311
1312        for (mt, handler) in &self.handlers {
1313            if *mt == message_type {
1314                let value = handler(window)?;
1315                return Ok(DispatchedMessage {
1316                    message_type,
1317                    value,
1318                });
1319            }
1320        }
1321
1322        if let Some(fallback) = &self.fallback {
1323            let value = fallback(window, &message_type)?;
1324            return Ok(DispatchedMessage {
1325                message_type,
1326                value,
1327            });
1328        }
1329
1330        Err(EdifactError::UnexpectedMessageType { message_type })
1331    }
1332
1333    /// Dispatch all messages from a byte reader.
1334    ///
1335    /// Each message window is extracted and dispatched in order.  The returned
1336    /// iterator is lazy — errors are yielded as `Err` items.
1337    pub fn dispatch_all_from_bytes<'a>(
1338        &'a self,
1339        input: &'a [u8],
1340    ) -> impl Iterator<Item = Result<DispatchedMessage, EdifactError>> + 'a {
1341        message_windows_bytes(input).map(move |window| {
1342            let window = window?;
1343            self.dispatch(&window.segments)
1344        })
1345    }
1346
1347    /// Dispatch all messages from a reader.
1348    ///
1349    /// Parses the stream into message windows and dispatches each.  The
1350    /// returned iterator yields owned [`DispatchedMessage`] values lazily:
1351    /// each window is fully buffered in memory (as `Vec<OwnedSegment>`) before
1352    /// dispatch, but windows are processed one at a time rather than all at once.
1353    pub fn dispatch_all_from_reader<R: Read + 'static>(
1354        &self,
1355        reader: R,
1356    ) -> impl Iterator<Item = Result<DispatchedMessage, EdifactError>> + '_ {
1357        message_windows_from_reader(reader).map(|window| {
1358            let window = window?;
1359            let borrowed: Vec<Segment<'_>> =
1360                window.segments.iter().map(|s| s.as_borrowed()).collect();
1361            self.dispatch(&borrowed)
1362        })
1363    }
1364}
1365
1366#[cfg(test)]
1367mod tests {
1368    use super::*;
1369
1370    // ── manual test impl ──────────────────────────────────────────────────────
1371    #[derive(Debug, PartialEq)]
1372    struct BgmSegment {
1373        doc_name_code: String,
1374        pruef_id: String,
1375        msg_function: Option<String>,
1376    }
1377
1378    impl EdifactSegmentTag for BgmSegment {
1379        const SEGMENT_TAG: &'static str = "BGM";
1380    }
1381
1382    struct NadM;
1383
1384    impl EdifactSegmentTag for NadM {
1385        const SEGMENT_TAG: &'static str = "NAD";
1386        const QUALIFIER_PATTERN: Option<&'static str> = Some("M*");
1387    }
1388
1389    struct NadWildcard;
1390
1391    impl EdifactSegmentTag for NadWildcard {
1392        const SEGMENT_TAG: &'static str = "NAD";
1393        const QUALIFIER_PATTERN: Option<&'static str> = Some("M*");
1394    }
1395
1396    impl EdifactDeserialize for BgmSegment {
1397        fn edifact_deserialize(segments: &[Segment<'_>]) -> Result<Self, EdifactError> {
1398            let seg = find_segment(segments, "BGM").ok_or_else(|| {
1399                EdifactError::MissingRequiredElement {
1400                    tag: "BGM".to_owned(),
1401                    element_index: 0,
1402                }
1403            })?;
1404            Ok(Self {
1405                doc_name_code: element_str(seg, 0).to_owned(),
1406                pruef_id: element_str(seg, 1).to_owned(),
1407                msg_function: seg
1408                    .element_str(2)
1409                    .filter(|s| !s.is_empty())
1410                    .map(str::to_owned),
1411            })
1412        }
1413    }
1414
1415    #[test]
1416    fn deserialize_single_segment() {
1417        let input = b"BGM+E03+11042+9'";
1418        let bgm: BgmSegment = deserialize(input).unwrap();
1419        assert_eq!(bgm.doc_name_code, "E03");
1420        assert_eq!(bgm.pruef_id, "11042");
1421        assert_eq!(bgm.msg_function, Some("9".to_owned()));
1422    }
1423
1424    #[test]
1425    fn streaming_deserialize_first_from_bytes() {
1426        let input = b"UNH+1+ORDERS:D:11A:UN'BGM+E03+11042+9'UNT+3+1'";
1427        let bgm: BgmSegment = deserialize_first_streaming(input).unwrap();
1428        assert_eq!(bgm.pruef_id, "11042");
1429    }
1430
1431    #[test]
1432    fn streaming_deserialize_all_from_bytes() {
1433        let input = b"BGM+E03+11042+9'RFF+AA:1'BGM+E01+11043+9'";
1434        let bgms: Vec<BgmSegment> = deserialize_all_streaming(input).unwrap();
1435        assert_eq!(bgms.len(), 2);
1436        assert_eq!(bgms[0].pruef_id, "11042");
1437        assert_eq!(bgms[1].pruef_id, "11043");
1438    }
1439
1440    #[test]
1441    fn streaming_deserialize_first_from_reader() {
1442        let input =
1443            std::io::Cursor::new(b"UNH+1+ORDERS:D:11A:UN'BGM+E03+11042+9'UNT+3+1'".to_vec());
1444        let bgm: BgmSegment = deserialize_first_from_reader(input).unwrap();
1445        assert_eq!(bgm.pruef_id, "11042");
1446    }
1447
1448    #[test]
1449    fn streaming_deserialize_all_from_reader() {
1450        let input = std::io::Cursor::new(b"BGM+E03+11042+9'BGM+E01+11043+9'".to_vec());
1451        let bgms: Vec<BgmSegment> = deserialize_all_from_reader(input).unwrap();
1452        assert_eq!(bgms.len(), 2);
1453        assert_eq!(bgms[0].pruef_id, "11042");
1454        assert_eq!(bgms[1].pruef_id, "11043");
1455    }
1456
1457    #[test]
1458    fn missing_segment_returns_error() {
1459        let input = b"DTM+137:20230401:102'";
1460        let result: Result<BgmSegment, _> = deserialize(input);
1461        assert!(result.is_err());
1462    }
1463
1464    #[test]
1465    fn vec_collects_all_matching_segments() {
1466        let input = b"DTM+137:20230401:102'BGM+E03+11042+9'BGM+E01+11043+9'";
1467        let bgms: Vec<BgmSegment> = deserialize(input).unwrap();
1468        assert_eq!(bgms.len(), 2);
1469        assert_eq!(bgms[0].pruef_id, "11042");
1470        assert_eq!(bgms[1].pruef_id, "11043");
1471    }
1472
1473    #[test]
1474    fn find_qualified_segment_matches_qualifier() {
1475        let input = b"NAD+MS+9900001+293'NAD+MR+9900002+293'";
1476        let segments: Vec<Segment<'_>> =
1477            crate::from_bytes(input).collect::<Result<_, _>>().unwrap();
1478        let nad_ms = find_qualified_segment(&segments, "NAD", "MS");
1479        let nad_mr = find_qualified_segment(&segments, "NAD", "MR");
1480        assert!(nad_ms.is_some());
1481        assert!(nad_mr.is_some());
1482        assert_eq!(element_str(nad_ms.unwrap(), 0), "MS");
1483        assert_eq!(element_str(nad_mr.unwrap(), 0), "MR");
1484    }
1485
1486    #[test]
1487    fn round_trip_str_api() {
1488        let input = "BGM+E03+11042+9'";
1489        let bgm: BgmSegment = deserialize_str(input).unwrap();
1490        assert_eq!(bgm.pruef_id, "11042");
1491    }
1492
1493    #[test]
1494    fn required_element_extraction() {
1495        let input = b"BGM+E03+11042+9'";
1496        let segments: Vec<Segment<'_>> =
1497            crate::from_bytes(input).collect::<Result<_, _>>().unwrap();
1498        let seg = &segments[0];
1499
1500        assert_eq!(required_element(seg, 0).unwrap(), "E03");
1501        assert_eq!(required_element(seg, 1).unwrap(), "11042");
1502        // Element 5 doesn't exist
1503        assert!(required_element(seg, 5).is_err());
1504    }
1505
1506    #[test]
1507    fn optional_element_extraction() {
1508        let input = b"BGM+E03+11042+9'BGM+E01++absent'";
1509        let segments: Vec<Segment<'_>> =
1510            crate::from_bytes(input).collect::<Result<_, _>>().unwrap();
1511
1512        // First segment
1513        assert_eq!(optional_element(&segments[0], 0), Some("E03"));
1514        assert_eq!(optional_element(&segments[0], 1), Some("11042"));
1515        assert_eq!(optional_element(&segments[0], 5), None);
1516
1517        // Second segment with empty element
1518        assert_eq!(optional_element(&segments[1], 1), None);
1519    }
1520
1521    #[test]
1522    fn component_extraction() {
1523        let input = b"UNB+UNOA:1+SENDER+RECEIVER+200101:0900+1'";
1524        let segments: Vec<Segment<'_>> =
1525            crate::from_bytes(input).collect::<Result<_, _>>().unwrap();
1526        let seg = &segments[0];
1527
1528        assert_eq!(required_component(seg, 0, 0).unwrap(), "UNOA");
1529        assert_eq!(required_component(seg, 0, 1).unwrap(), "1");
1530        // Non-existent component
1531        assert!(required_component(seg, 0, 5).is_err());
1532    }
1533
1534    #[test]
1535    fn composite_element_helper() {
1536        let input = b"UNB+UNOA:1+SENDER+RECEIVER+200101:0900+1'";
1537        let segments: Vec<Segment<'_>> =
1538            crate::from_bytes(input).collect::<Result<_, _>>().unwrap();
1539        let seg = &segments[0];
1540
1541        let comp = composite_element(seg, 0).unwrap();
1542        assert_eq!(comp.len(), 2);
1543        assert_eq!(comp.get(0), Some("UNOA"));
1544        assert_eq!(comp.get(1), Some("1"));
1545        assert_eq!(comp.get(5), None);
1546        assert_eq!(comp.get_or_empty(5), "");
1547    }
1548
1549    #[test]
1550    fn get_all_components() {
1551        // UNB has composite element: UNOA:1
1552        let input = b"UNB+UNOA:1+SENDER+RECEIVER+200101:0900+1'";
1553        let segments: Vec<Segment<'_>> =
1554            crate::from_bytes(input).collect::<Result<_, _>>().unwrap();
1555        let seg = &segments[0];
1556
1557        let comps: Vec<&str> = get_components_iter(seg, 0).collect(); // First element is UNOA:1
1558        assert!(!comps.is_empty(), "Expected components but got empty");
1559        assert_eq!(comps.len(), 2);
1560        assert_eq!(comps[0], "UNOA");
1561        assert_eq!(comps[1], "1");
1562    }
1563
1564    #[test]
1565    fn qualifier_pattern_matching_supports_exact_and_wildcard() {
1566        // Exact match (no wildcard)
1567        assert!(qualifier_matches_pattern("MS", "MS"));
1568        assert!(!qualifier_matches_pattern("MS", "M")); // Not a prefix match after R-003
1569        // Wildcard patterns
1570        assert!(qualifier_matches_pattern("MS", "M*"));
1571        assert!(qualifier_matches_pattern("MRY", "M*Y"));
1572        assert!(!qualifier_matches_pattern("AB", "M*"));
1573    }
1574
1575    /// Comprehensive table-driven tests for `qualifier_matches_pattern`.
1576    #[test]
1577    fn qualifier_matches_pattern_table() {
1578        // (value, pattern, expected)
1579        let cases: &[(&str, &str, bool)] = &[
1580            // ── empty inputs ────────────────────────────────────────────────
1581            ("", "", true),   // empty matches empty
1582            ("", "*", true),  // wildcard matches empty string
1583            ("A", "", false), // non-empty does not match empty pattern
1584            ("", "A", false), // empty does not match non-empty literal
1585            // ── literal (no wildcard) ────────────────────────────────────────
1586            ("MS", "MS", true),
1587            ("BY", "BY", true),
1588            ("ms", "MS", false),  // case-sensitive
1589            ("MSX", "MS", false), // prefix is NOT a match without wildcard
1590            ("M", "MS", false),   // too short
1591            // ── single wildcard at the end (prefix match) ────────────────────
1592            ("MS", "M*", true),
1593            ("MULTI", "MUL*", true),
1594            ("AB", "M*", false),
1595            ("", "M*", false), // empty does not start with 'M'
1596            // ── single wildcard at the start (suffix match) ──────────────────
1597            ("MSG", "*G", true),
1598            ("G", "*G", true),
1599            ("MSG", "*X", false),
1600            ("", "*G", false),
1601            // ── wildcard in the middle ───────────────────────────────────────
1602            ("MRY", "M*Y", true),
1603            ("MAY", "M*Y", true),
1604            ("MY", "M*Y", true),    // zero-width wildcard: "M" + "" + "Y"
1605            ("MYY", "M*Y", true),   // last 'Y' matches, wildcard = 'Y'
1606            ("MAYZ", "M*Y", false), // does not end with 'Y'
1607            ("AB", "M*Y", false),
1608            // ── bare wildcard (match-all) ────────────────────────────────────
1609            ("*", "*", true), // literal '*' value vs wildcard pattern
1610            ("anything", "*", true),
1611            ("", "*", true),
1612            // ── multiple wildcards ────────────────────────────────────────────
1613            ("ABCDE", "A*C*E", true),
1614            ("ACE", "A*C*E", true), // zero-width wildcards
1615            ("AXCYE", "A*C*E", true),
1616            ("ABCDF", "A*C*E", false),
1617            // ── wildcard with empty segment between stars ─────────────────────
1618            ("AB", "A**B", true), // "A**B" → parts ["A", "", "B"] → ends_with_wildcard?
1619            // ── pattern longer than value ─────────────────────────────────────
1620            ("AB", "A*B*C", false),
1621            // ── value contains pattern as substring but must anchor start ─────
1622            ("XMS", "MS", false),
1623        ];
1624
1625        for (value, pattern, expected) in cases {
1626            let got = qualifier_matches_pattern(value, pattern);
1627            assert_eq!(
1628                got, *expected,
1629                "qualifier_matches_pattern({value:?}, {pattern:?}) expected {expected} but got {got}"
1630            );
1631        }
1632    }
1633
1634    #[test]
1635    fn typed_qualifier_helpers_work() {
1636        let input = b"NAD+MS+9900001+293'NAD+MR+9900002+293'";
1637        let segments: Vec<Segment<'_>> =
1638            crate::from_bytes(input).collect::<Result<_, _>>().unwrap();
1639
1640        let first = find_segment_typed::<NadM>(&segments).unwrap();
1641        assert_eq!(first.element_str(0), Some("MS"));
1642
1643        let all: Vec<_> = find_segments_typed::<NadWildcard>(&segments).collect();
1644        assert_eq!(all.len(), 2);
1645    }
1646
1647    #[test]
1648    fn segment_accessor_trait_methods_work() {
1649        let input = b"UNB+UNOA:1+SENDER+RECEIVER+200101:0900+1'";
1650        let segments: Vec<Segment<'_>> =
1651            crate::from_bytes(input).collect::<Result<_, _>>().unwrap();
1652        let seg = &segments[0];
1653
1654        assert_eq!(SegmentAccessor::get_element(seg, 1), Some("SENDER"));
1655        assert_eq!(SegmentAccessor::required_composite(seg, 0, 1).unwrap(), "1");
1656        let parsed: i32 = SegmentAccessor::code_element(seg, 4).unwrap();
1657        assert_eq!(parsed, 1);
1658        let reps = SegmentAccessor::repeating_components(seg, 3, 0, 2).unwrap();
1659        assert_eq!(reps, vec!["200101", "0900"]);
1660    }
1661
1662    #[test]
1663    fn group_helpers_detect_contiguity() {
1664        struct NadAny;
1665        impl EdifactSegmentTag for NadAny {
1666            const SEGMENT_TAG: &'static str = "NAD";
1667        }
1668
1669        let contiguous_input = b"NAD+MS+1'NAD+MR+2'RFF+AA:1'";
1670        let contiguous_segments: Vec<Segment<'_>> = crate::from_bytes(contiguous_input)
1671            .collect::<Result<_, _>>()
1672            .unwrap();
1673        assert!(groups_are_contiguous_by_qualifier::<NadAny>(
1674            &contiguous_segments
1675        ));
1676
1677        let non_contiguous_input = b"NAD+MS+1'RFF+AA:1'NAD+MR+2'";
1678        let non_contiguous_segments: Vec<Segment<'_>> = crate::from_bytes(non_contiguous_input)
1679            .collect::<Result<_, _>>()
1680            .unwrap();
1681        assert!(!groups_are_contiguous_by_qualifier::<NadAny>(
1682            &non_contiguous_segments
1683        ));
1684    }
1685
1686    #[test]
1687    fn group_helpers_collect_contiguous_groups() {
1688        struct NadAny;
1689        impl EdifactSegmentTag for NadAny {
1690            const SEGMENT_TAG: &'static str = "NAD";
1691        }
1692
1693        let input = b"NAD+MS+1'NAD+MR+2'RFF+AA:1'NAD+BY+3'";
1694        let segments: Vec<Segment<'_>> =
1695            crate::from_bytes(input).collect::<Result<_, _>>().unwrap();
1696        let groups = contiguous_groups_by_qualifier::<NadAny>(&segments);
1697
1698        assert_eq!(groups.len(), 2);
1699        assert_eq!(groups[0].len(), 2);
1700        assert_eq!(groups[1].len(), 1);
1701    }
1702
1703    // ── MessageWindowsIter tests ──────────────────────────────────────────────
1704
1705    #[test]
1706    fn message_windows_bytes_yields_complete_windows() {
1707        let input = b"UNB+UNOA:1+S+R+200101:0900+1'\
1708                      UNH+1+ORDERS:D:96A:UN'\
1709                      BGM+220+PO-001+9'\
1710                      UNT+3+1'\
1711                      UNZ+1+1'";
1712        let windows: Vec<_> = message_windows_bytes(input)
1713            .collect::<Result<_, _>>()
1714            .unwrap();
1715        assert_eq!(windows.len(), 1);
1716        assert_eq!(windows[0].segments[0].tag, "UNH");
1717        assert_eq!(windows[0].segments.last().unwrap().tag, "UNT");
1718        assert_eq!(windows[0].message_type.as_deref(), Some("ORDERS"));
1719        assert_eq!(windows[0].association_code.as_deref(), None);
1720    }
1721
1722    #[test]
1723    fn message_windows_bytes_preserves_owned_unh_metadata() {
1724        let input = b"UNB+UNOA:1+S+R+200101:0900+1'\
1725                      UNH+1+ORD?ERS:D:96A:UN:5??5??3a'\
1726                      BGM+220+PO-001+9'\
1727                      UNT+3+1'\
1728                      UNZ+1+1'";
1729        let windows: Vec<_> = message_windows_bytes(input)
1730            .collect::<Result<_, _>>()
1731            .unwrap();
1732
1733        assert_eq!(windows.len(), 1);
1734        assert_eq!(windows[0].message_type.as_deref(), Some("ORDERS"));
1735        assert_eq!(windows[0].association_code.as_deref(), Some("5?5?3a"));
1736    }
1737
1738    #[test]
1739    fn message_windows_truncated_stream_returns_error() {
1740        // Stream ends after UNH and BGM but without UNT — truncation must be an error
1741        let input = b"UNH+1+ORDERS:D:96A:UN'BGM+220+PO-001+9'";
1742        let results: Vec<_> = message_windows_bytes(input).collect();
1743        assert_eq!(results.len(), 1);
1744        assert!(
1745            matches!(results[0], Err(EdifactError::UnexpectedEof { .. })),
1746            "expected UnexpectedEof for truncated window, got: {:?}",
1747            results[0]
1748        );
1749    }
1750
1751    #[test]
1752    fn message_windows_subsequent_calls_return_none_after_truncation() {
1753        let input = b"UNH+1+ORDERS:D:96A:UN'BGM+220+PO-001+9'";
1754        let mut iter = message_windows_bytes(input);
1755        assert!(matches!(
1756            iter.next(),
1757            Some(Err(EdifactError::UnexpectedEof { .. }))
1758        ));
1759        // After the error, the iterator must be fused (done = true)
1760        assert!(iter.next().is_none());
1761    }
1762
1763    #[test]
1764    fn message_windows_unh_without_unt_before_next_unh_returns_error() {
1765        let input = b"UNH+1+ORDERS:D:96A:UN'BGM+220+PO-001+9'\
1766                      UNH+2+ORDERS:D:96A:UN'BGM+220+PO-002+9'UNT+3+2'";
1767        let results: Vec<_> = message_windows_bytes(input).collect();
1768        // First item must be an error (UNH before UNT — missing closer)
1769        assert!(
1770            matches!(
1771                results[0],
1772                Err(EdifactError::InvalidSegmentForMessage { ref tag, .. }) if tag == "UNH"
1773            ),
1774            "expected InvalidSegmentForMessage(UNH), got: {:?}",
1775            results[0]
1776        );
1777    }
1778
1779    // ── SegmentAccessor unit tests ─────────────────────────────────────────────
1780
1781    fn parse_one(input: &str) -> crate::OwnedSegment {
1782        crate::from_reader_collect(std::io::Cursor::new(input.as_bytes()))
1783            .expect("parse failed")
1784            .into_iter()
1785            .next()
1786            .expect("at least one segment")
1787    }
1788
1789    #[test]
1790    fn segment_accessor_get_element_returns_value() {
1791        let owned = parse_one("BGM+220+PO-001+9'");
1792        let seg = owned.as_borrowed();
1793        assert_eq!(SegmentAccessor::get_element(&seg, 0), Some("220"));
1794        assert_eq!(SegmentAccessor::get_element(&seg, 1), Some("PO-001"));
1795        assert_eq!(SegmentAccessor::get_element(&seg, 2), Some("9"));
1796        assert_eq!(
1797            SegmentAccessor::get_element(&seg, 9),
1798            None,
1799            "out-of-bounds must return None"
1800        );
1801    }
1802
1803    #[test]
1804    fn segment_accessor_get_element_filters_empty() {
1805        let owned = parse_one("TST+++VALUE'");
1806        let seg = owned.as_borrowed();
1807        // elements 0 and 1 are empty; element 2 is "VALUE"
1808        assert_eq!(
1809            SegmentAccessor::get_element(&seg, 0),
1810            None,
1811            "empty element must return None"
1812        );
1813        assert_eq!(
1814            SegmentAccessor::get_element(&seg, 1),
1815            None,
1816            "empty element must return None"
1817        );
1818        assert_eq!(SegmentAccessor::get_element(&seg, 2), Some("VALUE"));
1819    }
1820
1821    #[test]
1822    fn segment_accessor_get_component_returns_value() {
1823        let owned = parse_one("UNH+1+ORDERS:D:96A:UN'");
1824        let seg = owned.as_borrowed();
1825        assert_eq!(seg.get_component(1, 0), Some("ORDERS"));
1826        assert_eq!(seg.get_component(1, 1), Some("D"));
1827        assert_eq!(seg.get_component(1, 2), Some("96A"));
1828        assert_eq!(seg.get_component(1, 3), Some("UN"));
1829        assert_eq!(
1830            seg.get_component(1, 9),
1831            None,
1832            "out-of-bounds must return None"
1833        );
1834    }
1835
1836    #[test]
1837    fn segment_accessor_text_element_errors_on_missing() {
1838        let owned = parse_one("BGM+'");
1839        let seg = owned.as_borrowed();
1840        // element 0 is empty — text_element must return an error
1841        let err = seg.text_element(0);
1842        assert!(
1843            matches!(err, Err(EdifactError::MissingRequiredElement { ref tag, element_index: 0 }) if tag == "BGM"),
1844            "expected MissingRequiredElement, got: {err:?}"
1845        );
1846    }
1847
1848    #[test]
1849    fn segment_accessor_required_composite_errors_on_missing() {
1850        let owned = parse_one("DTM+137'");
1851        let seg = owned.as_borrowed();
1852        // component 1 of element 0 is absent
1853        let err = seg.required_composite(0, 1);
1854        assert!(
1855            matches!(err, Err(EdifactError::MissingRequiredComponent { ref tag, element_index: 0, component_index: 1 }) if tag == "DTM"),
1856            "expected MissingRequiredComponent, got: {err:?}"
1857        );
1858    }
1859
1860    #[test]
1861    fn segment_accessor_code_element_parses_integer() {
1862        let owned = parse_one("QTY+21:100'");
1863        let seg = owned.as_borrowed();
1864        let qty: u32 = seg.code_element(0).expect("should parse qualifier as u32");
1865        assert_eq!(qty, 21);
1866    }
1867
1868    #[test]
1869    fn segment_accessor_optional_element_absent_returns_none() {
1870        let owned = parse_one("BGM+220'");
1871        let seg = owned.as_borrowed();
1872        assert_eq!(seg.optional_element(5), None);
1873    }
1874}