hl7-net 0.1.0

Lightweight HL7 V2 parser/writer, ported from the Efferent HL7-V2 .NET library
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
use std::collections::HashMap;
use std::sync::LazyLock;

use regex::Regex;

use crate::encoding::HL7Encoding;
use crate::error::Hl7Error;
use crate::field::Field;
use crate::helper;
use crate::segment::Segment;

static SEGMENT_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^([A-Z][A-Z][A-Z1-9])([\(\[]([0-9]+)[\)\]]){0,1}$").unwrap());
static FIELD_REGEX: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^([0-9]+)([\(\[]([0-9]+)[\)\]]){0,1}$").unwrap());
static OTHER_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[1-9]([0-9]{1,2})?$").unwrap());

/// A parsed HL7 v2 message: a collection of [`Segment`]s keyed by name, plus the
/// message-level metadata extracted from the MSH segment.
#[derive(Debug, Clone, Default)]
pub struct Message {
    /// The raw message text (normalized after parsing).
    pub hl7_message: String,
    /// HL7 version from MSH-12.
    pub version: String,
    /// Message structure from MSH-9.3 (or a derived value).
    pub message_structure: String,
    /// Message control ID from MSH-10.
    pub message_control_id: String,
    /// Processing ID from MSH-11.
    pub processing_id: String,
    /// Number of segments in the message.
    pub segment_count: usize,
    /// The encoding (delimiters) used by the message.
    pub encoding: HL7Encoding,

    segments: HashMap<String, Vec<Segment>>,
    all_segments: Vec<String>,
}

impl Message {
    /// Creates an empty message with default encoding.
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a message wrapping the given raw HL7 text (not yet parsed).
    pub fn with_message(text: impl Into<String>) -> Self {
        Self { hl7_message: text.into(), ..Self::default() }
    }

    /// Convenience: wraps and parses `text` in one step.
    pub fn parse_str(text: impl Into<String>, bypass_validation: bool) -> Result<Self, Hl7Error> {
        let mut msg = Self::with_message(text);
        msg.parse(bypass_validation)?;
        Ok(msg)
    }

    // ----- Parsing & serialization ---------------------------------------

    /// Parses [`Self::hl7_message`] into segments/fields/components.
    ///
    /// Returns `true` when the message round-trips (re-serializing yields the same
    /// text). Pass `bypass_validation = true` to skip structural validation (do not
    /// use for newly constructed messages).
    pub fn parse(&mut self, bypass_validation: bool) -> Result<bool, Hl7Error> {
        let is_valid = if bypass_validation { true } else { self.validate_message()? };

        if !is_valid {
            return Ok(false);
        }

        if self.all_segments.is_empty() {
            self.all_segments = helper::split_message(&self.hl7_message);
        }

        let enc = self.encoding.clone();
        self.segments.clear();
        self.segment_count = 0;

        let lines = self.all_segments.clone();
        for line in lines {
            if line.trim().is_empty() {
                continue;
            }

            let segment = Segment::parse(&line, &enc).map_err(|e| {
                Hl7Error::with_code(
                    format!("Failed to parse the message with error - {}", e.message),
                    Hl7Error::PARSING_ERROR,
                )
            })?;
            self.add_new_segment(segment);
        }

        let serialized = self.serialize().map_err(|e| {
            Hl7Error::with_code(
                format!("Failed to serialize parsed message with error - {}", e.message),
                Hl7Error::PARSING_ERROR,
            )
        })?;

        if serialized.is_empty() {
            return Err(Hl7Error::with_code(
                "Unable to serialize to original message - ",
                Hl7Error::PARSING_ERROR,
            ));
        }

        self.encoding.evaluate_segment_delimiter(&self.hl7_message)?;

        Ok(self.equals(&serialized))
    }

    /// Serializes the message back to HL7 text.
    pub fn serialize(&self) -> Result<String, Hl7Error> {
        let mut out = String::new();
        for seg in self.segments_in_order() {
            seg.serialize(&mut out, &self.encoding);
        }
        Ok(out)
    }

    // ----- Value access --------------------------------------------------

