forked from dshills/golevel7
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decode.go
87 lines (80 loc) · 1.67 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package golevel7
import (
"bufio"
"bytes"
"io"
//"log"
)
// 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)
superBuf := []byte{}
var err error
for {
buf := make([]byte, 0, bufCap)
n, err := r.Read(buf[:cap(buf)])
buf = buf[:n]
quit := false
switch {
case err == io.EOF:
//log.Printf("->err == io.EOF")
superBuf = append(superBuf, buf...)
quit = true
case n < bufCap:
//log.Printf("->n < bufCap")
superBuf = append(superBuf, buf...)
//quit = true
case err != nil:
//log.Printf("->err != nil")
superBuf = nil
default:
//log.Printf("->default")
superBuf = append(superBuf, buf...)
}
if quit {
break
}
}
return superBuf, 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")
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
}