-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransform.go
More file actions
1094 lines (943 loc) · 30.6 KB
/
transform.go
File metadata and controls
1094 lines (943 loc) · 30.6 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
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
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 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"
// Change describes a single modification to apply to an HL7 message.
// Create Change values using Replace, Null, Omit, Move, or Copy.
//
// The interface is sealed via an unexported method — only types in this
// package can implement it.
type Change interface {
applyChange() // unexported; seals the interface
}
type deleteSegmentChange struct {
segType string
index int
}
func (deleteSegmentChange) applyChange() {}
type deleteAllSegmentsChange struct {
segType string
}
func (deleteAllSegmentsChange) applyChange() {}
type insertAfterChange struct {
afterType string
afterIndex int
newType string
}
func (insertAfterChange) applyChange() {}
type insertBeforeChange struct {
beforeType string
beforeIndex int
newType string
}
func (insertBeforeChange) applyChange() {}
type appendSegmentChange struct {
newType string
}
func (appendSegmentChange) applyChange() {}
type replaceChange struct {
location string
value string
}
func (replaceChange) applyChange() {}
type nullChange struct {
location string
}
func (nullChange) applyChange() {}
type omitChange struct {
location string
}
func (omitChange) applyChange() {}
type moveChange struct {
dst string
src string
}
func (moveChange) applyChange() {}
type copyChange struct {
dst string
src string
}
func (copyChange) applyChange() {}
type mapAllValuesChange struct{ mapper ValueMapper }
func (mapAllValuesChange) applyChange() {}
type mapValueChange struct {
location string
mapper ValueMapper
}
func (mapValueChange) applyChange() {}
// Replace returns a Change that sets the value at location to the given string.
// The value is plain text and will be escaped for the output delimiter set.
func Replace(location, value string) Change { return replaceChange{location, value} }
// Null returns a Change that sets the field at location to the HL7 null value ("").
func Null(location string) Change { return nullChange{location} }
// Omit returns a Change that removes the value at location (makes it empty).
func Omit(location string) Change { return omitChange{location} }
// Move returns a Change that copies the value from src to dst, then clears src.
func Move(dst, src string) Change { return moveChange{dst, src} }
// Copy returns a Change that copies the value at src to dst.
// The source value is preserved (unlike Move, which clears the source).
func Copy(dst, src string) Change { return copyChange{dst, src} }
// DeleteSegment returns a Change that deletes the n-th occurrence (0-based) of
// segType. If the segment is not found, the change is a no-op. Attempting to
// delete MSH returns ErrCannotDeleteMSH.
func DeleteSegment(segType string, index int) Change {
return deleteSegmentChange{segType, index}
}
// DeleteAllSegments returns a Change that deletes all occurrences of segType.
// If none are found, the change is a no-op. Attempting to delete MSH returns
// ErrCannotDeleteMSH.
func DeleteAllSegments(segType string) Change {
return deleteAllSegmentsChange{segType}
}
// InsertSegmentAfter returns a Change that inserts a new empty segment of
// newType immediately after the n-th occurrence (0-based) of afterType.
// Use afterIndex = -1 to target the last occurrence. Returns
// ErrSegmentNotFound if afterType is not present in the message.
func InsertSegmentAfter(afterType string, afterIndex int, newType string) Change {
return insertAfterChange{afterType, afterIndex, newType}
}
// InsertSegmentBefore returns a Change that inserts a new empty segment of
// newType immediately before the n-th occurrence (0-based) of beforeType.
// Use beforeIndex = -1 to target the last occurrence. Returns
// ErrSegmentNotFound if beforeType is not present in the message.
func InsertSegmentBefore(beforeType string, beforeIndex int, newType string) Change {
return insertBeforeChange{beforeType, beforeIndex, newType}
}
// AppendSegment returns a Change that appends a new empty segment of newType
// at the end of the message. This change never returns an error.
func AppendSegment(newType string) Change { return appendSegmentChange{newType} }
// MapAllValues returns a Change that applies mapper to every leaf value in the
// message, including empty and null ("") leaves. MSH-1 and MSH-2
// (delimiter definition fields) are never modified.
//
// The mapper receives unescaped field-content bytes; its output is escaped
// before storage. If the mapper returns an error for any value, Transform
// returns that error and the message is not modified.
func MapAllValues(mapper ValueMapper) Change { return mapAllValuesChange{mapper} }
// MapValue returns a Change that applies mapper to the value at the given
// terser-style location. The mapper receives unescaped bytes at that location
// (nil if the location is absent); its output is escaped before storage.
// If the mapper returns an error, Transform returns that error.
func MapValue(location string, mapper ValueMapper) Change {
return mapValueChange{location, mapper}
}
// Transform applies the given changes to the message and returns a new Message.
// The original message is not modified. The output uses the same delimiters as the source.
func (m *Message) Transform(changes ...Change) (*Message, error) {
return applyTransform(m, m.delims, changes)
}
// TransformWith applies the given changes and returns a new Message using the
// specified delimiter set. All field values are re-encoded from the source
// delimiters to the target delimiters.
func (m *Message) TransformWith(delims Delimiters, changes ...Change) (*Message, error) {
if err := delims.validate(); err != nil {
return nil, err
}
return applyTransform(m, delims, changes)
}
// workBuf holds a single contiguous byte buffer with all segments separated
// by \r terminators. Segment boundaries are tracked as offset pairs so that
// changes can be applied by splicing bytes directly in the buffer.
type workBuf struct {
data []byte
segs []segBound
}
type segBound struct {
start, end int // byte offsets in data; end is exclusive, before \r
}
// newEmptyWorkBuf creates a workBuf seeded with a minimal MSH skeleton
// using the given delimiters. Used by MessageBuilder for from-scratch construction.
func newEmptyWorkBuf(delims Delimiters) workBuf {
data := make([]byte, 0, 256)
data = append(data, 'M', 'S', 'H',
delims.Field, delims.Component, delims.Repetition,
delims.Escape, delims.SubComponent)
end := len(data)
data = append(data, SegmentTerminator)
return workBuf{data: data, segs: []segBound{{0, end}}}
}
func newWorkBuf(src *Message, dstDelims Delimiters) workBuf {
var data []byte
var bounds []segBound
if src.delims == dstDelims {
totalSize := len(src.raw)
data = make([]byte, totalSize, totalSize+totalSize/4)
copy(data, src.raw)
// Walk known segment lengths — O(segments) instead of O(data).
bounds = make([]segBound, len(src.segments))
offset := 0
for i := range src.segments {
segLen := len(src.segments[i].raw)
bounds[i] = segBound{offset, offset + segLen}
offset += segLen
for offset < totalSize && (data[offset] == '\r' || data[offset] == '\n') {
offset++
}
}
} else {
data = reencodeData(src.raw, src.delims, dstDelims)
// Escaping may expand bytes, so scan for terminators.
bounds = make([]segBound, 0, len(src.segments))
start := 0
for i := range data {
if data[i] == '\r' || data[i] == '\n' {
if i > start {
bounds = append(bounds, segBound{start, i})
}
start = i + 1
}
}
if start < len(data) {
bounds = append(bounds, segBound{start, len(data)})
}
}
// Ensure a trailing terminator so new segments can be appended cleanly.
if len(data) > 0 && data[len(data)-1] != '\r' && data[len(data)-1] != '\n' {
data = append(data, SegmentTerminator)
}
return workBuf{data: data, segs: bounds}
}
func (w *workBuf) segBytes(i int) []byte {
return w.data[w.segs[i].start:w.segs[i].end]
}
var mshType = []byte("MSH")
func (w *workBuf) findSeg(typ []byte, idx int) int {
matchIdx := 0
for i := range w.segs {
seg := w.segBytes(i)
if len(seg) >= 3 && bytes.Equal(seg[:3], typ) {
if matchIdx == idx {
return i
}
matchIdx++
}
}
return -1
}
// resolveSegIdx returns the workBuf index of the occurrence of typ selected by
// index. index == -1 selects the last occurrence; non-negative values select
// the n-th (0-based) occurrence. Returns -1 if not found.
func (w *workBuf) resolveSegIdx(typ []byte, index int) int {
if index >= 0 {
return w.findSeg(typ, index)
}
last := -1
for i := range w.segs {
if seg := w.segBytes(i); len(seg) >= 3 && bytes.Equal(seg[:3], typ) {
last = i
}
}
return last
}
// deleteSegAt removes the segment at segIdx from the buffer, including its
// trailing \r terminator.
func (w *workBuf) deleteSegAt(segIdx int) {
start := w.segs[segIdx].start
end := w.segs[segIdx].end + 1 // include the \r terminator
if end > len(w.data) {
end = len(w.data)
}
removed := end - start
copy(w.data[start:], w.data[end:])
w.data = w.data[:len(w.data)-removed]
copy(w.segs[segIdx:], w.segs[segIdx+1:])
w.segs = w.segs[:len(w.segs)-1]
for i := segIdx; i < len(w.segs); i++ {
w.segs[i].start -= removed
w.segs[i].end -= removed
}
}
// insertBefore inserts a new segment of newType immediately before the segment
// at position pos. If pos == len(w.segs), the segment is appended at the end.
func (w *workBuf) insertBefore(pos int, newType []byte) {
var bytePos int
if pos < len(w.segs) {
bytePos = w.segs[pos].start
} else {
bytePos = len(w.data)
}
shift := len(newType) + 1 // newType bytes + \r
newLen := len(w.data) + shift
if cap(w.data) >= newLen {
w.data = w.data[:newLen]
copy(w.data[bytePos+shift:], w.data[bytePos:newLen-shift])
} else {
buf := make([]byte, newLen, newLen+newLen/4)
copy(buf[:bytePos], w.data[:bytePos])
copy(buf[bytePos+shift:], w.data[bytePos:])
w.data = buf
}
copy(w.data[bytePos:], newType)
w.data[bytePos+len(newType)] = SegmentTerminator
newBound := segBound{bytePos, bytePos + len(newType)}
w.segs = append(w.segs, segBound{})
copy(w.segs[pos+1:], w.segs[pos:])
w.segs[pos] = newBound
for i := pos + 1; i < len(w.segs); i++ {
w.segs[i].start += shift
w.segs[i].end += shift
}
}
func (w *workBuf) createSeg(typ []byte, idx int, delims Delimiters) int {
count := 0
for i := range w.segs {
if seg := w.segBytes(i); len(seg) >= 3 && bytes.Equal(seg[:3], typ) {
count++
}
}
lastIdx := -1
for count <= idx {
start := len(w.data)
if bytes.Equal(typ, mshType) {
w.data = append(w.data, typ[0], typ[1], typ[2],
delims.Field, delims.Component, delims.Repetition,
delims.Escape, delims.SubComponent)
} else {
w.data = append(w.data, typ...)
}
end := len(w.data)
w.data = append(w.data, SegmentTerminator)
w.segs = append(w.segs, segBound{start, end})
lastIdx = len(w.segs) - 1
count++
}
return lastIdx
}
func (w *workBuf) readField(segIdx int, delims Delimiters, fieldNum int) []byte {
return readFieldBytes(w.segBytes(segIdx), delims, fieldNum)
}
func (w *workBuf) replaceField(segIdx int, delims Delimiters, fieldNum int, newValue []byte) {
seg := w.segBytes(segIdx)
fStart, fEnd, found := fieldByteRange(seg, delims, fieldNum)
if found {
w.splice(segIdx, w.segs[segIdx].start+fStart, w.segs[segIdx].start+fEnd, newValue)
} else {
gaps := fieldGaps(seg, delims, fieldNum)
w.spliceExtend(segIdx, w.segs[segIdx].end, gaps, delims.Field, newValue)
}
}
// splice replaces w.data[start:end] with data and updates segment bounds.
func (w *workBuf) splice(segIdx, start, end int, data []byte) {
delta := len(data) - (end - start)
if delta == 0 {
copy(w.data[start:end], data)
return
}
oldLen := len(w.data)
newLen := oldLen + delta
if delta > 0 {
if cap(w.data) >= newLen {
w.data = w.data[:newLen]
copy(w.data[end+delta:newLen], w.data[end:oldLen])
} else {
newBuf := make([]byte, newLen, newLen+newLen/4)
copy(newBuf[:start], w.data[:start])
copy(newBuf[start+len(data):], w.data[end:])
w.data = newBuf
}
} else {
copy(w.data[start+len(data):], w.data[end:])
w.data = w.data[:newLen]
}
copy(w.data[start:start+len(data)], data)
w.segs[segIdx].end += delta
for i := segIdx + 1; i < len(w.segs); i++ {
w.segs[i].start += delta
w.segs[i].end += delta
}
}
func (w *workBuf) parse() (*Message, error) {
return ParseMessage(w.data)
}
// mshEncEnd returns the byte offset immediately after MSH-2 encoding characters.
// For a well-formed MSH segment "MSH|^~\&|...", this is the index of the
// second field separator. segRaw must be at least 4 bytes (MSH + field sep).
func mshEncEnd(segRaw []byte, delims Delimiters) int {
i := 4
for i < len(segRaw) && segRaw[i] != delims.Field {
i++
}
return i
}
// fieldByteRange finds the byte range [start, end) of fieldNum within segRaw.
// Zero allocations.
func fieldByteRange(segRaw []byte, delims Delimiters, fieldNum int) (start, end int, found bool) {
isMSH := len(segRaw) >= 3 && segRaw[0] == 'M' && segRaw[1] == 'S' && segRaw[2] == 'H'
var scanFrom int
var targetIdx int
if isMSH {
scanFrom = mshEncEnd(segRaw, delims)
targetIdx = fieldNum - 3
} else {
scanFrom = 3
targetIdx = fieldNum - 1
}
if targetIdx < 0 || scanFrom >= len(segRaw) {
return 0, 0, false
}
idx := -1
fStart := -1
for i := scanFrom; i < len(segRaw); i++ {
if segRaw[i] == delims.Field {
idx++
if idx == targetIdx {
fStart = i + 1
} else if idx == targetIdx+1 {
return fStart, i, true
}
}
}
if fStart >= 0 {
return fStart, len(segRaw), true
}
return 0, 0, false
}
// fieldGaps returns the number of field separators needed to extend a segment
// so that fieldNum exists. Pure computation, zero allocations.
func fieldGaps(segRaw []byte, delims Delimiters, fieldNum int) int {
isMSH := len(segRaw) >= 3 && segRaw[0] == 'M' && segRaw[1] == 'S' && segRaw[2] == 'H'
var maxField int
if isMSH {
encEnd := mshEncEnd(segRaw, delims)
if encEnd < len(segRaw) {
maxField = countDelimited(segRaw[encEnd+1:], delims.Field) + 2
} else if len(segRaw) > 3 {
maxField = 2
}
} else {
if len(segRaw) > 3 && segRaw[3] == delims.Field {
maxField = countDelimited(segRaw[4:], delims.Field)
}
}
return fieldNum - maxField
}
// spliceExtend inserts gaps copies of sep followed by value at position at,
// growing w.data in place. Avoids the intermediate []byte that fieldExtension
// previously allocated.
func (w *workBuf) spliceExtend(segIdx, at, gaps int, sep byte, value []byte) {
dataLen := gaps + len(value)
if dataLen == 0 {
return
}
oldLen := len(w.data)
newLen := oldLen + dataLen
if cap(w.data) >= newLen {
w.data = w.data[:newLen]
copy(w.data[at+dataLen:newLen], w.data[at:oldLen])
} else {
newBuf := make([]byte, newLen, newLen+newLen/4)
copy(newBuf[:at], w.data[:at])
copy(newBuf[at+dataLen:], w.data[at:oldLen])
w.data = newBuf
}
pos := at
for range gaps {
w.data[pos] = sep
pos++
}
copy(w.data[pos:], value)
w.segs[segIdx].end += dataLen
for i := segIdx + 1; i < len(w.segs); i++ {
w.segs[i].start += dataLen
w.segs[i].end += dataLen
}
}
// readFieldBytes extracts the raw bytes of a field from segment raw bytes.
func readFieldBytes(segRaw []byte, delims Delimiters, fieldNum int) []byte {
if len(segRaw) < 3 || fieldNum < 1 {
return nil
}
isMSH := segRaw[0] == 'M' && segRaw[1] == 'S' && segRaw[2] == 'H'
if isMSH {
switch fieldNum {
case 1:
if len(segRaw) < 4 {
return nil
}
return segRaw[3:4]
case 2:
if len(segRaw) < 5 {
return nil
}
return segRaw[4:mshEncEnd(segRaw, delims)]
}
}
start, end, found := fieldByteRange(segRaw, delims, fieldNum)
if !found {
return nil
}
return segRaw[start:end]
}
var nullValue = []byte{'"', '"'}
func applyTransform(src *Message, dstDelims Delimiters, changes []Change) (*Message, error) {
// Short-circuit: no changes with same delimiters.
if len(changes) == 0 && src.delims == dstDelims {
return ParseMessage(src.raw)
}
// Short-circuit: no changes with different delimiters — reencode and
// parse directly, skipping the workBuf bounds computation.
if len(changes) == 0 {
return ParseMessage(reencodeData(src.raw, src.delims, dstDelims))
}
w := newWorkBuf(src, dstDelims)
for _, c := range changes {
if err := applyOneChange(&w, dstDelims, c); err != nil {
return nil, err
}
}
return w.parse()
}
func validateLocation(location string) (Location, error) {
loc, err := ParseLocation(location)
if err != nil {
return loc, err
}
return loc, rejectMSHDelimFields(loc)
}
func applyOneChange(w *workBuf, delims Delimiters, c Change) error {
switch ch := c.(type) {
case replaceChange:
loc, err := validateLocation(ch.location)
if err != nil {
return err
}
escaped := Escape([]byte(ch.value), delims)
applyValueAtLocation(w, delims, loc, escaped)
case nullChange:
loc, err := validateLocation(ch.location)
if err != nil {
return err
}
applyValueAtLocation(w, delims, loc, nullValue)
case omitChange:
loc, err := validateLocation(ch.location)
if err != nil {
return err
}
applyValueAtLocation(w, delims, loc, nil)
case moveChange:
dstLoc, err := validateLocation(ch.dst)
if err != nil {
return err
}
srcLoc, err := validateLocation(ch.src)
if err != nil {
return err
}
moveVal := readValueAtLocation(w, delims, srcLoc)
// Copy: subsequent splices may shift or reallocate w.data.
if moveVal != nil {
cp := make([]byte, len(moveVal))
copy(cp, moveVal)
moveVal = cp
}
applyValueAtLocation(w, delims, dstLoc, moveVal)
applyValueAtLocation(w, delims, srcLoc, nil)
case copyChange:
dstLoc, err := validateLocation(ch.dst)
if err != nil {
return err
}
srcLoc, err := validateLocation(ch.src)
if err != nil {
return err
}
copyVal := readValueAtLocation(w, delims, srcLoc)
// Copy: subsequent splices may shift or reallocate w.data.
if copyVal != nil {
cp := make([]byte, len(copyVal))
copy(cp, copyVal)
copyVal = cp
}
applyValueAtLocation(w, delims, dstLoc, copyVal)
case deleteSegmentChange:
if ch.segType == "MSH" {
return ErrCannotDeleteMSH
}
if segIdx := w.findSeg([]byte(ch.segType), ch.index); segIdx >= 0 {
w.deleteSegAt(segIdx)
}
case deleteAllSegmentsChange:
if ch.segType == "MSH" {
return ErrCannotDeleteMSH
}
// Collect indices in a single pass, then delete right-to-left to keep
// earlier indices valid after each deletion.
var indices []int
for i := range w.segs {
if seg := w.segBytes(i); len(seg) >= 3 && string(seg[:3]) == ch.segType {
indices = append(indices, i)
}
}
for i := len(indices) - 1; i >= 0; i-- {
w.deleteSegAt(indices[i])
}
case insertAfterChange:
afterIdx := w.resolveSegIdx([]byte(ch.afterType), ch.afterIndex)
if afterIdx < 0 {
return ErrSegmentNotFound
}
w.insertBefore(afterIdx+1, []byte(ch.newType))
case insertBeforeChange:
beforeIdx := w.resolveSegIdx([]byte(ch.beforeType), ch.beforeIndex)
if beforeIdx < 0 {
return ErrSegmentNotFound
}
w.insertBefore(beforeIdx, []byte(ch.newType))
case appendSegmentChange:
w.insertBefore(len(w.segs), []byte(ch.newType))
case mapAllValuesChange:
return applyMapAllValues(w, delims, ch.mapper)
case mapValueChange:
loc, err := validateLocation(ch.location)
if err != nil {
return err
}
raw := readValueAtLocation(w, delims, loc)
newRaw, err := mapLeafValue(raw, delims, ch.mapper)
if err != nil {
return err
}
applyValueAtLocation(w, delims, loc, newRaw)
}
return nil
}
func applyValueAtLocation(w *workBuf, delims Delimiters, loc Location, value []byte) {
segType := []byte(loc.Segment)
segIdx := w.findSeg(segType, loc.SegmentIndex)
if isFieldLevel(loc) {
if segIdx < 0 {
segIdx = w.createSeg(segType, loc.SegmentIndex, delims)
}
w.replaceField(segIdx, delims, loc.Field, value)
return
}
// Sub-field: read current field, splice at position, write back.
var fieldBytes []byte
if segIdx >= 0 {
fieldBytes = w.readField(segIdx, delims, loc.Field)
}
newFieldBytes := spliceField(fieldBytes, delims, loc.Repetition, loc.Component, loc.SubComponent, value)
if segIdx < 0 {
segIdx = w.createSeg(segType, loc.SegmentIndex, delims)
}
w.replaceField(segIdx, delims, loc.Field, newFieldBytes)
}
func readValueAtLocation(w *workBuf, delims Delimiters, loc Location) []byte {
segIdx := w.findSeg([]byte(loc.Segment), loc.SegmentIndex)
if segIdx < 0 {
return nil
}
fieldBytes := readFieldBytes(w.segBytes(segIdx), delims, loc.Field)
if fieldBytes == nil {
return nil
}
if isFieldLevel(loc) {
return fieldBytes
}
return extractFromField(fieldBytes, delims, loc.Repetition, loc.Component, loc.SubComponent)
}
func isFieldLevel(loc Location) bool {
return loc.Repetition == 0 && loc.Component == 0 && loc.SubComponent == 0
}
func rejectMSHDelimFields(loc Location) error {
if loc.Segment == "MSH" && (loc.Field == 1 || loc.Field == 2) {
return ErrMSHDelimiterField
}
return nil
}
// spliceField modifies a field's bytes at the specified hierarchical position.
// It navigates to the target byte range using offsets (no intermediate slices)
// and builds the result with a single allocation.
func spliceField(raw []byte, delims Delimiters, rep, comp, sub int, value []byte) []byte {
var repPad, compPad, subPad int
pStart, pEnd := 0, len(raw)
// Level 1: Repetition (0-based).
s, e, ok := nthRange(raw, delims.Repetition, rep)
if ok {
pStart, pEnd = s, e
} else {
repPad = rep - countDelimited(raw, delims.Repetition) + 1
pStart = len(raw)
pEnd = len(raw)
}
// Level 2: Component (1-based; only entered when comp > 0).
if comp > 0 {
ci := comp - 1
piece := raw[pStart:pEnd]
cs, ce, cok := nthRange(piece, delims.Component, ci)
if cok {
pEnd = pStart + ce
pStart = pStart + cs
} else {
compPad = ci - countDelimited(piece, delims.Component) + 1
pStart = pEnd
}
// Level 3: Subcomponent (1-based; only entered when sub > 0).
if sub > 0 {
si := sub - 1
piece = raw[pStart:pEnd]
ss, se, sok := nthRange(piece, delims.SubComponent, si)
if sok {
pEnd = pStart + se
pStart = pStart + ss
} else {
subPad = si - countDelimited(piece, delims.SubComponent) + 1
pStart = pEnd
}
}
}
// Build result: raw[:pStart] + padding delimiters + value + raw[pEnd:]
n := pStart + repPad + compPad + subPad + len(value) + len(raw) - pEnd
result := make([]byte, n)
pos := copy(result, raw[:pStart])
for range repPad {
result[pos] = delims.Repetition
pos++
}
for range compPad {
result[pos] = delims.Component
pos++
}
for range subPad {
result[pos] = delims.SubComponent
pos++
}
pos += copy(result[pos:], value)
copy(result[pos:], raw[pEnd:])
return result
}
// extractFromField extracts the value at the specified position from field bytes.
func extractFromField(raw []byte, delims Delimiters, rep, comp, sub int) []byte {
piece := nthSlice(raw, delims.Repetition, rep)
if piece == nil {
return nil
}
if comp == 0 {
return piece
}
piece = nthSlice(piece, delims.Component, comp-1)
if piece == nil {
return nil
}
if sub == 0 {
return piece
}
return nthSlice(piece, delims.SubComponent, sub-1)
}
// reencodeData re-encodes data from src to dst delimiters in a single pass.
// The MSH header (segment type + field separator + 4 encoding characters) is
// remapped directly. For the remainder: structural delimiter bytes are mapped
// to their destination equivalents; delimiter escape sequences (F/S/T/R/E) are
// resolved to their literal source delimiter value and then re-escaped if that
// value collides with a destination delimiter; other escape sequences are
// preserved with the escape character remapped; and plain-text bytes that
// collide with a destination delimiter are escaped.
func reencodeData(data []byte, src, dst Delimiters) []byte {
out := make([]byte, 0, len(data)+len(data)/4)
// MSH-1 and MSH-2 define the delimiter set as literal bytes — they are
// not structural separators or escape sequences, so remap them directly.
i := 0
if len(data) >= 8 && data[0] == 'M' && data[1] == 'S' && data[2] == 'H' && data[3] == src.Field {
out = append(out, 'M', 'S', 'H', dst.Field,
dst.Component, dst.Repetition, dst.Escape, dst.SubComponent)
i = 8
}
for i < len(data) {
b := data[i]
if b == src.Escape {
// Find the closing escape character.
close := bytes.IndexByte(data[i+1:], src.Escape)
if close == -1 {
// Unclosed escape — treat as literal byte.
out = appendMaybeEscaped(out, b, dst)
i++
continue
}
body := data[i+1 : i+1+close]
// Delimiter codes: resolve to the literal source delimiter
// value, then re-escape only if it collides with dst.
if len(body) == 1 {
switch body[0] {
case 'F':
out = appendMaybeEscaped(out, src.Field, dst)
case 'S':
out = appendMaybeEscaped(out, src.Component, dst)
case 'T':
out = appendMaybeEscaped(out, src.SubComponent, dst)
case 'R':
out = appendMaybeEscaped(out, src.Repetition, dst)
case 'E':
out = appendMaybeEscaped(out, src.Escape, dst)
default:
out = append(out, dst.Escape, body[0], dst.Escape)
}
} else {
// Multi-byte body (hex, charset, locally-defined, formatted
// text) — preserve with escape character remapped.
out = append(out, dst.Escape)
out = append(out, body...)
out = append(out, dst.Escape)
}
i += close + 2 // skip opening escape + body + closing escape
continue
}
// Structural delimiters — map to destination equivalents.
switch b {
case src.Field:
out = append(out, dst.Field)
case src.Component:
out = append(out, dst.Component)
case src.Repetition:
out = append(out, dst.Repetition)
case src.SubComponent:
out = append(out, dst.SubComponent)
default:
out = appendMaybeEscaped(out, b, dst)
}
i++
}
return out
}
// applyMapAllValues applies mapper to every leaf (subcomponent-level) value in
// the message. MSH-1 and MSH-2 are never touched. The mapper receives
// unescaped bytes and its result is re-escaped before storage.
func applyMapAllValues(w *workBuf, delims Delimiters, mapper ValueMapper) error {
for segIdx := range w.segs {
segRaw := w.segBytes(segIdx)
isMSH := len(segRaw) >= 3 && segRaw[0] == 'M' && segRaw[1] == 'S' && segRaw[2] == 'H'
// MSH fields start at 3 (skip MSH-1 and MSH-2).
firstField := 1
if isMSH {
firstField = 3
}
for fieldNum := firstField; ; fieldNum++ {
// Re-read segment bytes on each iteration because replaceField may
// reallocate w.data and shift segment offsets.
segRaw = w.segBytes(segIdx)
raw := readFieldBytes(segRaw, delims, fieldNum)
if raw == nil {
break
}
newRaw, err := mapFieldValues(raw, delims, mapper)
if err != nil {
return err
}
if !bytes.Equal(raw, newRaw) {
w.replaceField(segIdx, delims, fieldNum, newRaw)
}
}
}
return nil
}
// mapFieldValues applies mapper to every leaf within a field's raw bytes.
// The field may contain repetitions, each of which may contain components, etc.
// Returns raw unchanged (no allocation) if the mapper is a no-op for all leaves.
func mapFieldValues(raw []byte, delims Delimiters, mapper ValueMapper) ([]byte, error) {
n := countDelimited(raw, delims.Repetition)
if n == 1 {
return mapRepValues(raw, delims, mapper)
}
return mapDelimited(raw, delims.Repetition, func(piece []byte) ([]byte, error) {
return mapRepValues(piece, delims, mapper)
})
}
// mapRepValues applies mapper to every leaf within a single repetition's bytes.
// Returns raw unchanged (no allocation) if the mapper is a no-op for all leaves.