hl7probe 0.7.0

Inspect and validate HL7 v2 messages from the command line
Documentation
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
941
942
943
944
945
946
947
948
//! HL7 v2 lexical parser: MLLP/batch stripping, segment/field/component/subcomponent
//! decomposition and escape-sequence handling.

use std::fmt::Write as _;

use std::fmt;

/// The five delimiters an HL7 v2 message declares in MSH-1 and MSH-2.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Separators {
    pub field: char,
    pub component: char,
    pub repetition: char,
    pub escape: char,
    pub subcomponent: char,
}

impl Default for Separators {
    fn default() -> Self {
        Self {
            field: '|',
            component: '^',
            repetition: '~',
            escape: '\\',
            subcomponent: '&',
        }
    }
}

impl Separators {
    /// Reads MSH-1 (the character right after `MSH`) and MSH-2 (the encoding
    /// characters up to the next field separator).
    fn from_msh(line: &str) -> Result<Self, ParseError> {
        let mut chars = line.chars();
        // MSH-1 is the character straight after the segment name.
        let (Some(_), Some(_), Some(_), Some(field)) =
            (chars.next(), chars.next(), chars.next(), chars.next())
        else {
            return Err(ParseError::new(
                0,
                "MSH segment is truncated before the field separator",
            ));
        };
        if field.is_alphanumeric() || field.is_whitespace() {
            return Err(ParseError::new(
                0,
                format!("MSH-1 field separator {field:?} is not a usable delimiter"),
            ));
        }
        let mut sep = Self {
            field,
            ..Default::default()
        };
        // MSH-2 declares up to four encoding characters, ending at the next
        // field separator. Read straight off the iterator: this runs for every
        // message in a batch, and collecting five characters into a Vec first
        // cost three allocations a message.
        let mut encoding = chars.take_while(|c| *c != field);
        if let Some(c) = encoding.next() {
            sep.component = c;
        }
        if let Some(c) = encoding.next() {
            sep.repetition = c;
        }
        if let Some(c) = encoding.next() {
            sep.escape = c;
        }
        if let Some(c) = encoding.next() {
            sep.subcomponent = c;
        }
        // Anything left means all four slots were filled and more followed.
        let extra = encoding.count();
        if extra > 0 {
            return Err(ParseError::new(
                0,
                format!(
                    "MSH-2 declares {} encoding characters, expected at most 4",
                    4 + extra
                ),
            ));
        }
        let all = [
            sep.field,
            sep.component,
            sep.repetition,
            sep.escape,
            sep.subcomponent,
        ];
        for i in 0..all.len() {
            for j in (i + 1)..all.len() {
                if all[i] == all[j] {
                    return Err(ParseError::new(
                        0,
                        format!("delimiter {:?} is declared twice in MSH-1/MSH-2", all[i]),
                    ));
                }
            }
        }
        Ok(sep)
    }
}

#[derive(Debug, Clone)]
pub struct ParseError {
    pub line: usize,
    pub message: String,
}

impl ParseError {
    fn new(line: usize, message: impl Into<String>) -> Self {
        Self {
            line,
            message: message.into(),
        }
    }

    /// The whole input held nothing that looks like an HL7 message.
    pub(crate) fn no_message() -> Self {
        Self::new(0, "no MSH segment found - is this an HL7 v2 message?")
    }
}

impl std::error::Error for ParseError {}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.line > 0 {
            write!(f, "line {}: {}", self.line, self.message)
        } else {
            write!(f, "{}", self.message)
        }
    }
}

/// A single component, itself made of `&`-delimited subcomponents.
///
/// This and its siblings are views over the segment line, not owned trees: a
/// field carries the text it occupied and splits it when asked. HL7 leaves are
/// two or three characters on average, so building a `Vec<String>` for each one
/// cost far more than the text it held.
#[derive(Debug, Clone, Copy)]
pub struct Component<'a> {
    raw: &'a str,
    sep: Separators,
    /// MSH-1 and MSH-2 are the delimiters themselves and must never be split.
    literal: bool,
}

