forked from go-pg/pg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharray_parser.go
159 lines (141 loc) · 2.36 KB
/
array_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
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
package types
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"github.com/go-pg/pg/internal/parser"
)
var endOfArray = errors.New("pg: end of array")
type arrayParser struct {
p parser.StreamingParser
stickyErr error
}
func newArrayParserErr(err error) *arrayParser {
return &arrayParser{
stickyErr: err,
}
}
func newArrayParser(rd Reader) *arrayParser {
p := parser.NewStreamingParser(rd)
err := p.SkipByte('{')
if err != nil {
return newArrayParserErr(err)
}
return &arrayParser{
p: p,
}
}
func (p *arrayParser) NextElem() ([]byte, error) {
if p.stickyErr != nil {
return nil, p.stickyErr
}
c, err := p.p.ReadByte()
if err != nil {
if err == io.EOF {
return nil, endOfArray
}
return nil, err
}
switch c {
case '"':
b, err := p.p.ReadSubstring()
if err != nil {
return nil, err
}
err = p.readCommaBrace()
if err != nil {
return nil, err
}
return b, nil
case '{':
b, err := p.readSubArray()
if err != nil {
return nil, err
}
err = p.readCommaBrace()
if err != nil {
return nil, err
}
return b, nil
case '}':
return nil, endOfArray
default:
err = p.p.UnreadByte()
if err != nil {
return nil, err
}
var b []byte
for {
bb, err := p.p.ReadSlice(',')
if b == nil {
b = bb[:len(bb):len(bb)]
} else {
b = append(b, bb...)
}
if err == nil {
b = b[:len(b)-1]
break
}
if err == bufio.ErrBufferFull {
continue
}
if err == io.EOF {
if b[len(b)-1] == '}' {
b = b[:len(b)-1]
break
}
}
return nil, err
}
if bytes.Equal(b, []byte("NULL")) {
return nil, nil
}
return b, nil
}
}
func (p *arrayParser) readSubArray() ([]byte, error) {
var b []byte
b = append(b, '{')
for {
c, err := p.p.ReadByte()
if err != nil {
return nil, err
}
if c == '}' {
b = append(b, '}')
return b, nil
}
if c == '"' {
b = append(b, '"')
for {
bb, err := p.p.ReadSlice('"')
b = append(b, bb...)
if err != nil {
if err == bufio.ErrBufferFull {
continue
}
return nil, err
}
if len(b) > 1 && b[len(b)-2] != '\\' {
break
}
}
continue
}
b = append(b, c)
}
}
func (p *arrayParser) readCommaBrace() error {
c, err := p.p.ReadByte()
if err != nil {
return err
}
switch c {
case ',', '}':
return nil
default:
return fmt.Errorf("pg: got %q, wanted ',' or '}'", c)
}
}