-
Notifications
You must be signed in to change notification settings - Fork 46
/
field.go
103 lines (94 loc) · 2.21 KB
/
field.go
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
package golevel7
import (
"fmt"
"golevel7/commons"
"strings"
)
// Field is an HL7 field
type Field struct {
SegName string
SeqNum int
Components []Component
Value []rune
}
func (f *Field) NumSubFields() int {
return len(f.Components)
}
func (f *Field) String() string {
// var str string
// for _, c := range f.Components {
// str += "Field Component: " + string(c.Value) + "\n"
// str += c.String()
// }
if f.SeqNum == 0 {
return fmt.Sprintf("\t%v", commons.FieldNames[f.SegName][f.SeqNum])
}
return fmt.Sprintf("\t%v: %v", commons.FieldNames[f.SegName][f.SeqNum], string(f.Value))
}
func (f *Field) parse(seps *Delimeters) error {
r := strings.NewReader(string(f.Value))
i := 0
ii := 0
for {
ch, _, _ := r.ReadRune()
ii++
switch {
case ch == eof || (ch == endMsg && seps.LFTermMsg):
if ii > i {
cmp := Component{Value: f.Value[i : ii-1]}
cmp.parse(seps)
f.Components = append(f.Components, cmp)
}
return nil
case ch == seps.Component:
cmp := Component{Value: f.Value[i : ii-1]}
cmp.parse(seps)
f.Components = append(f.Components, cmp)
i = ii
case ch == seps.Escape:
ii++
r.ReadRune()
}
}
}
func (f *Field) encode(seps *Delimeters) []rune {
buf := []string{}
for _, c := range f.Components {
buf = append(buf, string(c.Value))
}
return []rune(string(strings.Join(buf, string(seps.Component))))
}
// Component returns the component i
func (f *Field) Component(i int) (*Component, error) {
if i > len(f.Components) || i < 1 {
return nil, fmt.Errorf("Component out of range")
}
return &f.Components[i-1], nil
}
// Get returns the value specified by the Location
func (f *Field) Get(l *Location) (string, error) {
if l.Comp == -1 {
return string(f.Value), nil
}
comp, err := f.Component(l.Comp)
if err != nil {
return "", err
}
return comp.Get(l)
}
// Set will insert a value into a message at Location
func (f *Field) Set(l *Location, val string, seps *Delimeters) error {
loc := l.Comp
if loc < 0 {
loc = 0
}
if x := loc - len(f.Components) + 1; x > 0 {
f.Components = append(f.Components, make([]Component, x)...)
}
err := f.Components[loc].Set(l, val, seps)
if err != nil {
return err
}
f.Value = f.encode(seps)
return nil
}