impl<'a> Component<'a> {
    #[must_use]
    pub fn sub(&self, seq: usize) -> &'a str {
        self.subs().nth(seq.wrapping_sub(1)).unwrap_or("")
    }

    pub fn subs(&self) -> impl Iterator<Item = &'a str> {
        split(self.raw, self.sep.subcomponent, self.literal)
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        if self.literal {
            return self.raw.is_empty();
        }
        self.raw.chars().all(|c| c == self.sep.subcomponent)
    }
}

/// One repetition of a field (`~`-delimited at the field level).
#[derive(Debug, Clone, Copy)]
pub struct Repetition<'a> {
    raw: &'a str,
    sep: Separators,
    literal: bool,
}

impl<'a> Repetition<'a> {
    #[must_use]
    pub fn comp(&self, seq: usize) -> Component<'a> {
        Component {
            raw: self.comp_text(seq),
            sep: self.sep,
            literal: self.literal,
        }
    }

    pub fn comps(&self) -> impl Iterator<Item = Component<'a>> {
        let (sep, literal) = (self.sep, self.literal);
        split(self.raw, self.sep.component, self.literal).map(move |raw| Component {
            raw,
            sep,
            literal,
        })
    }

    /// Component `seq` as text, or `""` when the repetition has no such
    /// component.
    #[must_use]
    pub fn comp_text(&self, seq: usize) -> &'a str {
        split(self.raw, self.sep.component, self.literal)
            .nth(seq.wrapping_sub(1))
            .unwrap_or("")
    }

    /// The repetition as it appeared, component separators included.
    #[must_use]
    pub const fn text(&self) -> &'a str {
        self.raw
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        if self.literal {
            return self.raw.is_empty();
        }
        self.raw
            .chars()
            .all(|c| c == self.sep.component || c == self.sep.subcomponent)
    }

    /// Number of components actually carrying data.
    #[must_use]
    pub fn filled_comps(&self) -> usize {
        self.comps()
            .enumerate()
            .filter(|(_, c)| !c.is_empty())
            .map(|(i, _)| i + 1)
            .last()
            .unwrap_or(0)
    }
}

/// A field: one or more repetitions.
#[derive(Debug, Clone, Copy)]
pub struct Field<'a> {
    raw: &'a str,
    sep: Separators,
    literal: bool,
}

impl<'a> Field<'a> {
    #[must_use]
    pub fn is_empty(&self) -> bool {
        if self.literal {
            return self.raw.is_empty();
        }
        self.raw.chars().all(|c| {
            c == self.sep.repetition || c == self.sep.component || c == self.sep.subcomponent
        })
    }

    /// HL7 explicit null: the two-character value `""` means "delete this value".
    #[must_use]
    pub fn is_null(&self) -> bool {
        self.rep_count() == 1
            && split(self.raw, self.sep.component, self.literal).count() == 1
            && self.rep(1).comp(1).sub(1) == "\"\""
    }

    #[must_use]
    pub fn rep(&self, seq: usize) -> Repetition<'a> {
        Repetition {
            raw: split(self.raw, self.sep.repetition, self.literal)
                .nth(seq.wrapping_sub(1))
                .unwrap_or(""),
            sep: self.sep,
            literal: self.literal,
        }
    }

    pub fn reps(&self) -> impl Iterator<Item = Repetition<'a>> {
        let (sep, literal) = (self.sep, self.literal);
        split(self.raw, self.sep.repetition, self.literal).map(move |raw| Repetition {
            raw,
            sep,
            literal,
        })
    }

    #[must_use]
    pub fn rep_count(&self) -> usize {
        split(self.raw, self.sep.repetition, self.literal).count()
    }

    /// First repetition, component `seq`, as text.
    #[must_use]
    pub fn comp(&self, seq: usize) -> &'a str {
        self.rep(1).comp_text(seq)
    }

    /// Whole field as it appeared on the wire (repetitions included).
    #[must_use]
    pub const fn text(&self) -> &'a str {
        self.raw
    }
}

