1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
//! `edifact` — EDIFACT (ISO 9735) for Rust: zero-copy parser, a writer that
//! computes its envelope, typed (de)serialization, layered validation, `DTM`
//! dates and `CONTRL` generation. Bounded by default against hostile input.
//!
//! # Quick start
//! ```
//! use edifact::from_bytes;
//! let input = b"UNB+UNOA:1+SENDER+RECEIVER+200101:0900+1'UNZ+0+1'";
//! let segments: Vec<_> = from_bytes(input).collect::<Result<_, _>>().unwrap();
//! assert_eq!(segments[0].tag, "UNB");
//! ```
//!
//! # One segment type, borrowed or owned
//!
//! [`Segment<'a>`] holds its text as [`Cow<'a, str>`][std::borrow::Cow], which is
//! what lets a single type cover both parsing modes:
//!
//! - [`from_bytes`] yields `Segment<'input>` whose text borrows from the input
//! ([`Cow::Borrowed`][std::borrow::Cow::Borrowed]) unless a release escape
//! forced a copy; a segment's own allocation is its element vector.
//! - [`from_reader`] has no buffer to borrow from and yields `Segment<'static>`,
//! aliased as [`OwnedSegment`], with every non-empty value owned.
//!
//! `Segment` is covariant in `'a`, so `&[OwnedSegment]` is accepted anywhere
//! `&[Segment<'_>]` is wanted: one API serves both paths, with no conversion.
//!
//! ```
//! use edifact::{OwnedSegment, Segment};
//!
//! fn count_bgm(segments: &[Segment<'_>]) -> usize {
//! segments.iter().filter(|s| s.tag == "BGM").count()
//! }
//!
//! let borrowed: Vec<Segment<'_>> =
//! edifact::from_bytes(b"BGM+220'").collect::<Result<_, _>>()?;
//! let owned: Vec<OwnedSegment> =
//! edifact::from_reader(std::io::Cursor::new(b"BGM+220'")).collect::<Result<_, _>>()?;
//!
//! assert_eq!(count_bgm(&borrowed), 1);
//! assert_eq!(count_bgm(&owned), 1);
//! # Ok::<(), edifact::EdifactError>(())
//! ```
//!
//! # Crate features
//!
//! - `derive` (enabled by default): re-exports the derive macros from
//! `edifact-derive` — [`EdifactDeserialize`][macro@EdifactDeserialize] /
//! [`EdifactSerialize`][macro@EdifactSerialize] for segment and message
//! structs, and
//! [`EdifactCompositeDeserialize`][macro@EdifactCompositeDeserialize] /
//! [`EdifactCompositeSerialize`][macro@EdifactCompositeSerialize] for the
//! composite-element structs they reference.
//! - `diagnostics` (off by default): [`EdifactError`], [`ValidationIssue`] and
//! [`ValidationReport`] implement `miette::Diagnostic` (code, severity, help;
//! issues also carry labelled spans).
//! - `serde` (off by default): `Serialize` / `Deserialize` for
//! [`ValidationReport`], [`ValidationIssue`], and the envelope types.
//! - `dtm` (off by default, no dependencies): [`dtm`], the UNCL 2379 codec for
//! `DTM` values — decode, format, compare, build and validate.
//! - `dtm-time` (off by default): `dtm` plus conversions to and from the
//! [`time`](https://docs.rs/time/0.3) crate.
//!
//! Features are additive: each adds items and trait impls, and none changes
//! parsing or validation behaviour.
//!
//! # Parse and text contracts
//!
//! Parsing is strict and deterministic:
//!
//! - A byte order mark and any whitespace before the first service segment are
//! skipped — ISO 9735 authorises neither, but both arrive constantly. The
//! repertoire sniff ([`sniff_charset`]) skips the same prologue.
//! - A segment that ends without its terminator is a **truncation** (`E001`,
//! [`EdifactError::UnexpectedEof`]):
//! accepting it would let a file cut off mid-transfer parse as complete.
//! - Segment and element text must decode as UTF-8 (`E003`).
//! - A release character must escape exactly one following byte; a trailing `?`
//! at end-of-input is rejected (`E019`).
//! - Input is bounded by default: 64 KiB per segment, 16 MiB per message,
//! 256 MiB per input ([`ReaderConfig`]). A budget **reports** a violation
//! (`E020`, `E036`) instead of ending the iterator, which would look like a
//! clean end of input.
//! - The service characters are discovered the way ISO 9735-1 says a receiver
//! should discover them: from a leading `UNA` if there is one, otherwise the
//! §5.1 defaults with the repetition separator resolved from the syntax
//! version in `UNB` S001 DE 0002 — active as `*` for version 4, inactive for
//! versions 1–3, where `*` is ordinary data. Override both with
//! [`ReaderConfig::with_service_string_advice`] when parsing a fragment that
//! carries neither header.
//! - When the repetition separator is active, repeating data elements are split
//! into [`Element::repetitions`] rather than left glued into the value
//! (ISO 9735-1 §8.7).
//!
//! These contracts hold identically for [`from_bytes`] and [`from_reader`]: the
//! same bytes give equal segments with equal spans, or the same error at the
//! same offset, however the reader chunks its input.
//!
//! ```
//! use edifact::from_reader;
//! use std::io::Cursor;
//!
//! let input = b"UNA:;.? 'BGM;220;test?;value'";
//! let segments: Vec<_> = from_reader(Cursor::new(&input[..]))
//! .collect::<Result<Vec<_>, _>>()
//! .unwrap();
//! assert_eq!(segments.len(), 1);
//! assert_eq!(segments[0].tag, "BGM");
//! assert_eq!(segments[0].element_str(0), Some("220"));
//! assert_eq!(segments[0].element_str(1), Some("test;value"));
//! ```
//!
//! # Validation
//!
//! [`ValidationContext`] runs switchable envelope, syntax, charset, structure,
//! code-list and profile layers into one [`ValidationReport`]. Every
//! [`ValidationIssue`] says which layer found it, which pack produced it and,
//! for the built-in checks, what kind of fault it is ([`FindingKind`]):
//!
//! ```
//! use edifact::{ProfileRulePack, ValidationContext, ValidationIssue, ValidationSeverity, from_bytes};
//!
//! let pack = ProfileRulePack::new("ORDERS-DEMO")
//! .for_message_type("ORDERS")
//! .with_rule_fn(|segments, issues| {
//! if !segments.iter().any(|s| s.tag == "BGM") {
//! issues.push(
//! ValidationIssue::new(ValidationSeverity::Error, "ORDERS requires a BGM")
//! .with_rule_id("DEMO-P001"),
//! );
//! }
//! });
//!
//! let segments: Vec<_> = from_bytes(b"UNH+1+ORDERS:D:96A:UN'DTM+137:1:102'UNT+3+1'")
//! .collect::<Result<_, _>>()?;
//! let report = ValidationContext::builder().with_profile_pack(pack).build().validate(&segments);
//!
//! assert_eq!(report.filter_by_rule_prefix("DEMO-").total_issues(), 1);
//! let issue = &report.errors()[0];
//! assert_eq!(issue.layer(), Some(edifact::ValidationLayer::Profile));
//! assert_eq!(issue.pack(), Some("ORDERS-DEMO"));
//! # Ok::<(), edifact::EdifactError>(())
//! ```
//!
//! Guides: [validation](https://hupe1980.github.io/edifact/docs/validation/),
//! [segment groups](https://hupe1980.github.io/edifact/docs/segment-groups/),
//! [profile packs](https://hupe1980.github.io/edifact/docs/profile-packs/).
//!
//! # Writing
//!
//! An interchange is built from a typed [`InterchangeHeader`];
//! [`InterchangeBuilder`], [`MessageBuilder`] and [`Writer`] compute `UNT` and
//! `UNZ`. A message dropped without `finish()` gets no `UNT`, and a writer whose
//! sink failed is poisoned (`E072`). See the
//! [writing guide](https://hupe1980.github.io/edifact/docs/writing/).
//!
//! # Async usage
//!
//! There is no native `async` API: parsing is CPU work over a buffer. Read with
//! your runtime and parse synchronously; the
//! [async integration guide](https://hupe1980.github.io/edifact/docs/async-integration/)
//! shows the patterns, including `spawn_blocking` for large files.
//!
//! ```rust,no_run
//! # async fn example(mut reader: impl tokio::io::AsyncReadExt + Unpin)
//! # -> Result<(), Box<dyn std::error::Error>> {
//! let mut buf = Vec::new();
//! reader.read_to_end(&mut buf).await?;
//! let segments: Vec<_> = edifact::from_bytes(&buf).collect::<Result<Vec<_>, _>>()?;
//! # let _ = segments;
//! # Ok(())
//! # }
//! ```
//!
//! # Security
//!
//! Every malformed or over-budget input is a typed [`EdifactError`], never a
//! panic. Error text escapes control and bidirectional characters from the
//! input. The defaults bound every entry point; size [`ReaderConfig`] to your
//! traffic. The [threat model](threat_model) lists the adversary, the scope,
//! and every known threat class with its status and evidence.
// ── core modules ──────────────────────────────────────────────────────────────
/// EDIFACT character repertoires (`UNB` S001 DE 0001) and transcoding.
/// `CONTRL` — the ISO 9735-4 syntax and service report message.
pub
/// Error types and validation reporting primitives.
pub
pub
/// Core zero-copy and owned EDIFACT data model types.
pub
pub
/// Validation report types: [`ValidationSeverity`], [`ValidationIssue`], [`ValidationReport`].
///
/// These types are also re-exported from the crate root.
/// ISO 9735 service-segment definitions: envelope, package, `UGH`/`UGT` and `CONTRL` segments.
pub
pub
pub
// ── typed serialization layer ─────────────────────────────────────────────────
pub
// ── flat re-exports: core ─────────────────────────────────────────────────────
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use severity_for_error;
pub use ;
pub use ;
pub use ;
pub use ;
// ── flat re-exports: serde ────────────────────────────────────────────────────
/// User-facing deserialization API.
pub use ;
// ── Proc-macro support ─────────────────────────────────────────────────────────
pub use ;
pub use ;
pub use ;
pub use ;
// ── core free functions ───────────────────────────────────────────────────────
use ;
/// Iterator returned by [`from_bytes`].
/// Iterator returned by [`from_reader`].
///
/// # Resource bounds
///
/// As [`from_reader`]: the [`ReaderConfig::default()`][ReaderConfig] limits
/// apply. Memory is one segment plus an 8 KiB read buffer.
/// Parse `input` bytes into an iterator of [`Segment`]s.
///
/// Borrows its text directly from `input`. A segment costs one allocation for
/// its element vector (at its exact length; none for a segment without
/// elements), one per value that contained a release sequence and so had to be
/// unescaped into an owned `String`, and occasionally one to grow the parser's
/// reusable element buffer. Elements that do not repeat allocate nothing for
/// repetitions. Asserted by the `allocation_budget` integration test.
///
/// # Resource bounds
///
/// [`ReaderConfig::default()`][ReaderConfig] applies: 64 KiB per segment,
/// 16 MiB per message, 256 MiB in total. The iterator holds one segment;
/// collecting the whole input into a `Vec` takes up to 128 × its bytes in heap
/// (`allocation_budget::worst_case_window_heap_within_factor`), so stream
/// untrusted input instead. Use [`from_bytes_with_config`] to change the
/// limits, [`ReaderConfig::unbounded`] for trusted input.
///
/// # Same answer as the reader path
///
/// [`from_reader`] and [`from_bufread`] return exactly what this returns for
/// the same bytes — equal segments with equal spans, or the same error with
/// the same offset — however the reader chunks its input. The
/// `parse_path_parity` integration tests (one per divergence class plus an
/// exhaustive sweep over short inputs) and the `fuzz_parity_*` bolero targets
/// assert this.
/// Parse `input` bytes into an iterator of [`Segment`]s with explicit configuration.
///
/// Every [`ReaderConfig`] limit is enforced as a **hard cap that yields an error**,
/// never as a silent stop:
///
/// - `max_segment_bytes` — [`EdifactError::SegmentTooLong`] when a single segment
/// exceeds the threshold.
/// - `max_segments`, `max_messages`, `max_message_bytes`,
/// `max_input_bytes` — [`EdifactError::LimitExceeded`] when the input carries
/// more than the budget, at the start of the offending segment (or at the
/// byte budget itself).
///
/// `max_input_bytes` counts every byte of `input` the parser would consume,
/// trailing whitespace included: bytes beyond it are
/// never examined, and their mere presence is the violation. The reader path
/// gives the same answer for the same bytes.
///
/// A budget that merely ended the iterator would be indistinguishable from a clean
/// end of input, so a caller collecting into a `Vec` would silently accept a
/// **truncated** interchange as a complete one. Input that ends exactly at a limit
/// is not a violation and finishes normally.
///
/// `ReaderConfig::default()` bounds segments (64 KiB), messages (16 MiB) and the
/// input (256 MiB); `ReaderConfig::unbounded()` lifts every limit.
///
/// # Example
///
/// ```
/// use edifact::{EdifactError, ReaderConfig, from_bytes_with_config};
///
/// // Exactly at the limit: fine.
/// let cfg = ReaderConfig::default().max_segments(1);
/// assert!(from_bytes_with_config(b"BGM+220'", cfg).collect::<Result<Vec<_>, _>>().is_ok());
///
/// // One segment too many: a loud error, not a quiet truncation.
/// let err = from_bytes_with_config(b"BGM+220'DTM+137'", cfg)
/// .collect::<Result<Vec<_>, _>>()
/// .unwrap_err();
/// assert!(matches!(
/// err,
/// EdifactError::LimitExceeded { limit: "max_segments", max: 1, offset: 8, .. }
/// ));
/// ```
/// Scan `input` without stopping at the first fault.
///
/// Yields every segment [`from_bytes_with_config`] would yield — the same
/// segments, with the same absolute spans — and, where the strict parser stops,
/// a [`Fault`][recover::Fault] carrying the strict error, then resumes after the
/// faulted segment's terminator. Every [`ReaderConfig`] limit in
/// `config` applies, plus a fault budget; a terminal fault ends the scan.
///
/// This is the lazy form of [`RecoveredInterchange::scan`], which also derives
/// the `UNB` addressing, the message windows and the `CONTRL` location of every
/// fault. See the [`recover`] module for the full contract.
///
/// # Example
///
/// ```
/// use edifact::recover::Scanned;
/// use edifact::{RecoveryConfig, scan_recovering};
///
/// let input = b"UNH+1+ORDERS:D:96A:UN'BGM+220'\xFF'UNT+4+1'";
/// let items: Vec<Scanned<'_>> = scan_recovering(input, &RecoveryConfig::default()).collect();
///
/// let tags: Vec<_> = items.iter().map(|item| item.tag()).collect();
/// assert_eq!(tags, [Some("UNH"), Some("BGM"), None, Some("UNT")]);
/// assert_eq!(items[2].as_fault().unwrap().error().stable_code(), "E006");
/// ```
/// Parse a reader into a lazy iterator of [`OwnedSegment`]s.
///
/// Returns a [`FromReaderIter`] that parses and yields segments on demand,
/// keeping memory bounded. `.collect::<Result<Vec<_>, _>>()` when you do want
/// them all in memory.
///
/// # Resource bounds
///
/// [`ReaderConfig::default()`][ReaderConfig] applies: 64 KiB per segment,
/// 16 MiB per message, at most 256 MiB read. Memory is one segment plus an
/// 8 KiB read buffer. Use [`from_reader_with_config`] to change the limits,
/// [`ReaderConfig::unbounded`] for trusted input.
///
/// # Errors
///
/// Each `next()` call yields `Some(Ok(segment))` for a successfully parsed
/// segment, `Some(Err(EdifactError))` for a parse or I/O failure, and `None`
/// when the end of the stream has been reached.
///
/// Apart from I/O failures, the items are exactly those [`from_bytes`] yields
/// for the same bytes, whatever sizes the reader's reads return (asserted by
/// the `parse_path_parity` tests and the `fuzz_parity_*` bolero targets).
/// Parse a byte slice, decoding it from the repertoire its own `UNB` declares.
///
/// [`decode_interchange`] followed by [`from_bytes`], in one call that a
/// caller cannot forget to make. Forgetting is the failure mode worth designing
/// against: a `UNOC` corpus stored as UTF-8 parses fine, so the tests pass and
/// the first *conformant* counterparty message — the one with `ü` as the single
/// byte `0xFC` — is rejected as invalid text.
///
/// Segments are owned because the decoded buffer is this function's, not the
/// caller's: an ISO 8859-1 payload has to be transcoded to exist as UTF-8 at
/// all. When the payload is already ASCII or `UNOY`, decoding borrows and copies
/// nothing, but the segments are still owned — reach for
/// [`decode_interchange`] plus [`from_bytes`] when you want to keep the
/// zero-copy path and hold the buffer yourself.
///
/// # Resource bounds
///
/// [`ReaderConfig::default()`][ReaderConfig] applies to the decoded bytes (a
/// Latin-1 interchange can double in length). The result holds every segment:
/// up to 128 × the decoded bytes in heap. Stream untrusted input with
/// [`from_reader_decoded`] instead.
///
/// # Errors
///
/// As [`decode_interchange`], plus any parse error.
///
/// # Example
///
/// ```
/// // A conformant UNOC interchange: `Müller` is `4D FC 6C 6C 65 72`.
/// let mut raw = b"UNB+UNOC:3+S+R+260101:0900+IC1'NAD+BY+M".to_vec();
/// raw.push(0xFC);
/// raw.extend_from_slice(b"ller'UNZ+0+IC1'");
///
/// // Parsing it directly fails — it is not UTF-8, and it never claimed to be.
/// assert!(edifact::from_bytes(&raw).collect::<Result<Vec<_>, _>>().is_err());
///
/// let segments = edifact::from_bytes_decoded(&raw)?;
/// assert_eq!(segments[1].element_str(1), Some("Müller"));
/// # Ok::<(), edifact::EdifactError>(())
/// ```
/// [`from_bytes_decoded`] with explicit [`ReaderConfig`] limits.
///
/// # Errors
///
/// As [`from_bytes_decoded`], and the same error
/// [`from_reader_decoded_with_config`] yields for `input`: the fault or limit
/// the input reaches first, a byte the repertoire leaves undefined included.
/// Parse a reader, decoding it from the repertoire the stream's own `UNB`
/// declares — **lazily**.
///
/// [`decode_reader`] has to read far enough to find the `UNB` before it can
/// answer, so it returns a `Result` — and a `?` on it turns a lazy pipeline
/// eager, forcing the caller to box the iterator or wrap the error in a
/// one-item chain. This does the sniff on the first `next()` instead, so the
/// signature stays a plain `Iterator` and a decode failure arrives as its first
/// item, exactly like a parse failure does.
///
/// # Resource bounds
///
/// [`ReaderConfig::default()`][ReaderConfig] applies to the decoded stream:
/// 64 KiB per segment, 16 MiB per message, 256 MiB in total. Memory is one
/// segment, the 8 KiB sniff head and two 8 KiB buffers.
///
/// # Example
///
/// ```
/// let mut raw = b"UNB+UNOC:3+S+R+260101:0900+IC1'NAD+BY+M".to_vec();
/// raw.push(0xFC);
/// raw.extend_from_slice(b"ller'UNZ+0+IC1'");
///
/// // No `?` before the loop: the pipeline stays lazy.
/// let segments: Vec<_> = edifact::from_reader_decoded(std::io::Cursor::new(raw))
/// .collect::<Result<Vec<_>, _>>()?;
/// assert_eq!(segments[1].element_str(1), Some("Müller"));
/// # Ok::<(), edifact::EdifactError>(())
/// ```
/// [`from_reader_decoded`] with explicit [`ReaderConfig`] limits.
///
/// # Resource bounds
///
/// Every limit in `config` applies to the **decoded** UTF-8 stream: a Latin-1
/// interchange can be up to twice as long after decoding, so `max_input_bytes`
/// admits at least half as many raw bytes. Memory is one segment of at most
/// `max_segment_bytes`, the 8 KiB sniff head and two 8 KiB buffers.
///
/// # Errors
///
/// Yielded as items, in input order: a byte the repertoire leaves undefined
/// is [`EdifactError::InvalidText`] at its raw offset, after the segments
/// before it. When the prologue runs past `max_input_bytes` before the sniff
/// window refuses it, the `max_input_bytes` limit is reported.
/// Lazy iterator returned by [`from_reader_decoded`].
///
/// Sniffs the interchange's repertoire on the first `next()`, so constructing it
/// cannot fail and the caller keeps a plain `Iterator`.
///
/// # Resource bounds
///
/// As [`from_reader_decoded_with_config`]: the configured limits count decoded
/// bytes; memory is one segment plus the sniff head and two 8 KiB buffers.
type DecodedReader<R> = DecodingReader;
/// Report whichever limit the input reaches first: a sniff-window refusal at
/// an offset beyond `max_input_bytes` becomes the input limit.
/// Serialize `segments` to an [`std::io::Write`] implementation.
///
/// # Errors
///
/// Returns an error if writing fails or if segment serialization fails.
/// Serialize `segments` to an owned `Vec<u8>`.
///
/// Accepts segments from either parsing path: `&[OwnedSegment]` coerces to
/// `&[Segment<'_>]`.
///
/// # Errors
///
/// Returns an error if serialization fails.
///
/// # Example
///
/// ```
/// let segments: Vec<_> = edifact::from_bytes(b"BGM+220+PO-1'")
/// .collect::<Result<Vec<_>, _>>()?;
/// assert_eq!(edifact::segments_to_bytes(&segments)?, b"BGM+220+PO-1'".to_vec());
/// # Ok::<(), edifact::EdifactError>(())
/// ```
/// Compiles and runs every ```` ```rust ```` block in the published guides as a
/// doctest.
///
/// A rename that breaks a guide breaks the build.
///
/// Blocks that genuinely cannot run (they need a live socket, a real directory
/// file, or a downstream crate) should be marked ```` ```rust,ignore ```` or
/// ```` ```rust,no_run ```` in the guide itself.