forked from quickfixgo/quickfix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
121 lines (96 loc) · 2.2 KB
/
parser.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package quickfix
import (
"bytes"
"io"
"time"
)
const (
defaultBufSize = 4096
)
type parser struct {
buffer []byte
reader io.Reader
lastRead time.Time
}
func newParser(reader io.Reader) *parser {
return &parser{reader: reader}
}
func (p *parser) readMore() (int, error) {
if len(p.buffer) == cap(p.buffer) {
newBuffer := make([]byte, len(p.buffer), len(p.buffer)+defaultBufSize)
copy(newBuffer, p.buffer)
p.buffer = newBuffer
}
n, e := p.reader.Read(p.buffer[len(p.buffer):cap(p.buffer)])
p.lastRead = time.Now()
p.buffer = p.buffer[:len(p.buffer)+n]
return n, e
}
func (p *parser) findIndex(delim []byte) (int, error) {
return p.findIndexAfterOffset(0, delim)
}
func (p *parser) findIndexAfterOffset(offset int, delim []byte) (int, error) {
for {
if offset > len(p.buffer) {
if n, err := p.readMore(); n == 0 && err != nil {
return -1, err
}
continue
}
if index := bytes.Index(p.buffer[offset:], delim); index != -1 {
return index + offset, nil
}
n, err := p.readMore()
if n == 0 && err != nil {
return -1, err
}
}
}
func (p *parser) findStart() (int, error) {
return p.findIndex([]byte("8="))
}
func (p *parser) findEndAfterOffset(offset int) (int, error) {
index, err := p.findIndexAfterOffset(offset, []byte("\00110="))
if err != nil {
return index, err
}
index, err = p.findIndexAfterOffset(index+1, []byte("\001"))
if err != nil {
return index, err
}
return index + 1, nil
}
func (p *parser) jumpLength() (int, error) {
lengthIndex, err := p.findIndex([]byte("9="))
if err != nil {
return 0, err
}
lengthIndex += 3
offset, err := p.findIndexAfterOffset(lengthIndex, []byte("\001"))
if err != nil {
return 0, err
}
length, err := atoi(p.buffer[lengthIndex:offset])
if err != nil {
return length, err
}
return offset + length, nil
}
func (p *parser) ReadMessage() ([]byte, error) {
start, err := p.findStart()
if err != nil {
return []byte{}, err
}
p.buffer = p.buffer[start:]
index, err := p.jumpLength()
if err != nil {
return []byte{}, err
}
index, err = p.findEndAfterOffset(index)
if err != nil {
return []byte{}, err
}
msgBytes := p.buffer[:index:index]
p.buffer = p.buffer[index:]
return msgBytes, nil
}