/// Splits on `sep`, or yields the whole text when it must not be split. An
/// empty input still yields one empty piece, matching `str::split`.
fn split(raw: &str, sep: char, literal: bool) -> impl Iterator<Item = &str> {
    let mut whole = literal.then_some(raw);
    let mut parts = (!literal).then(|| raw.split(sep));
    std::iter::from_fn(move || match &mut parts {
        Some(parts) => parts.next(),
        None => whole.take(),
    })
}

/// One segment line.
#[derive(Debug, Clone)]
pub struct Segment<'a> {
    pub name: &'a str,
    /// 1-based line number in the source file, for error reporting.
    pub line: usize,
    /// 1-based occurrence among segments with the same name.
    pub occurrence: usize,
    /// The text of each field, in order. Index 0 holds field 1.
    fields: Vec<&'a str>,
    pub raw: &'a str,
    sep: Separators,
}

impl<'a> Segment<'a> {
    #[must_use]
    pub fn field(&self, seq: usize) -> Option<Field<'a>> {
        let raw = *self.fields.get(seq.wrapping_sub(1))?;
        Some(Field {
            raw,
            sep: self.sep,
            // MSH-1 is the field separator and MSH-2 the encoding characters:
            // both are delimiters rather than values.
            literal: self.name == "MSH" && seq <= 2,
        })
    }

    /// True when field `seq` exists and carries data.
    #[must_use]
    pub fn has(&self, seq: usize) -> bool {
        self.field(seq).is_some_and(|f| !f.is_empty())
    }

    /// Field `seq` as raw text, or `""` when absent.
    #[must_use]
    pub fn text(&self, seq: usize) -> &'a str {
        self.field(seq).map_or("", |f| f.text())
    }

    /// First repetition, component `c`, of field `seq`.
    #[must_use]
    pub fn comp(&self, seq: usize, c: usize) -> &'a str {
        self.field(seq).map_or("", |f| f.comp(c))
    }

    /// Highest field number carrying data.
    #[must_use]
    pub fn last_populated(&self) -> usize {
        (1..=self.fields.len())
            .rfind(|seq| self.has(*seq))
            .unwrap_or(0)
    }

    /// Z-segments are site-defined and exempt from dictionary checks.
    #[must_use]
    pub fn is_custom(&self) -> bool {
        self.name.starts_with('Z')
    }

    fn parse(name: &'a str, raw: &'a str, line: usize, sep: &Separators) -> Self {
        let parts: Vec<&str> = raw.split(sep.field).collect();
        let mut fields: Vec<&'a str> = Vec::new();
        // MSH is positionally special: MSH-1 *is* the field separator, so the
        // first split part after the name is MSH-2, not MSH-1.
        let rest = if name == "MSH" {
            // The separator itself, sliced from the line rather than rebuilt.
            fields.push(&raw[name.len()..name.len() + sep.field.len_utf8()]);
            fields.push(parts.get(1).copied().unwrap_or(""));
            &parts[2.min(parts.len())..]
        } else {
            &parts[1.min(parts.len())..]
        };
        fields.extend_from_slice(rest);
        Self {
            name,
            line,
            occurrence: 1,
            fields,
            raw,
            sep: *sep,
        }
    }
}

/// A fully decomposed HL7 message.
#[derive(Debug, Clone)]
pub struct Message<'a> {
    pub sep: Separators,
    pub segments: Vec<Segment<'a>>,
    /// 1-based line where this message's MSH was found.
    pub start_line: usize,
    /// Non-fatal observations made while tokenising (stray bytes, batch wrappers).
    pub notes: Vec<String>,
}