    /// Gets the value at a path such as `PID.5.2` (segment.field.component.subcomponent).
    ///
    /// A segment occurrence may be supplied as `PID(2).5`. Returns the decoded value;
    /// a "present but null" value is returned as an empty string.
    pub fn get_value(&self, path: &str) -> Result<String, Hl7Error> {
        let parts: Vec<&str> = path.split('.').collect();
        let com_count = parts.len();

        if !validate_value_format(&parts) {
            return Err(Hl7Error::new(format!("Request format is not valid: {path}")));
        }

        let caps = SEGMENT_REGEX
            .captures(parts[0])
            .ok_or_else(|| Hl7Error::new(format!("Request format is not valid: {path}")))?;
        let seg_name = caps.get(1).map(|m| m.as_str()).unwrap_or("");
        let mut occurrence = 0usize;
        if let Some(m) = caps.get(3)
            && let Ok(v) = m.as_str().parse::<usize>()
        {
            occurrence = v.saturating_sub(1);
        }

        let segment = self
            .segments
            .get(seg_name)
            .and_then(|list| list.get(occurrence))
            .ok_or_else(|| Hl7Error::new(format!("Segment name not available: {path}")))?;

        let enc = &self.encoding;
        let str_value: Option<String> = match com_count {
            4 => {
                let field = get_field(segment, parts[1]).map_err(|e| {
                    Hl7Error::new(format!("SubComponent not available - {path} Error: {}", e.message))
                })?;
                let ci = parse_index(parts[2])?;
                let sci = parse_index(parts[3])?;
                let comp = field.components.get(ci).ok_or_else(|| {
                    Hl7Error::new(format!("SubComponent not available - {path}"))
                })?;
                let sub = comp.sub_components.get(sci).ok_or_else(|| {
                    Hl7Error::new(format!("SubComponent not available - {path}"))
                })?;
                sub.value(enc)
            }
            3 => {
                let field = get_field(segment, parts[1]).map_err(|e| {
                    Hl7Error::new(format!("Component not available - {path} Error: {}", e.message))
                })?;
                let ci = parse_index(parts[2])?;
                let comp = field
                    .components
                    .get(ci)
                    .ok_or_else(|| Hl7Error::new(format!("Component not available - {path}")))?;
                comp.value(enc)
            }
            2 => {
                let field = get_field(segment, parts[1]).map_err(|e| {
                    Hl7Error::new(format!("Field not available - {path} Error: {}", e.message))
                })?;
                field.value(enc)
            }
            _ => segment.value(enc),
        };

        Ok(enc.decode(str_value.as_deref().unwrap_or("")))
    }

    /// Sets the value at a path such as `PID.5.2` in every matching segment.
    pub fn set_value(&mut self, path: &str, value: &str) -> Result<bool, Hl7Error> {
        let parts: Vec<&str> = path.split('.').collect();
        let com_count = parts.len();

        if !validate_value_format(&parts) {
            return Err(Hl7Error::new("Request format is not valid"));
        }

        let seg_name = parts[0];
        let enc = self.encoding.clone();

        let list = self
            .segments
            .get_mut(seg_name)
            .ok_or_else(|| Hl7Error::new("Segment name not available"))?;

        let mut is_set = false;

        for segment in list.iter_mut() {
            match com_count {
                4 => {
                    let ci = parse_index(parts[2])?;
                    let sci = parse_index(parts[3])?;
                    let field = get_field_mut(segment, parts[1]).map_err(|e| {
                        Hl7Error::new(format!(
                            "SubComponent not available - {path} Error: {}",
                            e.message
                        ))
                    })?;
                    let comp = field.components.get_mut(ci).ok_or_else(|| {
                        Hl7Error::new(format!("SubComponent not available - {path}"))
                    })?;
                    let sub = comp.sub_components.get_mut(sci).ok_or_else(|| {
                        Hl7Error::new(format!("SubComponent not available - {path}"))
                    })?;
                    sub.set_value(value);
                    is_set = true;
                }
                3 => {
                    let ci = parse_index(parts[2])?;
                    let field = get_field_mut(segment, parts[1]).map_err(|e| {
                        Hl7Error::new(format!("Component not available - {path} Error: {}", e.message))
                    })?;
                    let comp = field
                        .components
                        .get_mut(ci)
                        .ok_or_else(|| Hl7Error::new(format!("Component not available - {path}")))?;
                    comp.set_value(value, &enc);
                    is_set = true;
                }
                2 => {
                    let field = get_field_mut(segment, parts[1]).map_err(|e| {
                        Hl7Error::new(format!("Field not available - {path} Error: {}", e.message))
                    })?;
                    field.set_value(value, &enc);
                    is_set = true;
                }
                _ => return Err(Hl7Error::new("Cannot overwrite a segment value")),
            }
        }

        Ok(is_set)
    }

