Skip to main content

edifact_rs/
tokenizer.rs

1//! EDIFACT tokenizer — splits raw bytes into typed tokens.
2//!
3//! Respects UNA service string advice for non-default delimiters.
4//! Uses `memchr` for fast delimiter scanning (no byte-by-byte inner loops).
5
6use crate::{error::EdifactError, model::Span};
7use memchr::{memchr, memchr2, memchr3};
8
9/// EDIFACT service string advice (UNA segment).
10///
11/// Defaults: `+` (element), `:` (component), `?` (release), `.` (decimal mark),
12/// `*` (repetition separator), `'` (segment terminator).
13///
14/// All six service characters are first-class fields.  [`is_valid`][Self::is_valid]
15/// checks all six for mutual distinctness and for being printable, non-alphanumeric
16/// ASCII, so a collision between the repetition separator and any other delimiter —
17/// or a delimiter that would clash with segment-tag characters — is caught at UNA
18/// parse time.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub struct ServiceStringAdvice {
21    /// Data element separator (default `+`)
22    pub element_sep: u8,
23    /// Component data element separator (default `:`)
24    pub component_sep: u8,
25    /// Release character (default `?`)
26    pub release_char: u8,
27    /// Decimal notation mark (default `.`; UNA byte 5, ISO 9735-1 §7.1).
28    /// Not used by the tokenizer for splitting, but preserved for downstream use.
29    pub decimal_mark: u8,
30    /// Repetition separator (UNA byte 7, ISO 9735-4 §3.1).
31    ///
32    /// Defaults to space (`0x20`), the conventional "not used" sentinel, when no
33    /// UNA is present.  Some DVGW gas-market profiles and other non-default
34    /// EDIFACT implementations declare a real repetition separator here; this
35    /// field is always populated from the UNA so that downstream code can access
36    /// it without re-parsing the raw UNA bytes.
37    ///
38    /// The tokenizer does not currently split on the repetition separator — that
39    /// responsibility belongs to downstream consumers — but `is_valid()` includes
40    /// it in the six-way uniqueness check to catch delimiter collisions early.
41    pub repetition_sep: u8,
42    /// Segment terminator (default `'`)
43    pub segment_term: u8,
44}
45
46impl Default for ServiceStringAdvice {
47    fn default() -> Self {
48        Self {
49            element_sep: b'+',
50            component_sep: b':',
51            release_char: b'?',
52            decimal_mark: b'.',
53            // Space (0x20) is the conventional "not used" sentinel found at
54            // position 7 in the vast majority of real-world EDIFACT interchanges
55            // that do not employ ISO 9735-4 repetition elements.  `is_valid()`
56            // accepts space here without a printability or uniqueness check.
57            repetition_sep: b' ',
58            segment_term: b'\'',
59        }
60    }
61}
62
63impl ServiceStringAdvice {
64    /// Parse a UNA header and validate that all six service characters
65    /// (`element_sep`, `component_sep`, `decimal_mark`, `release_char`,
66    /// `repetition_sep`, and `segment_term`) are mutually distinct and are
67    /// printable, non-alphanumeric ASCII.  See [`is_valid`][Self::is_valid] for
68    /// the exact rule.
69    ///
70    /// Returns [`EdifactError::InvalidUna`] if the invariant is violated.
71    /// Falls back to [`ServiceStringAdvice::default`] when no UNA is present.
72    ///
73    /// This is the **safe, default constructor** — always use this for input from
74    /// an external source.  For trusted or internal use where delimiter uniqueness
75    /// is already guaranteed, use [`from_bytes_unchecked`](Self::from_bytes_unchecked).
76    pub fn from_bytes(input: &[u8]) -> Result<Self, crate::error::EdifactError> {
77        let ssa = Self::from_bytes_unchecked(input);
78        if !ssa.is_valid() {
79            return Err(crate::error::EdifactError::InvalidUna);
80        }
81        Ok(ssa)
82    }
83
84    /// Parse a UNA header from the beginning of an EDIFACT interchange **without**
85    /// validating delimiter uniqueness or printability.
86    ///
87    /// If no UNA is present, returns [`ServiceStringAdvice::default`].
88    ///
89    /// The `repetition_sep` field is populated from UNA byte 7 (ISO 9735-4 §3.1)
90    /// or defaults to space (`0x20`, the "not used" sentinel) when no UNA is present.
91    ///
92    /// # When to use
93    ///
94    /// Use this only for trusted internal data (e.g. round-tripping data where
95    /// the UNA invariant is already guaranteed) or in fuzz/property tests that
96    /// intentionally explore degenerate delimiter combinations.
97    ///
98    /// For any external or user-provided input, prefer [`from_bytes`](Self::from_bytes)
99    /// which validates delimiter uniqueness and rejects invalid bytes.
100    pub fn from_bytes_unchecked(input: &[u8]) -> Self {
101        // UNA is 9 bytes: "UNA" + 6 service chars
102        if input.len() >= 9 && &input[..3] == b"UNA" {
103            Self {
104                component_sep: input[3],
105                element_sep: input[4],
106                decimal_mark: input[5],
107                release_char: input[6],
108                repetition_sep: input[7],
109                segment_term: input[8],
110            }
111        } else {
112            Self::default()
113        }
114    }
115
116    /// Return `true` if all active service characters are mutually distinct
117    /// and printable ASCII.
118    ///
119    /// The five *mandatory* characters (`element_sep`, `component_sep`,
120    /// `decimal_mark`, `release_char`, `segment_term`) must all be printable,
121    /// **non-alphanumeric** ASCII (`0x21–0x7E`, excluding `0-9A-Za-z`) and
122    /// mutually distinct (10 pairwise checks).  Alphanumerics are rejected
123    /// because segment tags are written verbatim and cannot be escaped, so a
124    /// letter delimiter would make tags containing it unrepresentable.
125    ///
126    /// The `repetition_sep` field is also validated when it is **not a space**
127    /// (`0x20`).  A space at position 7 of the UNA is the conventional
128    /// "absent" sentinel used by interchanges that do not employ repetition
129    /// elements (ISO 9735-1 / ISO 9735-4 §3.1), and it is accepted without
130    /// a printability or uniqueness check.  Any other value must be printable
131    /// non-alphanumeric ASCII and distinct from all five mandatory characters.
132    ///
133    /// High bytes (`>= 0x80`) are rejected because they would incorrectly bisect
134    /// multi-byte UTF-8 sequences, and DEL (`0x7F`) is a non-printable control
135    /// character.
136    pub fn is_valid(&self) -> bool {
137        let [e, c, d, r, t] = [
138            self.element_sep,
139            self.component_sep,
140            self.decimal_mark,
141            self.release_char,
142            self.segment_term,
143        ];
144        // All five mandatory chars must be printable, non-alphanumeric ASCII and
145        // mutually distinct (10 pairwise checks).
146        //
147        // Alphanumerics are excluded because segment tags are always three ASCII
148        // uppercase letters and are written verbatim (a tag cannot be escaped).
149        // A delimiter such as `N` would therefore make `NAD` unrepresentable —
150        // the writer would emit a premature terminator and the result would not
151        // reparse.  Real-world UNA strings use punctuation exclusively, so this
152        // rejects only degenerate configurations.
153        let printable_ascii = |b: u8| (0x21..=0x7E).contains(&b) && !b.is_ascii_alphanumeric();
154        let basic_valid = printable_ascii(e)
155            && printable_ascii(c)
156            && printable_ascii(d)
157            && printable_ascii(r)
158            && printable_ascii(t)
159            && e != c
160            && e != d
161            && e != r
162            && e != t
163            && c != d
164            && c != r
165            && c != t
166            && d != r
167            && d != t
168            && r != t;
169        if !basic_valid {
170            return false;
171        }
172        // repetition_sep: space (0x20) means "not used" — accepted as-is.
173        // Any other value must be printable ASCII and distinct from all five
174        // mandatory service characters.
175        let rep = self.repetition_sep;
176        if rep == b' ' {
177            true
178        } else {
179            printable_ascii(rep) && rep != e && rep != c && rep != d && rep != r && rep != t
180        }
181    }
182}
183
184/// Token produced by [`Tokenizer`].
185#[derive(Debug, Clone, PartialEq, Eq)]
186pub enum Token<'a> {
187    /// 3-character segment tag (e.g. `"BGM"`)
188    SegmentTag {
189        /// Raw tag value.
190        value: &'a str,
191        /// Source span of the tag.
192        span: Span,
193    },
194    /// Data element value (between element separators)
195    DataElement {
196        /// Raw element value.
197        value: &'a str,
198        /// Source span of the element value.
199        span: Span,
200    },
201    /// Component within a composite data element (between component separators)
202    ComponentElement {
203        /// Raw component value.
204        value: &'a str,
205        /// Source span of the component value.
206        span: Span,
207    },
208    /// Segment terminator — signals the end of a segment
209    SegmentTerminator {
210        /// Source span of the segment terminator byte.
211        span: Span,
212    },
213}
214
215#[derive(Debug)]
216pub(crate) struct RawSegment {
217    pub(crate) bytes: Vec<u8>,
218    pub(crate) start_offset: usize,
219}
220
221/// Zero-copy tokenizer over a byte slice.
222///
223/// Yields `Token` values, each borrowing from the original input.
224///
225/// # Segment size guard
226///
227/// The default constructor [`Tokenizer::new`] enforces a **64 KiB** per-segment
228/// limit, which is sufficient for all well-formed EDIFACT interchanges and guards
229/// against adversarially crafted inputs that omit segment terminators.
230/// Use [`Tokenizer::with_limit`] to raise or lower this threshold, or
231/// [`Tokenizer::unlimited`] to remove it entirely (trusted / pre-validated input only).
232pub struct Tokenizer<'a> {
233    input: &'a [u8],
234    pos: usize,
235    ssa: ServiceStringAdvice,
236    state: TokState,
237    /// Maximum allowed segment byte length (tag + elements, **excluding** the
238    /// segment terminator byte itself).  Checked in `read_value` and `read_tag`.
239    /// `usize::MAX` = unlimited.
240    max_segment_bytes: usize,
241    /// Byte position where the current segment started (set in `read_tag`).
242    segment_start: usize,
243}
244
245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
246enum TokState {
247    /// Expecting a segment tag next
248    ExpectTag,
249    /// Inside a segment; next byte could be element or component sep, release, or terminator
250    InSegment,
251}
252
253impl<'a> Tokenizer<'a> {
254    /// Return the byte offset of the first non-UNA byte in `input`.
255    ///
256    /// If the input starts with the `UNA` service string advice (first 3
257    /// bytes are `b"UNA"`), the UNA header is exactly 9 bytes long and the
258    /// first segment tag starts at offset 9.  Otherwise parsing starts at 0.
259    #[inline]
260    fn una_start_pos(input: &[u8]) -> usize {
261        if input.len() >= 9 && &input[..3] == b"UNA" {
262            9
263        } else {
264            0
265        }
266    }
267
268    /// Construct a tokenizer with the default 64 KiB segment-size limit.
269    ///
270    /// If a single segment's byte length exceeds 65 536 bytes, the iterator
271    /// returns [`EdifactError::SegmentTooLong`].  This guards against
272    /// pathological or adversarially crafted inputs that omit segment
273    /// terminators and would otherwise cause unbounded scanning.
274    ///
275    /// Call [`Tokenizer::unlimited`] if you deliberately need to process
276    /// segments larger than 64 KiB, or [`Tokenizer::with_limit`] to supply a
277    /// custom bound.
278    pub fn new(input: &'a [u8], ssa: ServiceStringAdvice) -> Self {
279        Self::with_limit(input, ssa, 65_536)
280    }
281
282    /// Construct a tokenizer with **no** segment-size limit.
283    ///
284    /// # Security warning
285    ///
286    /// This constructor imposes **no upper bound** on how many bytes a single
287    /// segment may consume.  For untrusted or adversarially crafted input a
288    /// missing segment terminator can cause the tokenizer to scan the entire
289    /// input before returning an error.  Prefer [`Tokenizer::new`] (64 KiB
290    /// limit) or [`Tokenizer::with_limit`] for untrusted sources.
291    #[must_use]
292    pub fn unlimited(input: &'a [u8], ssa: ServiceStringAdvice) -> Self {
293        Self {
294            input,
295            pos: Self::una_start_pos(input),
296            ssa,
297            state: TokState::ExpectTag,
298            max_segment_bytes: usize::MAX,
299            segment_start: 0,
300        }
301    }
302
303    /// Construct a tokenizer with a segment-size limit.
304    ///
305    /// If a single segment's byte length (from the start of the tag to the end
306    /// of the last value, not including the terminator itself) exceeds `limit`,
307    /// the iterator returns [`EdifactError::SegmentTooLong`].
308    ///
309    /// # Examples
310    ///
311    /// ```
312    /// use edifact_rs::{ServiceStringAdvice, Tokenizer};
313    ///
314    /// let input = b"BGM+220+PO-4711+9'";
315    /// let ssa = ServiceStringAdvice::default();
316    /// let tokens: Vec<_> = Tokenizer::with_limit(input, ssa, 64)
317    ///     .collect::<Result<_, _>>()
318    ///     .unwrap();
319    /// assert!(!tokens.is_empty());
320    /// ```
321    pub fn with_limit(input: &'a [u8], ssa: ServiceStringAdvice, max_segment_bytes: usize) -> Self {
322        Self {
323            input,
324            pos: Self::una_start_pos(input),
325            ssa,
326            state: TokState::ExpectTag,
327            max_segment_bytes,
328            segment_start: 0,
329        }
330    }
331
332    /// Current byte position in the input.
333    #[inline]
334    pub fn position(&self) -> usize {
335        self.pos
336    }
337
338    /// Return the service string advice active for this tokenizer.
339    #[inline]
340    pub fn service_string_advice(&self) -> ServiceStringAdvice {
341        self.ssa
342    }
343
344    /// Consume leading whitespace / CR / LF between segments (not inside data values).
345    fn skip_inter_segment_whitespace(&mut self) {
346        while self.pos < self.input.len() {
347            match self.input[self.pos] {
348                b' ' | b'\t' | b'\r' | b'\n' => self.pos += 1,
349                _ => break,
350            }
351        }
352    }
353
354    /// Read a field value starting at `self.pos`, advancing past the value.
355    ///
356    /// Recognises the release character (`?` by default) and returns the raw
357    /// slice including release sequences. The parser layer resolves them.
358    ///
359    /// Uses `memchr3` to bulk-scan over non-special bytes between hits, only
360    /// falling back to a per-byte step when a release character is encountered.
361    fn read_value(&mut self) -> Result<(&'a str, Span), EdifactError> {
362        let start = self.pos;
363        let (elem, comp, release, term) = (
364            self.ssa.element_sep,
365            self.ssa.component_sep,
366            self.ssa.release_char,
367            self.ssa.segment_term,
368        );
369        // Absolute cap on how far this value may extend before the per-segment
370        // byte guard trips.  Bounding the scan window here (rather than only
371        // checking the length after the loop) keeps adversarial input that omits
372        // every delimiter from forcing a scan across the whole remaining input.
373        let scan_end = self
374            .segment_start
375            .saturating_add(self.max_segment_bytes)
376            .saturating_add(1)
377            .min(self.input.len());
378
379        // Absolute offset of the next segment terminator at or after the current
380        // search origin.  `memchr3` below rescans only the bytes it actually
381        // consumes, but a naive `memchr(term, remaining)` per iteration would
382        // rescan the whole tail on every release sequence, making a value such as
383        // `?a?a?a…` quadratic.  Caching the hit keeps the terminator search
384        // amortised linear: each rescan starts past the previous hit, so the
385        // scanned regions are disjoint.
386        let mut term_hit = memchr(term, &self.input[self.pos..scan_end]).map(|i| self.pos + i);
387
388        loop {
389            if self.pos >= scan_end {
390                break;
391            }
392            let remaining = &self.input[self.pos..scan_end];
393            // Refresh the cached terminator position once the cursor has moved
394            // past it (only happens when a release sequence escaped a terminator).
395            if term_hit.is_some_and(|t| t < self.pos) {
396                term_hit = memchr(term, remaining).map(|i| self.pos + i);
397            }
398            let hit_ect = memchr3(elem, comp, release, remaining);
399            let hit_term = term_hit.map(|t| t - self.pos);
400            let hit = match (hit_ect, hit_term) {
401                (None, None) => {
402                    self.pos = scan_end;
403                    break;
404                }
405                (Some(a), None) => a,
406                (None, Some(b)) => b,
407                (Some(a), Some(b)) => a.min(b),
408            };
409            let b = remaining[hit];
410            if b == release {
411                // A release char must be followed by exactly one escaped byte.
412                // If it is the last byte in the buffer the sequence is malformed.
413                if self.pos + hit + 1 >= self.input.len() {
414                    return Err(EdifactError::InvalidReleaseSequence {
415                        offset: self.pos + hit,
416                    });
417                }
418                // Skip release char + the escaped byte.
419                self.pos += hit + 2;
420                continue;
421            }
422            // b is elem, comp, or term — end of value.
423            self.pos += hit;
424            break;
425        }
426        let span = Span::new(start, self.pos);
427        let value = std::str::from_utf8(&self.input[start..self.pos])
428            .map_err(|_| EdifactError::InvalidText { offset: start })?;
429        // Enforce the per-segment byte-length guard.
430        if self.pos - self.segment_start > self.max_segment_bytes {
431            return Err(EdifactError::SegmentTooLong {
432                offset: self.segment_start,
433                limit: self.max_segment_bytes,
434            });
435        }
436        Ok((value, span))
437    }
438
439    /// Fast scan for the segment tag (exactly 3 ASCII uppercase letters).
440    fn read_tag(&mut self) -> Result<Option<Token<'a>>, EdifactError> {
441        self.skip_inter_segment_whitespace();
442        if self.pos >= self.input.len() {
443            return Ok(None);
444        }
445        let start = self.pos;
446        // A segment tag is terminated by the element separator or segment terminator.
447        // Bound the scan to max_segment_bytes + 1 so adversarial input with no delimiters
448        // cannot force memchr to scan arbitrarily large buffers before we return an error.
449        let input_remaining = &self.input[self.pos..];
450        let scan_limit = self
451            .max_segment_bytes
452            .saturating_add(1)
453            .min(input_remaining.len());
454        let remaining = &input_remaining[..scan_limit];
455        // Take the *nearest* of the two terminating delimiters.  Searching for
456        // the element separator first and only falling back to the segment
457        // terminator would run straight past the terminator of an element-less
458        // segment (`UNZ'…`) and swallow the following segment's tag.
459        let end = memchr2(self.ssa.element_sep, self.ssa.segment_term, remaining)
460            .unwrap_or(remaining.len());
461
462        if end == 0 {
463            // First byte is already a delimiter — tag is zero-length, which is invalid.
464            let byte = self.input[self.pos];
465            self.pos += 1;
466            return Err(EdifactError::InvalidDelimiter {
467                byte,
468                offset: start,
469            });
470        }
471
472        // Enforce the per-segment byte-length guard in read_tag as well.
473        // Without this check, adversarial input with no delimiters could cause
474        // memchr to scan the entire remaining buffer (potentially hundreds of MB).
475        if end > self.max_segment_bytes {
476            // Advance past the offending bytes so the iterator can continue.
477            self.pos = start + end;
478            return Err(EdifactError::SegmentTooLong {
479                offset: start,
480                limit: self.max_segment_bytes,
481            });
482        }
483        let tag_bytes = &self.input[start..start + end];
484        // Always advance pos so errors cannot cause an infinite retry loop.
485        self.pos = start + end;
486        // Record segment start for the size-limit check in read_value.
487        self.segment_start = start;
488        let tag = std::str::from_utf8(tag_bytes)
489            .map_err(|_| EdifactError::InvalidSegmentTag(format!("{tag_bytes:?}")))?;
490        if tag.len() != 3 || !tag.bytes().all(|b| b.is_ascii_uppercase()) {
491            return Err(EdifactError::InvalidSegmentTag(tag.to_owned()));
492        }
493        self.state = TokState::InSegment;
494        Ok(Some(Token::SegmentTag {
495            value: tag,
496            span: Span::new(start, start + end),
497        }))
498    }
499}
500
501impl<'a> Iterator for Tokenizer<'a> {
502    type Item = Result<Token<'a>, EdifactError>;
503
504    fn next(&mut self) -> Option<Self::Item> {
505        loop {
506            if self.pos >= self.input.len() {
507                return None;
508            }
509
510            match self.state {
511                TokState::ExpectTag => {
512                    return match self.read_tag() {
513                        Ok(Some(tok)) => Some(Ok(tok)),
514                        Ok(None) => None,
515                        Err(e) => Some(Err(e)),
516                    };
517                }
518                TokState::InSegment => {
519                    let b = self.input[self.pos];
520                    let (elem, comp, term) = (
521                        self.ssa.element_sep,
522                        self.ssa.component_sep,
523                        self.ssa.segment_term,
524                    );
525
526                    if b == term {
527                        let start = self.pos;
528                        self.pos += 1;
529                        self.state = TokState::ExpectTag;
530                        return Some(Ok(Token::SegmentTerminator {
531                            span: Span::new(start, self.pos),
532                        }));
533                    } else if b == elem {
534                        self.pos += 1;
535                        let (value, span) = match self.read_value() {
536                            Ok(value) => value,
537                            Err(error) => return Some(Err(error)),
538                        };
539                        // Peek: is the *next* byte a component sep?
540                        // We emit DataElement for the leading sub-element regardless;
541                        // subsequent components within the same element are ComponentElement.
542                        return Some(Ok(Token::DataElement { value, span }));
543                    } else if b == comp {
544                        self.pos += 1;
545                        let (value, span) = match self.read_value() {
546                            Ok(value) => value,
547                            Err(error) => return Some(Err(error)),
548                        };
549                        return Some(Ok(Token::ComponentElement { value, span }));
550                    } else if b == b'\r' || b == b'\n' {
551                        self.pos += 1;
552                        // inter-element whitespace inside a segment — skip
553                        continue;
554                    } else {
555                        // Unexpected byte inside a segment — skip it and report.
556                        let offset = self.pos;
557                        self.pos += 1; // always advance to prevent infinite retry loop
558                        self.state = TokState::ExpectTag;
559                        return Some(Err(EdifactError::InvalidDelimiter { byte: b, offset }));
560                    }
561                }
562            }
563        }
564    }
565}
566
567#[cfg(test)]
568mod tests {
569    use super::*;
570
571    fn tokens(input: &[u8]) -> Vec<Token<'_>> {
572        let ssa = ServiceStringAdvice::from_bytes_unchecked(input);
573        Tokenizer::new(input, ssa)
574            .collect::<Result<Vec<_>, _>>()
575            .expect("tokenize failed")
576    }
577
578    #[test]
579    fn minimal_unb_unz() {
580        let input = b"UNB+UNOA:1+SENDER+RECEIVER+200101:0900+1'UNZ+0+1'";
581        let toks = tokens(input);
582        assert!(matches!(toks[0], Token::SegmentTag { value: "UNB", .. }));
583        // should end with UNZ terminator
584        assert!(matches!(toks.last(), Some(Token::SegmentTerminator { .. })));
585    }
586
587    #[test]
588    fn release_character_not_a_delimiter() {
589        // `?+` inside a value must NOT produce a DataElement split
590        let input = b"BGM+220+test?+value'";
591        let toks = tokens(input);
592        // Elements after BGM tag: "220", "test?+value"
593        let vals: Vec<_> = toks
594            .iter()
595            .filter_map(|t| {
596                if let Token::DataElement { value, .. } = t {
597                    Some(*value)
598                } else {
599                    None
600                }
601            })
602            .collect();
603        assert_eq!(vals, vec!["220", "test?+value"]);
604    }
605
606    #[test]
607    fn custom_una_delimiters() {
608        // UNA with `;` as element sep
609        let input = b"UNA:;.? 'BGM;220;hello'";
610        let toks = tokens(input);
611        assert!(matches!(toks[0], Token::SegmentTag { value: "BGM", .. }));
612        let vals: Vec<_> = toks
613            .iter()
614            .filter_map(|t| {
615                if let Token::DataElement { value, .. } = t {
616                    Some(*value)
617                } else {
618                    None
619                }
620            })
621            .collect();
622        assert!(vals.contains(&"220"));
623    }
624
625    #[test]
626    fn tokens_expose_spans() {
627        let input = b"BGM+220+ABC'";
628        let toks = tokens(input);
629        assert!(matches!(
630            toks[0],
631            Token::SegmentTag {
632                value: "BGM",
633                span: Span { start: 0, end: 3 }
634            }
635        ));
636        assert!(matches!(
637            toks[1],
638            Token::DataElement {
639                value: "220",
640                span: Span { start: 4, end: 7 }
641            }
642        ));
643    }
644
645    #[test]
646    fn truncated_input_does_not_panic() {
647        let input = b"UNB+UNOA:1"; // no terminator
648        let _: Vec<_> = Tokenizer::new(input, ServiceStringAdvice::default()).collect();
649        // must not panic regardless of result
650    }
651
652    #[test]
653    fn invalid_segment_tags_are_rejected() {
654        for input in [
655            &b"bgm+220+'"[..],
656            &b"ABCDE+220+'"[..],
657            &b"BGM1+220+'"[..],
658            &b"BGM +220+'"[..],
659            &b" BG+220+'"[..],
660        ] {
661            let result = Tokenizer::new(input, ServiceStringAdvice::default())
662                .collect::<Result<Vec<_>, _>>();
663            assert!(result.is_err(), "expected tag rejection for {input:?}");
664        }
665    }
666
667    #[test]
668    fn element_less_segment_does_not_swallow_the_next_tag() {
669        // `read_tag` must stop at the *nearest* of element-separator and
670        // segment-terminator.  Scanning for `+` first would run past the `'`
671        // and produce the bogus tag "UNZ'UNB".
672        let segs: Vec<_> = crate::from_bytes(b"UNZ'UNB+A'")
673            .collect::<Result<Vec<_>, _>>()
674            .expect("element-less segment must parse");
675        assert_eq!(
676            segs.iter().map(|s| s.tag).collect::<Vec<_>>(),
677            vec!["UNZ", "UNB"]
678        );
679        assert!(segs[0].elements.is_empty());
680    }
681
682    #[test]
683    fn release_heavy_value_is_bounded_by_the_segment_guard() {
684        // A value consisting solely of release sequences and no delimiter must
685        // trip the per-segment guard rather than scanning the whole input once
686        // per release sequence (which was quadratic).
687        let mut input = b"BGM+".to_vec();
688        input.extend(std::iter::repeat_n(b"?a".as_slice(), 200_000).flatten());
689        let err = crate::from_bytes(&input)
690            .collect::<Result<Vec<_>, _>>()
691            .expect_err("oversized segment must be rejected");
692        assert!(
693            matches!(err, EdifactError::SegmentTooLong { .. }),
694            "expected SegmentTooLong, got {err:?}"
695        );
696    }
697
698    #[test]
699    fn escaped_terminator_inside_a_value_is_not_a_segment_break() {
700        // Exercises the cached-terminator refresh path: the first `'` is escaped,
701        // so the scan must resume past it and find the real terminator.
702        let segs: Vec<_> = crate::from_bytes(b"FTX+a?'b+c'")
703            .collect::<Result<Vec<_>, _>>()
704            .expect("escaped terminator must parse");
705        assert_eq!(segs.len(), 1);
706        assert_eq!(segs[0].element_str(0), Some("a'b"));
707        assert_eq!(segs[0].element_str(1), Some("c"));
708    }
709
710    #[test]
711    fn chunked_reader_parses_via_parser() {
712        // The reader tokenizer path was removed; verify the equivalent via the parser.
713        let input = b"UNA:+.? 'BGM+220+test?+value'UNT+2+1'";
714        let segments =
715            crate::parser::from_bufread(std::io::BufReader::new(std::io::Cursor::new(input)))
716                .expect("parser should succeed");
717        assert!(segments.iter().any(|s| s.tag == "BGM"));
718        // The release sequence '?+' inside 'test?+value' should survive in the element.
719        let bgm = segments.iter().find(|s| s.tag == "BGM").unwrap();
720        let raw_val = bgm
721            .elements
722            .get(1)
723            .and_then(|e| e.components.first())
724            .map(|(s, _)| s.as_str());
725        assert_eq!(raw_val, Some("test+value"));
726    }
727}