impl<'a> Message<'a> {
    #[must_use]
    pub fn msh(&self) -> &Segment<'a> {
        &self.segments[0]
    }

    /// MSH-12.1, e.g. `2.5.1`.
    #[must_use]
    pub fn version(&self) -> &'a str {
        self.msh().comp(12, 1)
    }

    /// (message code, trigger event, structure) from MSH-9.
    #[must_use]
    pub fn message_type(&self) -> (&'a str, &'a str, &'a str) {
        let f = self.msh();
        (f.comp(9, 1), f.comp(9, 2), f.comp(9, 3))
    }

    /// `ADT^A01`, or just `ADT` when no trigger event is present.
    #[must_use]
    pub fn type_label(&self) -> String {
        let (code, trigger, _) = self.message_type();
        match (code.is_empty(), trigger.is_empty()) {
            (true, _) => "(no MSH-9)".to_string(),
            (false, true) => code.to_string(),
            (false, false) => format!("{code}^{trigger}"),
        }
    }

    #[must_use]
    pub fn control_id(&self) -> &'a str {
        self.msh().comp(10, 1)
    }

    #[must_use]
    pub fn find(&self, name: &str) -> Vec<&Segment<'a>> {
        self.segments.iter().filter(|s| s.name == name).collect()
    }

    #[must_use]
    pub fn first(&self, name: &str) -> Option<&Segment<'a>> {
        self.segments.iter().find(|s| s.name == name)
    }
}

/// One message's worth of source lines, still unparsed.
/// Where a message sits in the file, rather than a copy of it or an index of
/// its lines. Splitting the lines again when the message is parsed costs the
/// same walk either way, and it keeps a whole batch down to a few bytes per
/// message instead of twenty-four per line.
#[derive(Debug)]
pub struct RawMessage<'a> {
    pub start_line: usize,
    text: &'a str,
    pub notes: Vec<String>,
}

impl<'a> RawMessage<'a> {
    /// The segment lines this message is made of, cleaned of framing bytes and
    /// numbered as they are in the file. Blank lines and batch wrappers are
    /// skipped here exactly as `split_messages` skipped them.
    pub fn lines(&self) -> impl Iterator<Item = (usize, &'a str)> + '_ {
        lines(self.text)
            .enumerate()
            .filter_map(move |(offset, (_, line))| {
                let cleaned = clean(line);
                if cleaned.is_empty() || is_batch_wrapper(head(cleaned)) {
                    return None;
                }
                Some((self.start_line + offset, cleaned))
            })
    }

    /// The MSH line, which every message starts with and which decides on its
    /// own whether the message can be read at all.
    fn first_line(&self) -> (usize, &'a str) {
        self.lines().next().unwrap_or((self.start_line, self.text))
    }
}

/// Splits on CR, LF or CRLF, counting CRLF as one break so line numbers match
/// what an editor shows, and reports where each line starts. Iterating beats
/// normalising the whole file into a new `String` first, which cost two full
/// copies of the input.
fn lines(text: &str) -> impl Iterator<Item = (usize, &str)> {
    let mut offset = 0usize;
    let mut rest = Some(text);
    std::iter::from_fn(move || {
        let current = rest?;
        let start = offset;
        match current.find(['\r', '\n']) {
            None => {
                rest = None;
                Some((start, current))
            }
            Some(at) => {
                let (line, tail) = current.split_at(at);
                let skip = usize::from(tail.starts_with("\r\n")) + 1;
                offset += at + skip;
                rest = Some(&tail[skip..]);
                Some((start, line))
            }
        }
    })
}

/// Strips MLLP framing bytes and surrounding whitespace from a line.
fn clean(line: &str) -> &str {
    line.trim_matches(|c: char| {
        c == '\u{0b}' || c == '\u{1c}' || c == '\u{1d}' || c == '\0' || c.is_whitespace()
    })
}

fn is_batch_wrapper(head: &str) -> bool {
    matches!(head, "FHS" | "BHS" | "BTS" | "FTS")
}

/// The first three characters of a line, which is where a segment name lives.
fn head(text: &str) -> &str {
    let end = text.char_indices().nth(3).map_or(text.len(), |(i, _)| i);
    &text[..end]
}

/// Splits a file into messages, tolerating CR/LF/CRLF endings, MLLP framing
/// bytes and HL7 batch (FHS/BHS/BTS/FTS) wrappers.
#[must_use]
pub fn split_messages(raw: &str) -> (Vec<RawMessage<'_>>, Vec<String>) {
    let mut messages: Vec<RawMessage<'_>> = Vec::new();
    let mut warnings: Vec<String> = Vec::new();
    let mut pending_notes: Vec<String> = Vec::new();
    let mut stray_reported = false;
    // Byte range of the message being accumulated, so it can be sliced out of
    // `raw` once the next MSH (or the end of the file) closes it.
    let mut open: Option<(usize, usize)> = None;

    for (idx, (offset, line)) in lines(raw).enumerate() {
        let lineno = idx + 1;
        let cleaned = clean(line);
        if cleaned.is_empty() {
            continue;
        }
        let head = head(cleaned);
        if is_batch_wrapper(head) {
            pending_notes.push(format!("line {lineno}: batch wrapper {head} skipped"));
            continue;
        }
        let line_end = offset + line.len();
        if head == "MSH" {
            // The open range and the message it belongs to are pushed
            // together, so these are both Some or both None.
            if let (Some((start, end)), Some(previous)) =
                (open.replace((offset, line_end)), messages.last_mut())
            {
                previous.text = &raw[start..end];
            }
            messages.push(RawMessage {
                start_line: lineno,
                text: &raw[offset..line_end],
                notes: std::mem::take(&mut pending_notes),
            });
        } else if let Some((_, end)) = open.as_mut() {
            *end = line_end;
        } else if !stray_reported {
            stray_reported = true;
            warnings.push(format!(
                "line {lineno}: content before the first MSH segment was ignored"
            ));
        }
    }
    if let (Some((start, end)), Some(last)) = (open, messages.last_mut()) {
        last.text = &raw[start..end];
    }
    (messages, warnings)
}

/// The three-character name a line starts with, when it is a usable segment
/// name. Shared so the whole-message check and the segment loop cannot drift.
fn segment_name(text: &str) -> Option<&str> {
    let name = head(text);
    let usable = name.chars().count() == 3
        && name
            .chars()
            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit())
        && name.starts_with(|c: char| c.is_ascii_uppercase());
    usable.then_some(name)
}