    /// Whether the field at `path` is componentized.
    pub fn is_componentized(&self, path: &str) -> Result<bool, Hl7Error> {
        let parts: Vec<&str> = path.split('.').collect();

        if !validate_value_format(&parts) {
            return Err(Hl7Error::new("Request format is not valid"));
        }
        if parts.len() < 2 {
            return Err(Hl7Error::new("Field not identified in request"));
        }

        let segment = self
            .segments
            .get(parts[0])
            .and_then(|list| list.first())
            .ok_or_else(|| Hl7Error::new(format!("Field not available - {path}")))?;
        let field = get_field(segment, parts[1])
            .map_err(|e| Hl7Error::new(format!("Field not available - {path} Error: {}", e.message)))?;

        Ok(field.is_componentized)
    }

    /// Whether the field at `path` has repetitions.
    pub fn has_repetitions(&self, path: &str) -> Result<bool, Hl7Error> {
        let parts: Vec<&str> = path.split('.').collect();

        if !validate_value_format(&parts) {
            return Err(Hl7Error::new("Request format is not valid"));
        }
        if parts.len() < 2 {
            return Err(Hl7Error::new("Field not identified in request"));
        }

        let segment = self
            .segments
            .get(parts[0])
            .and_then(|list| list.first())
            .ok_or_else(|| Hl7Error::new(format!("Field not available - {path}")))?;
        let count = get_field_repetitions(segment, parts[1])
            .map_err(|e| Hl7Error::new(format!("Field not available - {path} Error: {}", e.message)))?;

        Ok(count > 1)
    }

    /// Whether the component at `path` is subcomponentized.
    pub fn is_subcomponentized(&self, path: &str) -> Result<bool, Hl7Error> {
        let parts: Vec<&str> = path.split('.').collect();

        if !validate_value_format(&parts) {
            return Err(Hl7Error::new("Request format is not valid"));
        }
        if parts.len() < 3 {
            return Err(Hl7Error::new("Component not identified in request"));
        }

        let segment = self
            .segments
            .get(parts[0])
            .and_then(|list| list.first())
            .ok_or_else(|| Hl7Error::new(format!("Component not available - {path}")))?;
        let field = get_field(segment, parts[1]).map_err(|e| {
            Hl7Error::new(format!("Component not available - {path} Error: {}", e.message))
        })?;
        let ci = parse_index(parts[2])?;
        let comp = field
            .components
            .get(ci)
            .ok_or_else(|| Hl7Error::new(format!("Component not available - {path}")))?;

        Ok(comp.is_subcomponentized)
    }

    // ----- Segment management --------------------------------------------

    /// Appends a segment, assigning it the next sequence number.
    pub fn add_new_segment(&mut self, mut segment: Segment) -> bool {
        segment.sequence_no = self.segment_count;
        self.segment_count += 1;
        self.segments.entry(segment.name.clone()).or_default().push(segment);
        true
    }

    /// Removes the `index`-th segment with the given name.
    pub fn remove_segment(&mut self, segment_name: &str, index: usize) -> bool {
        if let Some(list) = self.segments.get_mut(segment_name)
            && index < list.len()
        {
            list.remove(index);
            self.segment_count = self.segment_count.saturating_sub(1);
            return true;
        }
        false
    }

    /// All segments in original order.
    pub fn segments(&self) -> Vec<&Segment> {
        self.segments_in_order()
    }

    /// All segments with the given name, in original order.
    pub fn segments_named(&self, segment_name: &str) -> Vec<&Segment> {
        self.segments_in_order()
            .into_iter()
            .filter(|s| s.name == segment_name)
            .collect()
    }

    /// The first segment with the given name.
    pub fn default_segment(&self, segment_name: &str) -> Option<&Segment> {
        self.segments_in_order().into_iter().find(|s| s.name == segment_name)
    }

