-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessage.go
More file actions
240 lines (220 loc) · 8.07 KB
/
message.go
File metadata and controls
240 lines (220 loc) · 8.07 KB
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
// Copyright 2026 Joshua Jones <joshua.jones.software@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package hl7
import "bytes"
// Message represents a parsed HL7 v2 message.
// It owns the underlying byte buffer and provides access to segments.
//
// ParseMessage performs only Phase 1 parsing: delimiter extraction and
// segment boundary identification. Field, component, and subcomponent
// parsing is deferred until accessed.
type Message struct {
raw []byte
delims Delimiters
segments []Segment
}
// ParseMessage parses raw HL7 bytes into a Message.
//
// The input is copied so the caller may reuse the buffer. The parser extracts
// delimiters from the MSH segment header and splits the message into segments
// by scanning for carriage return (0x0D) terminators. Both \r and \r\n line
// endings are accepted.
//
// Returns an error if the message is too short, does not begin with an MSH
// segment, or has invalid delimiters.
func ParseMessage(data []byte) (*Message, error) {
if len(data) < minMSHLength {
return nil, ErrMessageTooShort
}
delims, err := extractDelimiters(data)
if err != nil {
return nil, err
}
// Make an owned copy, merging any ADD continuation segments into their
// preceding segment per HL7v2.5.1 Section 2.5.2.
owned, err := mergeADD(data, delims.Field)
if err != nil {
return nil, err
}
segments := splitSegments(owned, delims)
if len(segments) == 0 {
return nil, ErrNoMSHSegment
}
return &Message{
raw: owned,
delims: delims,
segments: segments,
}, nil
}
// splitSegments splits the message data into Segment values by scanning for
// the segment terminator (\r). Accepts \r, \n, and \r\n for real-world
// compatibility. Empty lines are skipped.
func splitSegments(data []byte, delims Delimiters) []Segment {
// Heuristic capacity: typical HL7 segments are 40-120 bytes; dividing by
// 80 with a +4 floor gives a good estimate in one pass, avoiding a separate
// pre-counting scan. The +4 floor ensures ADD-merged messages with fewer
// bytes-per-segment are still pre-sized adequately. Slight over-allocation
// is an acceptable tradeoff for eliminating the extra buffer scan.
segments := make([]Segment, 0, len(data)/80+4)
start := 0
for i := 0; i < len(data); i++ {
if data[i] == '\r' || data[i] == '\n' {
if i > start {
segments = append(segments, Segment{
raw: data[start:i],
delims: delims,
})
}
// Skip \r\n pairs and consecutive newlines.
if data[i] == '\r' && i+1 < len(data) && data[i+1] == '\n' {
i++
}
start = i + 1
}
}
// Handle final segment without trailing terminator.
if start < len(data) {
trailing := bytes.TrimRight(data[start:], "\r\n")
if len(trailing) > 0 {
segments = append(segments, Segment{
raw: trailing,
delims: delims,
})
}
}
return segments
}
// Segments returns all segments in the message.
// The returned slice shares the Message's internal storage; do not modify it.
func (m *Message) Segments() []Segment {
return m.segments
}
// Delimiters returns the delimiter set extracted from this message's MSH header.
func (m *Message) Delimiters() Delimiters {
return m.delims
}
// Raw returns the original message bytes.
func (m *Message) Raw() []byte {
return m.raw
}
// mergeADD copies data into a new buffer, stripping ADD segment boundaries so
// that ADD fields extend the preceding segment. The segment terminator and the
// "ADD" type marker are stripped, but the field separator that follows is kept,
// so each ADD field becomes the next additional field of the preceding segment.
//
// ADD segments without a field separator (e.g., "ADD\r") are not merged and
// remain as standalone segments.
//
// ADD segments that immediately follow MSH are also left as standalone segments.
// Per HL7v2.5.1, ADD extends data segments, not the message header. Leaving
// ADD visible after MSH allows Concatenate to correctly reassemble cross-message
// continuations where page N+1 starts with MSH followed by an ADD that continues
// the last segment of page N.
//
// ADD segments that follow MSA, DSC, PID, QRD, QRF, URD, or URS are invalid
// per HL7v2.5.1 Section 2.5.2 and cause mergeADD to return ErrInvalidADDContinuation.
func mergeADD(data []byte, fieldSep byte) ([]byte, error) {
pattern1 := [5]byte{'\r', 'A', 'D', 'D', fieldSep}
pattern2 := [5]byte{'\n', 'A', 'D', 'D', fieldSep}
// Fast path: no ADD segments present.
if !bytes.Contains(data, pattern1[:]) && !bytes.Contains(data, pattern2[:]) {
owned := make([]byte, len(data))
copy(owned, data)
return owned, nil
}
// Slow path: merge ADD segments, skipping merge when the preceding segment
// is MSH, and returning an error when the preceding segment is one of the
// types that cannot be continued (MSA, DSC, PID, QRD, QRF, URD, URS).
// segStart tracks where the current segment begins in owned.
owned := make([]byte, 0, len(data))
segStart := 0
i := 0
for i < len(data) {
// Check for \r\nADD<sep> (must check before \rADD<sep>).
if i+6 <= len(data) && data[i] == '\r' && data[i+1] == '\n' &&
data[i+2] == 'A' && data[i+3] == 'D' && data[i+4] == 'D' && data[i+5] == fieldSep {
if isMSHSeg(owned[segStart:], fieldSep) {
owned = append(owned, '\r', '\n')
segStart = len(owned)
i += 2 // skip \r\n; ADD<sep> will be copied normally
} else if isAddErrorSeg(owned[segStart:], fieldSep) {
return nil, ErrInvalidADDContinuation
} else {
i += 5 // skip \r\nADD, keep <sep> as the field boundary
}
continue
}
// Check for \rADD<sep>.
if i+5 <= len(data) && data[i] == '\r' &&
data[i+1] == 'A' && data[i+2] == 'D' && data[i+3] == 'D' && data[i+4] == fieldSep {
if isMSHSeg(owned[segStart:], fieldSep) {
owned = append(owned, '\r')
segStart = len(owned)
i++ // skip \r; ADD<sep> will be copied normally
} else if isAddErrorSeg(owned[segStart:], fieldSep) {
return nil, ErrInvalidADDContinuation
} else {
i += 4 // skip \rADD, keep <sep> as the field boundary
}
continue
}
// Check for \nADD<sep>.
if i+5 <= len(data) && data[i] == '\n' &&
data[i+1] == 'A' && data[i+2] == 'D' && data[i+3] == 'D' && data[i+4] == fieldSep {
if isMSHSeg(owned[segStart:], fieldSep) {
owned = append(owned, '\n')
segStart = len(owned)
i++ // skip \n; ADD<sep> will be copied normally
} else if isAddErrorSeg(owned[segStart:], fieldSep) {
return nil, ErrInvalidADDContinuation
} else {
i += 4 // skip \nADD, keep <sep> as the field boundary
}
continue
}
// Regular byte: copy to output and track segment boundaries.
b := data[i]
owned = append(owned, b)
i++
if b == '\r' {
if i < len(data) && data[i] == '\n' {
owned = append(owned, '\n')
i++
}
segStart = len(owned)
} else if b == '\n' {
segStart = len(owned)
}
}
return owned, nil
}
// isAddErrorSeg reports whether seg begins with a segment type that cannot be
// continued by an ADD segment per HL7v2.5.1 Section 2.5.2: MSA, DSC, PID,
// QRD, QRF, URD, URS.
// (MSH is handled separately by isMSHSeg — ADD after MSH is left standalone.)
func isAddErrorSeg(seg []byte, fieldSep byte) bool {
if len(seg) < 4 || seg[3] != fieldSep {
return false
}
a, b, c := seg[0], seg[1], seg[2]
return (a == 'M' && b == 'S' && c == 'A') ||
(a == 'D' && b == 'S' && c == 'C') ||
(a == 'P' && b == 'I' && c == 'D') ||
(a == 'Q' && b == 'R' && (c == 'D' || c == 'F')) ||
(a == 'U' && b == 'R' && (c == 'D' || c == 'S'))
}
// isMSHSeg reports whether seg is an MSH segment (starts with "MSH" + fieldSep).
func isMSHSeg(seg []byte, fieldSep byte) bool {
return len(seg) >= 4 && seg[0] == 'M' && seg[1] == 'S' && seg[2] == 'H' && seg[3] == fieldSep
}