impl RawMessage<'_> {
    /// The delimiters this message declares, or the reason it cannot be read.
    /// Both of `parse_message`'s failure modes are settled by the first line,
    /// so a batch can be checked for unreadable messages without building a
    /// single tree.
    /// # Errors
    ///
    /// Returns [`ParseError`] when the MSH line is truncated, declares a
    /// separator that cannot serve as one, or declares more than four
    /// encoding characters.
    pub fn separators(&self) -> Result<Separators, ParseError> {
        let (lineno, text) = self.first_line();
        let sep = Separators::from_msh(text).map_err(|e| ParseError::new(lineno, e.message))?;
        if segment_name(text) != Some("MSH") {
            return Err(ParseError::new(
                lineno,
                "message does not begin with a parsable MSH segment",
            ));
        }
        Ok(sep)
    }
}

/// # Errors
///
/// Returns [`ParseError`] when the message does not begin with a readable MSH
/// segment. Unrecognisable segments *within* a message are recorded as notes
/// rather than failing the parse.
pub fn parse_message<'a>(raw: &RawMessage<'a>) -> Result<Message<'a>, ParseError> {
    let sep = raw.separators()?;

    let mut segments: Vec<Segment<'a>> = Vec::new();
    let mut notes = raw.notes.clone();
    let mut counts: Vec<(&str, usize)> = Vec::new();

    for (lineno, text) in raw.lines() {
        let Some(name) = segment_name(text) else {
            notes.push(format!(
                "line {}: skipped unrecognisable segment starting {:?}",
                lineno,
                text.chars().take(8).collect::<String>()
            ));
            continue;
        };
        if text.chars().nth(3) != Some(sep.field) {
            notes.push(format!(
                "line {lineno}: segment {name} has no field separator after the name"
            ));
        }
        let mut seg = Segment::parse(name, text, lineno, &sep);
        let entry = counts.iter_mut().find(|(n, _)| *n == name);
        seg.occurrence = if let Some((_, c)) = entry {
            *c += 1;
            *c
        } else {
            counts.push((name, 1));
            1
        };
        segments.push(seg);
    }

    Ok(Message {
        sep,
        segments,
        start_line: raw.start_line,
        notes,
    })
}