    /// Mutable access to all segments with the given name, in original order.
    pub fn segments_named_mut(&mut self, segment_name: &str) -> Option<&mut Vec<Segment>> {
        self.segments.get_mut(segment_name)
    }

    /// Builds and appends an MSH header segment.
    #[allow(clippy::too_many_arguments)]
    pub fn add_segment_msh(
        &mut self,
        sending_application: &str,
        sending_facility: &str,
        receiving_application: &str,
        receiving_facility: &str,
        security: Option<&str>,
        message_type: &str,
        message_control_id: &str,
        processing_id: &str,
        version: &str,
    ) -> Result<(), Hl7Error> {
        let date_string = helper::now_long_date();
        let delim = self.encoding.field_delimiter;
        let all = self.encoding.all_delimiters();
        let seg_delim = self.encoding.segment_delimiter.clone();

        let mut response = String::new();
        response.push_str("MSH");
        response.push_str(&all);
        response.push(delim);
        response.push_str(sending_application);
        response.push(delim);
        response.push_str(sending_facility);
        response.push(delim);
        response.push_str(receiving_application);
        response.push(delim);
        response.push_str(receiving_facility);
        response.push(delim);
        response.push_str(&self.encoding.encode(&date_string));
        response.push(delim);
        response.push_str(security.unwrap_or(""));
        response.push(delim);
        response.push_str(message_type);
        response.push(delim);
        response.push_str(message_control_id);
        response.push(delim);
        response.push_str(processing_id);
        response.push(delim);
        response.push_str(version);
        response.push_str(&seg_delim);

        let message = Message::parse_str(response, false)?;
        let msh = message
            .default_segment("MSH")
            .ok_or_else(|| Hl7Error::new("MSH segment not found"))?
            .clone();
        self.add_new_segment(msh);

        Ok(())
    }

    // ----- Acknowledgements & framing ------------------------------------

    /// Builds the positive acknowledgement (ACK, code `AA`) for this message.
    pub fn get_ack(&self, bypass_validation: bool) -> Option<Message> {
        self.create_ack_message("AA", false, None, bypass_validation)
    }

    /// Builds a negative acknowledgement (NACK) with the given code and message.
    pub fn get_nack(&self, code: &str, err_msg: &str, bypass_validation: bool) -> Option<Message> {
        self.create_ack_message(code, true, Some(err_msg), bypass_validation)
    }

    /// Serializes the message into an MLLP-framed byte buffer.
    pub fn get_mllp(&self) -> Result<Vec<u8>, Hl7Error> {
        Ok(helper::get_mllp(&self.serialize()?))
    }

    fn create_ack_message(
        &self,
        code: &str,
        is_nack: bool,
        err_msg: Option<&str>,
        bypass_validation: bool,
    ) -> Option<Message> {
        if self.message_structure == "ACK" {
            return None;
        }

        let date_string = helper::now_long_date();
        let msh = self.segments.get("MSH")?.first()?;
        let delim = self.encoding.field_delimiter;
        let all = self.encoding.all_delimiters();
        let seg_delim = &self.encoding.segment_delimiter;

        let field = |i: usize| -> String {
            msh.fields.get(i).and_then(|f| f.value(&self.encoding)).unwrap_or_default()
        };

        let mut response = String::new();
        response.push_str("MSH");
        response.push_str(&all);
        response.push(delim);
        response.push_str(&field(4)); // receiving application -> sending
        response.push(delim);
        response.push_str(&field(5)); // receiving facility -> sending
        response.push(delim);
        response.push_str(&field(2)); // sending application -> receiving
        response.push(delim);
        response.push_str(&field(3)); // sending facility -> receiving
        response.push(delim);
        response.push_str(&date_string);
        response.push(delim);
        response.push(delim); // empty security
        response.push_str("ACK");
        response.push(delim);
        response.push_str(&self.message_control_id);
        response.push(delim);
        response.push_str(&self.processing_id);
        response.push(delim);
        response.push_str(&self.version);
        response.push_str(seg_delim);

        response.push_str("MSA");
        response.push(delim);
        response.push_str(code);
        response.push(delim);
        response.push_str(&self.message_control_id);
        if is_nack {
            response.push(delim);
            response.push_str(err_msg.unwrap_or(""));
        }
        response.push_str(seg_delim);

        Message::parse_str(response, bypass_validation).ok()
    }

