forked from dshills/golevel7
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathdecode.go
73 lines (66 loc) · 1.38 KB
/
decode.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
package hl7
import (
"bufio"
"bytes"
"io"
"strings"
)
// Decoder reades hl7 messages from a stream
type Decoder struct {
r io.Reader
}
// NewDecoder returns a new Decoder that reades from from stream r
// Assumes one message per stream
func NewDecoder(r io.Reader) *Decoder {
return &Decoder{r: r}
}
const bufCap = 1024 * 100
func readBuf(reader io.Reader) ([]byte, error) {
r := bufio.NewReader(reader)
buf := make([]byte, 0, bufCap)
for {
n, err := r.Read(buf[:cap(buf)])
buf = buf[:n]
switch {
case err == io.EOF:
return buf, err
case n < bufCap:
return buf, nil
case err != nil:
return nil, err
}
}
}
// Split will split a set of HL7 messages
// \x0b MESSAGE \x1c\x0d
func Split(buf []byte) [][]byte {
msgSep := []byte{'\x1c', '\x0d'}
msgs := bytes.Split(buf, msgSep)
vmsgs := [][]byte{}
for _, msg := range msgs {
if len(msg) < 4 {
continue
}
msg = bytes.TrimLeft(msg, "\x0b")
msg = []byte(strings.Replace(string(msg), "\n", "\r", -1))
vmsgs = append(vmsgs, msg)
}
return vmsgs
}
// Messages returns a new Message slice parsed from stream r
func (d *Decoder) Messages() ([]*Message, error) {
buf, err := readBuf(d.r)
if err != nil {
return nil, err
}
bufs := Split(buf)
z := []*Message{}
for _, buf := range bufs {
msg := NewMessage(buf)
if err := msg.Parse(); err != nil {
return nil, err
}
z = append(z, msg)
}
return z, nil
}