/// Resolves HL7 escape sequences for human-readable display.
#[must_use]
pub fn unescape(s: &str, sep: &Separators) -> String {
    if !s.contains(sep.escape) {
        return s.to_string();
    }
    let mut out = String::with_capacity(s.len());
    let chars: Vec<char> = s.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        if chars[i] != sep.escape {
            out.push(chars[i]);
            i += 1;
            continue;
        }
        let end = chars[i + 1..]
            .iter()
            .position(|c| *c == sep.escape)
            .map(|p| i + 1 + p);
        let Some(end) = end else {
            out.push(chars[i]);
            i += 1;
            continue;
        };
        let code: String = chars[i + 1..end].iter().collect();
        match code.as_str() {
            "F" => out.push(sep.field),
            "S" => out.push(sep.component),
            "T" => out.push(sep.subcomponent),
            "R" => out.push(sep.repetition),
            ".br" | ".sp" => out.push('\n'),
            // \E\ is the escape character itself; \\ is the same thing written bare.
            "E" | "" => out.push(sep.escape),
            other if other.starts_with('X') => {
                let hex = &other[1..];
                // Collecting into `Option<Vec<_>>` stops at the first bad pair,
                // so a malformed \Xnn\ falls through to the literal branch.
                let decoded = (!hex.is_empty() && hex.len() % 2 == 0)
                    .then(|| {
                        hex.as_bytes()
                            .chunks(2)
                            .map(|pair| {
                                u8::from_str_radix(std::str::from_utf8(pair).ok()?, 16).ok()
                            })
                            .collect::<Option<Vec<u8>>>()
                    })
                    .flatten();
                match decoded {
                    Some(bytes) => out.push_str(&String::from_utf8_lossy(&bytes)),
                    None => {
                        let _ = write!(out, "{}{}{}", sep.escape, other, sep.escape);
                    }
                }
            }
            // Highlighting and site-defined escapes carry no display text.
            other if other.starts_with('H') || other.starts_with('N') || other.starts_with('Z') => {
            }
            other => {
                let _ = write!(out, "{}{}{}", sep.escape, other, sep.escape);
            }
        }
        i = end + 1;
    }
    out
}