    // ----- Internals -----------------------------------------------------

    fn segments_in_order(&self) -> Vec<&Segment> {
        let mut all: Vec<&Segment> = self.segments.values().flatten().collect();
        all.sort_by_key(|s| s.sequence_no);
        all
    }

    /// Structural validation of the message; also extracts MSH metadata and
    /// normalizes [`Self::hl7_message`]. Mirrors the .NET `validateMessage`,
    /// wrapping every failure as a `BAD_MESSAGE`.
    fn validate_message(&mut self) -> Result<bool, Hl7Error> {
        self.validate_message_inner().map_err(|e| {
            Hl7Error::with_code(
                format!("Failed to validate the message with error - {}", e.message),
                Hl7Error::BAD_MESSAGE,
            )
        })?;
        Ok(true)
    }

    fn validate_message_inner(&mut self) -> Result<(), Hl7Error> {
        if self.hl7_message.is_empty() {
            return Err(Hl7Error::with_code("No Message Found", Hl7Error::BAD_MESSAGE));
        }

        // MSH + delimiters + 12 fields in MSH.
        if self.hl7_message.len() < 20 {
            return Err(Hl7Error::with_code(
                format!("Message Length too short: {} chars.", self.hl7_message.len()),
                Hl7Error::BAD_MESSAGE,
            ));
        }

        if !self.hl7_message.starts_with("MSH") {
            return Err(Hl7Error::with_code(
                "MSH segment not found at the beginning of the message",
                Hl7Error::BAD_MESSAGE,
            ));
        }

        self.encoding.evaluate_segment_delimiter(&self.hl7_message)?;
        self.all_segments = helper::split_message(&self.hl7_message);
        self.hl7_message =
            self.all_segments.join(&self.encoding.segment_delimiter) + &self.encoding.segment_delimiter;

        let first = &self.all_segments[0];
        let field_delimiters: String = first.chars().skip(3).take(5).collect();
        self.encoding.evaluate_delimiters(&field_delimiters)?;
        self.decompose_multibyte_hex_sequences();

        let fourth_char = self.hl7_message.chars().nth(3);

        for segment in &self.all_segments {
            if segment.trim().is_empty() {
                continue;
            }

            let name: String = segment.chars().take(3).collect();
            if !SEGMENT_REGEX.is_match(&name) {
                return Err(Hl7Error::with_code(
                    format!("Invalid segment name found: {segment}"),
                    Hl7Error::BAD_MESSAGE,
                ));
            }

            if segment.chars().count() > 3 && segment.chars().nth(3) != fourth_char {
                return Err(Hl7Error::with_code(
                    format!("Invalid segment found: {segment}"),
                    Hl7Error::BAD_MESSAGE,
                ));
            }
        }

        let msh_line = &self.all_segments[0];
        let field_sep_count = msh_line.chars().filter(|c| *c == self.encoding.field_delimiter).count();
        if field_sep_count < 11 {
            return Err(Hl7Error::with_code(
                "MSH segment doesn't contain all the required fields",
                Hl7Error::BAD_MESSAGE,
            ));
        }

        let msh_fields: Vec<&str> = msh_line.split(self.encoding.field_delimiter).collect();

        // MSH-12: version
        if msh_fields.len() >= 12 {
            let decoded = self.encoding.decode(msh_fields[11]);
            self.version =
                decoded.split(self.encoding.component_delimiter).next().unwrap_or("").to_string();
        } else {
            return Err(Hl7Error::with_code(
                "HL7 version not found in the MSH segment",
                Hl7Error::REQUIRED_FIELD_MISSING,
            ));
        }

        // MSH-9: message type & trigger event
        let msh_9 = self.encoding.decode(msh_fields[8]);
        if msh_9.is_empty() {
            return Err(Hl7Error::with_code(
                "MSH.9 not available",
                Hl7Error::UNSUPPORTED_MESSAGE_TYPE,
            ));
        }

        let comps: Vec<&str> = msh_9.split(self.encoding.component_delimiter).collect();
        if comps.len() >= 3 {
            self.message_structure = comps[2].to_string();
        } else if !comps.is_empty() && comps[0] == "ACK" {
            self.message_structure = "ACK".to_string();
        } else if comps.len() == 2 {
            self.message_structure = format!("{}_{}", comps[0], comps[1]);
        } else {
            return Err(Hl7Error::with_code(
                "Message Type & Trigger Event value not found in message",
                Hl7Error::UNSUPPORTED_MESSAGE_TYPE,
            ));
        }

        // MSH-10: message control ID
        self.message_control_id = self.encoding.decode(msh_fields[9]);
        if self.message_control_id.is_empty() {
            return Err(Hl7Error::with_code(
                "MSH.10 - Message Control ID not found",
                Hl7Error::REQUIRED_FIELD_MISSING,
            ));
        }

        // MSH-11: processing ID
        self.processing_id = self.encoding.decode(msh_fields[10]);
        if self.processing_id.is_empty() {
            return Err(Hl7Error::with_code(
                "MSH.11 - Processing ID not found",
                Hl7Error::REQUIRED_FIELD_MISSING,
            ));
        }

        Ok(())
    }

