hl7v2 1.3.0

HL7 v2 message parser and processor for Rust
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
//! Core data model for HL7 v2 messages.
//!
//! This module provides the foundational data structures for HL7 v2 messages,
//! including:
//! - Message, Segment, Field, Repetition, Component, Atom types
//! - Delimiter configuration
//! - Error types
//! - Presence semantics
//!
//! This module has minimal dependencies and focuses solely on data representation.

#![expect(
    clippy::arithmetic_side_effects,
    clippy::error_impl_error,
    clippy::indexing_slicing,
    clippy::missing_errors_doc,
    reason = "pre-existing model implementation debt moved from staged microcrate into hl7v2; cleanup is split from topology collapse"
)]

use serde::{Deserialize, Serialize};

/// Error type for HL7 v2 operations
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum Error {
    /// Encountered an invalid segment ID during parsing.
    #[error("Invalid segment ID")]
    InvalidSegmentId,

    /// The delimiter sequence had an invalid length.
    #[error("Bad delimiter length")]
    BadDelimLength,

    /// Two or more delimiter characters are the same.
    #[error("Duplicate delimiters")]
    DuplicateDelims,

    /// Escape sequence markers were unbalanced.
    #[error("Unbalanced escape")]
    UnbalancedEscape,

    /// An escape token could not be parsed.
    #[error("Invalid escape token")]
    InvalidEscapeToken,

    /// The MSH segment format does not match the HL7 requirement.
    #[error("MSH field malformed")]
    MshFieldMalformed,

    /// The MSH-10 control ID field is missing.
    #[error("MSH-10 missing")]
    Msh10Missing,

    /// The message processing ID is invalid.
    #[error("Invalid processing ID")]
    InvalidProcessingId,

    /// The message version was not recognized.
    #[error("Unrecognized version")]
    UnrecognizedVersion,

    /// Message charset is unsupported or invalid.
    #[error("Invalid charset")]
    InvalidCharset,

    /// A framing error occurred while reading or writing the message.
    #[error("Framing error: {0}")]
    Framing(String),

    /// The write operation failed for the underlying transport or writer.
    #[error("Write failed")]
    WriteFailed,

    /// Parsing failed for the specified segment and field.
    #[error("Parse error at segment {segment_id} field {field_index}: {source}")]
    ParseError {
        /// Segment where the parse failed.
        segment_id: String,
        /// Index of the field in the segment.
        field_index: usize,
        #[source]
        /// Underlying error that caused the parse failure.
        source: Box<Error>,
    },

    /// Field text does not satisfy the configured field format.
    #[error("Invalid field format: {details}")]
    InvalidFieldFormat {
        /// Human-readable details for the parse error.
        details: String,
    },

    /// Repetition text does not satisfy the configured repetition format.
    #[error("Invalid repetition format: {details}")]
    InvalidRepFormat {
        /// Human-readable details for the parse error.
        details: String,
    },

    /// Component text does not satisfy the configured component format.
    #[error("Invalid component format: {details}")]
    InvalidCompFormat {
        /// Human-readable details for the parse error.
        details: String,
    },

    /// Subcomponent text does not satisfy the configured subcomponent format.
    #[error("Invalid subcomponent format: {details}")]
    InvalidSubcompFormat {
        /// Human-readable details for the parse error.
        details: String,
    },

    /// The batch parsing operation failed.
    #[error("Batch parsing error: {details}")]
    BatchParseError {
        /// Human-readable details for the batch parsing failure.
        details: String,
    },

    /// The batch header could not be read or interpreted.
    #[error("Invalid batch header: {details}")]
    InvalidBatchHeader {
        /// Human-readable details for the batch header failure.
        details: String,
    },

    /// The batch trailer could not be read or interpreted.
    #[error("Invalid batch trailer: {details}")]
    InvalidBatchTrailer {
        /// Human-readable details for the batch trailer failure.
        details: String,
    },
}