#[cfg(test)]
#[must_use]
/// # Panics
///
/// Panics when `text` does not hold a parsable message. Test fixtures are
/// written by hand, so a fixture that does not parse is a broken test.
pub fn parse_str(text: &str) -> Message<'_> {
    let (raws, _) = split_messages(text);
    parse_message(&raws[0]).expect("fixture should parse")
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::unwrap_used,
        reason = "panicking is the failure mode a test wants"
    )]
    use super::*;

    const ADT: &str = "MSH|^~\\&|HIS|MERCY|LIS|LAB|20240115143200||ADT^A01^ADT_A01|MSG1|P|2.5.1\r\
PID|1||123456^^^MERCY^MR~999^^^SSA^SS||Smith^John^A||19850312|M\r\
PV1|1|I|ER^101^A&Bay 2^MERCY\r";

    #[test]
    fn reads_default_delimiters() {
        let m = parse_str(ADT);
        assert_eq!(m.sep, Separators::default());
        assert_eq!(m.segments.len(), 3);
    }

    #[test]
    fn honours_custom_delimiters() {
        let m = parse_str("MSH#@~\\&#A#B#C#D#20240101120000##ADT@A01#1#P#2.5.1\r");
        assert_eq!(m.sep.field, '#');
        assert_eq!(m.sep.component, '@');
        assert_eq!(m.type_label(), "ADT^A01");
    }

    /// A message borrows its text rather than owning a tree of `String`s, and
    /// the interactive viewer holds every message in a batch at once, so these
    /// sizes are a documented cost rather than an incidental one. Turning a
    /// borrowed field back into an owned one would show up here first.
    #[test]
    #[cfg(target_pointer_width = "64")]
    fn the_message_tree_stays_borrowed() {
        use std::mem::size_of;
        assert_eq!(size_of::<Segment<'_>>(), 96, "Segment grew");
        assert_eq!(size_of::<Message<'_>>(), 80, "Message grew");
        assert_eq!(size_of::<RawMessage<'_>>(), 48, "RawMessage grew");
        // Views over the segment text: pointer, delimiters, literal flag.
        assert_eq!(size_of::<Field<'_>>(), 40, "Field grew");
        assert_eq!(size_of::<Repetition<'_>>(), 40, "Repetition grew");
        assert_eq!(size_of::<Component<'_>>(), 40, "Component grew");
    }

    #[test]
    fn msh_field_numbering_is_offset_by_the_separator() {
        let m = parse_str(ADT);
        let msh = m.msh();
        assert_eq!(msh.text(1), "|");
        assert_eq!(msh.text(2), "^~\\&");
        assert_eq!(msh.text(3), "HIS");
        assert_eq!(msh.comp(9, 2), "A01");
        assert_eq!(m.version(), "2.5.1");
        assert_eq!(m.control_id(), "MSG1");
    }

    #[test]
    fn splits_repetitions_components_and_subcomponents() {
        let m = parse_str(ADT);
        let pid = m.first("PID").unwrap();
        let ids = pid.field(3).unwrap();
        assert_eq!(ids.rep_count(), 2);
        assert_eq!(ids.rep(2).comp_text(1), "999");
        assert_eq!(ids.rep(1).comp_text(5), "MR");

        let pv1 = m.first("PV1").unwrap();
        let location = pv1.field(3).unwrap().rep(1);
        assert_eq!(location.comp(3).sub(1), "A");
        assert_eq!(location.comp(3).sub(2), "Bay 2");
    }

    #[test]
    fn tracks_segment_occurrence_and_line() {
        let m = parse_str("MSH|^~\\&|A|B|C|D|20240101120000||ORU^R01|1|P|2.5.1\rOBX|1\rOBX|2\r");
        let obx = m.find("OBX");
        assert_eq!(obx.len(), 2);
        assert_eq!(obx[1].occurrence, 2);
        assert_eq!(obx[1].line, 3);
    }

    #[test]
    fn accepts_lf_crlf_and_mllp_framing() {
        for text in [
            "MSH|^~\\&|A|B|C|D|20240101120000||ACK|1|P|2.5.1\nMSA|AA|1\n",
            "MSH|^~\\&|A|B|C|D|20240101120000||ACK|1|P|2.5.1\r\nMSA|AA|1\r\n",
            "\u{b}MSH|^~\\&|A|B|C|D|20240101120000||ACK|1|P|2.5.1\rMSA|AA|1\r\u{1c}\r",
        ] {
            let m = parse_str(text);
            assert_eq!(m.segments.len(), 2, "{text:?}");
            assert_eq!(m.segments[1].name, "MSA");
        }
    }

    #[test]
    fn skips_batch_wrappers_and_splits_messages() {
        let text = "FHS|^~\\&\rBHS|^~\\&\r\
MSH|^~\\&|A|B|C|D|20240101120000||ADT^A01|1|P|2.5.1\rPID|1\r\
MSH|^~\\&|A|B|C|D|20240101130000||ADT^A03|2|P|2.5.1\rPID|1\rBTS|2\rFTS|1\r";
        let (raws, warnings) = split_messages(text);
        assert_eq!(raws.len(), 2);
        assert!(warnings.is_empty());
        let first = parse_message(&raws[0]).unwrap();
        assert_eq!(first.segments.len(), 2);
        assert_eq!(first.notes.len(), 2, "batch wrappers should be noted");
        assert_eq!(parse_message(&raws[1]).unwrap().control_id(), "2");
    }

    #[test]
    fn rejects_input_without_msh() {
        let (raws, warnings) = split_messages("PID|1||123\r");
        assert!(raws.is_empty());
        assert_eq!(warnings.len(), 1);
    }

    #[test]
    fn rejects_duplicate_delimiters() {
        let (raws, _) = split_messages("MSH|^~\\^|A|B|C|D|20240101120000||ACK|1|P|2.5.1\r");
        assert!(parse_message(&raws[0]).is_err());
    }

    #[test]
    fn detects_explicit_null() {
        let m = parse_str("MSH|^~\\&|A|B|C|D|20240101120000||ADT^A08|1|P|2.5.1\rPID|1||\"\"\r");
        assert!(m.first("PID").unwrap().field(3).unwrap().is_null());
    }

    #[test]
    fn resolves_escape_sequences() {
        let sep = Separators::default();
        assert_eq!(unescape("Smith \\T\\ Sons", &sep), "Smith & Sons");
        assert_eq!(unescape("100\\S\\200", &sep), "100^200");
        assert_eq!(unescape("a\\F\\b", &sep), "a|b");
        assert_eq!(unescape("line1\\.br\\line2", &sep), "line1\nline2");
        assert_eq!(unescape("\\X0A\\", &sep), "\n");
        assert_eq!(unescape("50\\E\\50", &sep), "50\\50");
        // Unknown escapes survive untouched rather than eating the text.
        assert_eq!(unescape("a\\Q9\\b", &sep), "a\\Q9\\b");
    }

    #[test]
    fn last_populated_ignores_trailing_empties() {
        let m = parse_str(
            "MSH|^~\\&|A|B|C|D|20240101120000||ADT^A01|1|P|2.5.1\rEVN|A01|20240101120000||||\r",
        );
        assert_eq!(m.first("EVN").unwrap().last_populated(), 2);
    }

    #[test]
    fn a_truncated_msh_line_cannot_declare_delimiters() {
        let (raws, _) = split_messages("MSH\r");
        let e = parse_message(&raws[0]).expect_err("nothing to read");
        assert!(e.message.contains("truncated"), "{e}");
    }

    #[test]
    fn more_than_four_encoding_characters_is_reported() {
        for (line, count) in [("MSH|^~\\&%|A\r", 5), ("MSH|^~\\&%$|A\r", 6)] {
            let (raws, _) = split_messages(line);
            let e = parse_message(&raws[0]).expect_err("too many");
            assert!(e.message.contains(&count.to_string()), "{e}");
            assert!(e.message.contains("at most 4"), "{e}");
        }
    }

    #[test]
    fn a_message_with_no_message_type_says_so() {
        let m = parse_str("MSH|^~\\&|A|B|C|D|20240115143200|||MSG1|P|2.5.1\r");
        assert_eq!(m.type_label(), "(no MSH-9)");
    }

    #[test]
    fn a_segment_without_a_field_separator_after_its_name_is_noted() {
        let m = parse_str("MSH|^~\\&|A|B|C|D|20240115143200||ADT^A01|1|P|2.5.1\rPID\r");
        assert!(
            m.notes.iter().any(|n| n.contains("no field separator")),
            "{:?}",
            m.notes
        );
    }

    #[test]
    fn an_unreadable_segment_name_is_skipped_with_a_note() {
        let m = parse_str("MSH|^~\\&|A|B|C|D|20240115143200||ADT^A01|1|P|2.5.1\r??|1|x\r");
        assert!(
            m.notes.iter().any(|n| n.contains("unrecognisable segment")),
            "{:?}",
            m.notes
        );
        assert_eq!(m.segments.len(), 1, "only MSH survives");
    }

    #[test]
    fn the_delimiter_fields_are_never_split_apart() {
        let m = parse_str(ADT);
        let msh2 = m.msh().field(2).expect("MSH-2 exists");
        // The encoding characters contain the component and repetition
        // separators; splitting on them would destroy the value.
        assert_eq!(msh2.text(), "^~\\&");
        assert_eq!(msh2.rep_count(), 1);
        assert_eq!(msh2.rep(1).comp(1).sub(1), "^~\\&");
        assert!(!msh2.is_empty());
    }

    #[test]
    fn a_field_beyond_the_end_of_a_segment_is_absent() {
        let m = parse_str(ADT);
        assert!(m.msh().field(999).is_none());
        assert_eq!(m.msh().text(999), "");
        assert_eq!(m.msh().comp(999, 1), "");
        assert!(!m.msh().has(999));
    }
}