    /// Round-trip self-check: compares the (hex-normalized) original message with
    /// the freshly serialized text, segment by segment.
    fn equals(&self, other: &str) -> bool {
        let seg_chars: Vec<char> = self.encoding.segment_delimiter.chars().collect();
        let split = |s: &str| -> Vec<String> {
            s.split(|c| seg_chars.contains(&c))
                .filter(|p| !p.is_empty())
                .map(str::to_string)
                .collect()
        };

        let mut arr1 = split(&self.hl7_message);
        let arr2 = split(other);

        self.decode_hexa_sequences(&mut arr1, false);

        arr1 == arr2
    }

    fn decompose_multibyte_hex_sequences(&mut self) {
        if self.encoding.escape_character == '\0' || self.all_segments.is_empty() {
            return;
        }

        let mut lines = std::mem::take(&mut self.all_segments);
        let changed = self.decode_hexa_sequences(&mut lines, true);
        self.all_segments = lines;

        if changed {
            self.hl7_message = self.all_segments.join(&self.encoding.segment_delimiter)
                + &self.encoding.segment_delimiter;
        }
    }

    /// Decodes (or decomposes) `\X..\` hex escapes across message lines. Returns
    /// whether anything changed. CR/LF bytes are preserved so they survive the
    /// serialization round-trip.
    fn decode_hexa_sequences(&self, lines: &mut [String], decompose: bool) -> bool {
        let esc = self.encoding.escape_character;
        let pattern = format!(r"\x{{{0:X}}}X([0-9A-Fa-f]*)\x{{{0:X}}}", esc as u32);
        let re = match Regex::new(&pattern) {
            Ok(r) => r,
            Err(_) => return false,
        };

        let mut changed = false;

        for line in lines.iter_mut() {
            if !line.contains(esc) {
                continue;
            }

            let replaced = re
                .replace_all(line, |caps: &regex::Captures| {
                    let whole = &caps[0];
                    let hex = caps.get(1).map(|m| m.as_str()).unwrap_or("");

                    if decompose {
                        decompose_multibyte_hex(whole, hex, esc)
                    } else if !is_encoded_linebreak_byte(hex) {
                        HL7Encoding::decode_hex_string(hex)
                    } else {
                        whole.to_string()
                    }
                })
                .into_owned();

            if &replaced != line {
                *line = replaced;
                changed = true;
            }
        }

        changed
    }
}

// ----- Free helpers ------------------------------------------------------

/// Parses a 1-based numeric index into a 0-based one.
fn parse_index(s: &str) -> Result<usize, Hl7Error> {
    s.parse::<usize>()
        .ok()
        .and_then(|n| n.checked_sub(1))
        .ok_or_else(|| Hl7Error::new(format!("Invalid index: {s}")))
}

/// Parses a field index (with optional repetition), returning 0-based values.
fn parse_field_index(index: &str) -> Result<(usize, usize), Hl7Error> {
    let caps = FIELD_REGEX
        .captures(index)
        .ok_or_else(|| Hl7Error::new("Invalid field index"))?;

    let field_index = caps[1]
        .parse::<usize>()
        .ok()
        .and_then(|n| n.checked_sub(1))
        .ok_or_else(|| Hl7Error::new("Invalid field index"))?;

    let repetition = match caps.get(3) {
        Some(m) => m
            .as_str()
            .parse::<usize>()
            .ok()
            .and_then(|n| n.checked_sub(1))
            .ok_or_else(|| Hl7Error::new("Invalid field index"))?,
        None => 0,
    };

    Ok((field_index, repetition))
}