/// Delimiters used in HL7 v2 messages
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Delims {
    /// Field separator (`MSH-1` and list separators).
    pub field: char,
    /// Component separator (`MSH-2` first character).
    pub comp: char,
    /// Repetition separator (`MSH-2` second character).
    pub rep: char,
    /// Escape character (`MSH-2` third character).
    pub esc: char,
    /// Subcomponent separator (`MSH-2` fourth character).
    pub sub: char,
}

impl Default for Delims {
    fn default() -> Self {
        Self {
            field: '|',
            comp: '^',
            rep: '~',
            esc: '\\',
            sub: '&',
        }
    }
}

impl Delims {
    /// Create default delimiters (|^~\&)
    pub fn new() -> Self {
        Self::default()
    }

    /// Parse delimiters from an MSH segment
    pub fn parse_from_msh(msh: &str) -> Result<Self, Error> {
        if msh.len() < 8 {
            return Err(Error::BadDelimLength);
        }

        let field_sep = msh.chars().nth(3).ok_or(Error::BadDelimLength)?;
        let comp_char = msh.chars().nth(4).ok_or(Error::BadDelimLength)?;
        let rep_char = msh.chars().nth(5).ok_or(Error::BadDelimLength)?;
        let esc_char = msh.chars().nth(6).ok_or(Error::BadDelimLength)?;
        let sub_char = msh.chars().nth(7).ok_or(Error::BadDelimLength)?;

        // Check that all delimiters are distinct
        let delimiters = [field_sep, comp_char, rep_char, esc_char, sub_char];
        for i in 0..delimiters.len() {
            for j in (i + 1)..delimiters.len() {
                if delimiters[i] == delimiters[j] {
                    return Err(Error::DuplicateDelims);
                }
            }
        }

        Ok(Self {
            field: field_sep,
            comp: comp_char,
            rep: rep_char,
            esc: esc_char,
            sub: sub_char,
        })
    }
}

/// Main message structure
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Message {
    /// Delimiters used for parsing and rendering message fields.
    pub delims: Delims,
    /// Segment list in message order.
    pub segments: Vec<Segment>,
    /// Character sets used in the message (from MSH-18)
    #[serde(default)]
    pub charsets: Vec<String>,
}

impl Message {
    /// Create a new empty message with default delimiters
    pub fn new() -> Self {
        Self {
            delims: Delims::default(),
            segments: Vec::new(),
            charsets: Vec::new(),
        }
    }

    /// Create a message with the given segments
    pub fn with_segments(segments: Vec<Segment>) -> Self {
        Self {
            delims: Delims::default(),
            segments,
            charsets: Vec::new(),
        }
    }
}

impl Default for Message {
    fn default() -> Self {
        Self::new()
    }
}

/// A batch of HL7 messages
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct Batch {
    /// Optional BHS header segment for the batch.
    pub header: Option<Segment>, // BHS segment
    /// HL7 messages contained in this batch.
    pub messages: Vec<Message>,
    /// Optional BTS trailer segment for the batch.
    pub trailer: Option<Segment>, // BTS segment
}

/// A file containing batches of HL7 messages
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct FileBatch {
    /// Optional FHS header segment for the file batch.
    pub header: Option<Segment>, // FHS segment
    /// Batches nested under this file batch.
    pub batches: Vec<Batch>,
    /// Optional FTS trailer segment for the file batch.
    pub trailer: Option<Segment>, // FTS segment
}

/// A segment in an HL7 message
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Segment {
    /// Three-character segment ID (for example `MSH`, `PID`).
    pub id: [u8; 3],
    /// Fields contained in the segment.
    pub fields: Vec<Field>,
}

impl Segment {
    /// Create a new segment with the given ID
    pub fn new(id: &[u8; 3]) -> Self {
        Self {
            id: *id,
            fields: Vec::new(),
        }
    }

    /// Get the segment ID as a string
    pub fn id_str(&self) -> &str {
        std::str::from_utf8(&self.id).unwrap_or("???")
    }

    /// Add a field to the segment
    pub fn add_field(&mut self, field: Field) {
        self.fields.push(field);
    }
}

/// A field in a segment
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Field {
    /// Repetitions contained in this field.
    pub reps: Vec<Rep>,
}