/// Resolves a field for read access, honoring an optional repetition suffix
/// (e.g. `3(2)` selects the second repetition of field 3).
fn get_field<'a>(segment: &'a Segment, index: &str) -> Result<&'a Field, Hl7Error> {
    let (field_index, repetition) = parse_field_index(index)?;
    let field = segment
        .fields
        .get(field_index)
        .ok_or_else(|| Hl7Error::new("Field not available"))?;

    if field.has_repetitions {
        field
            .repetitions
            .get(repetition)
            .ok_or_else(|| Hl7Error::new("Field repetition not available"))
    } else if repetition == 0 {
        Ok(field)
    } else {
        Err(Hl7Error::new("Field repetition not available"))
    }
}

/// Mutable counterpart of [`get_field`].
fn get_field_mut<'a>(segment: &'a mut Segment, index: &str) -> Result<&'a mut Field, Hl7Error> {
    let (field_index, repetition) = parse_field_index(index)?;
    let field = segment
        .fields
        .get_mut(field_index)
        .ok_or_else(|| Hl7Error::new("Field not available"))?;

    if field.has_repetitions {
        field
            .repetitions
            .get_mut(repetition)
            .ok_or_else(|| Hl7Error::new("Field repetition not available"))
    } else if repetition == 0 {
        Ok(field)
    } else {
        Err(Hl7Error::new("Field repetition not available"))
    }
}

/// Returns the number of repetitions for the field at `index` (`1` when the
/// field does not repeat, `0` when the index is not a valid field reference).
fn get_field_repetitions(segment: &Segment, index: &str) -> Result<usize, Hl7Error> {
    let caps = match FIELD_REGEX.captures(index) {
        Some(c) => c,
        None => return Ok(0),
    };

    let field_index = caps[1]
        .parse::<usize>()
        .ok()
        .and_then(|n| n.checked_sub(1))
        .ok_or_else(|| Hl7Error::new("Invalid field index"))?;

    let field = segment
        .fields
        .get(field_index)
        .ok_or_else(|| Hl7Error::new("Field not available"))?;

    if field.has_repetitions {
        Ok(field.repetitions.len())
    } else {
        Ok(1)
    }
}

/// Validates that a path split into `parts` is well-formed: a valid segment
/// name, then a field index, then numeric component/subcomponent indices.
fn validate_value_format(parts: &[&str]) -> bool {
    if parts.is_empty() || !SEGMENT_REGEX.is_match(parts[0]) {
        return false;
    }

    let mut is_valid = false;
    for (i, part) in parts.iter().enumerate().skip(1) {
        let matches = (i == 1 && FIELD_REGEX.is_match(part))
            || (i > 1 && OTHER_REGEX.is_match(part));

        if matches {
            is_valid = true;
        } else {
            return false;
        }
    }

    is_valid
}

/// Splits a multibyte `\X..\` hex escape that encodes a line break into one
/// single-byte escape per pair, so the CR/LF bytes survive the round-trip.
/// Sequences that don't encode a line break are returned unchanged.
fn decompose_multibyte_hex(match_value: &str, hex: &str, esc: char) -> String {
    if hex.len() <= 2 || !hex.len().is_multiple_of(2) || !contains_encoded_linebreak(hex) {
        return match_value.to_string();
    }

    let mut result = String::with_capacity(match_value.len());
    let mut i = 0;
    while i + 2 <= hex.len() {
        result.push(esc);
        result.push('X');
        result.push_str(&hex[i..i + 2]);
        result.push(esc);
        i += 2;
    }

    result
}

/// Whether any byte in the hex payload is an encoded CR or LF.
fn contains_encoded_linebreak(hex: &str) -> bool {
    (0..hex.len() / 2).any(|i| is_encoded_linebreak_byte(&hex[i * 2..i * 2 + 2]))
}

/// Whether a two-character hex byte is an encoded CR (`0D`) or LF (`0A`).
fn is_encoded_linebreak_byte(hex: &str) -> bool {
    matches!(hex, "0D" | "0A" | "0d" | "0a")
}