impl Field {
    /// Create a new empty field
    pub fn new() -> Self {
        Self { reps: Vec::new() }
    }

    /// Create a field with a single text value
    pub fn from_text(text: impl Into<String>) -> Self {
        Self {
            reps: vec![Rep::from_text(text)],
        }
    }

    /// Add a repetition to the field
    pub fn add_rep(&mut self, rep: Rep) {
        self.reps.push(rep);
    }

    /// Get the first value as text (convenience method)
    pub fn first_text(&self) -> Option<&str> {
        self.reps
            .first()?
            .comps
            .first()?
            .subs
            .first()
            .and_then(|atom| match atom {
                Atom::Text(t) => Some(t.as_str()),
                Atom::Null => None,
            })
    }
}

impl Default for Field {
    fn default() -> Self {
        Self::new()
    }
}

/// A repetition of a field
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Rep {
    /// Components contained in this repetition.
    pub comps: Vec<Comp>,
}

impl Rep {
    /// Create a new empty repetition
    pub fn new() -> Self {
        Self { comps: Vec::new() }
    }

    /// Create a repetition with a single text value
    pub fn from_text(text: impl Into<String>) -> Self {
        Self {
            comps: vec![Comp::from_text(text)],
        }
    }

    /// Add a component to the repetition
    pub fn add_comp(&mut self, comp: Comp) {
        self.comps.push(comp);
    }

    /// Get the first text value in this repetition
    pub fn first_text(&self) -> Option<&str> {
        self.comps.first()?.first_text()
    }
}

impl Default for Rep {
    fn default() -> Self {
        Self::new()
    }
}

/// A component of a field
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Comp {
    /// Subcomponents that make up this component.
    pub subs: Vec<Atom>,
}

impl Comp {
    /// Create a new empty component
    pub fn new() -> Self {
        Self { subs: Vec::new() }
    }

    /// Create a component with a single text value
    pub fn from_text(text: impl Into<String>) -> Self {
        Self {
            subs: vec![Atom::Text(text.into())],
        }
    }

    /// Add a subcomponent to the component
    pub fn add_sub(&mut self, atom: Atom) {
        self.subs.push(atom);
    }

    /// Get the first text value in this component
    pub fn first_text(&self) -> Option<&str> {
        self.subs.first()?.as_text()
    }
}

impl Default for Comp {
    fn default() -> Self {
        Self::new()
    }
}

/// An atomic value in the message
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Atom {
    /// Plain text value.
    Text(String),
    /// Explicit NULL marker.
    Null,
}

impl Atom {
    /// Create a text atom
    pub fn text(s: impl Into<String>) -> Self {
        Atom::Text(s.into())
    }

    /// Create a null atom
    pub fn null() -> Self {
        Atom::Null
    }

    /// Check if this is a null atom
    pub fn is_null(&self) -> bool {
        matches!(self, Atom::Null)
    }

    /// Get the text value if this is a text atom
    pub fn as_text(&self) -> Option<&str> {
        match self {
            Atom::Text(s) => Some(s.as_str()),
            Atom::Null => None,
        }
    }
}

/// Presence semantics for HL7 v2 fields
#[derive(Debug, Clone, PartialEq)]
pub enum Presence {
    /// Field is not present in the message (index out of range)
    Missing,
    /// Field is present but empty (zero-length)
    Empty,
    /// Field contains a literal NULL value ("")
    Null,
    /// Field contains a value
    Value(String),
}

impl Presence {
    /// Check if the field is missing
    pub fn is_missing(&self) -> bool {
        matches!(self, Presence::Missing)
    }

    /// Check if the field is present (may be empty or have a value)
    pub fn is_present(&self) -> bool {
        !self.is_missing()
    }

    /// Check if the field has an actual value
    pub fn has_value(&self) -> bool {
        matches!(self, Presence::Value(_))
    }

    /// Get the value if present
    pub fn value(&self) -> Option<&str> {
        match self {
            Presence::Value(v) => Some(v.as_str()),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests;