summaryrefslogtreecommitdiff
path: root/vendor/github.com/uptrace/bun/dialect/pgdialect/array_parser.go
blob: 1c927fca0ddcb5180181d6a1e9a494e3d1fd54e2 (plain)
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
package pgdialect

import (
	"bytes"
	"fmt"
	"io"
)

type arrayParser struct {
	b []byte
	i int

	buf []byte
	err error
}

func newArrayParser(b []byte) *arrayParser {
	p := &arrayParser{
		b: b,
		i: 1,
	}
	if len(b) < 2 || b[0] != '{' || b[len(b)-1] != '}' {
		p.err = fmt.Errorf("bun: can't parse array: %q", b)
	}
	return p
}

func (p *arrayParser) NextElem() ([]byte, error) {
	if p.err != nil {
		return nil, p.err
	}

	c, err := p.readByte()
	if err != nil {
		return nil, err
	}

	switch c {
	case '}':
		return nil, io.EOF
	case '"':
		b, err := p.readSubstring()
		if err != nil {
			return nil, err
		}

		if p.peek() == ',' {
			p.skipNext()
		}

		return b, nil
	default:
		b := p.readSimple()
		if bytes.Equal(b, []byte("NULL")) {
			b = nil
		}

		if p.peek() == ',' {
			p.skipNext()
		}

		return b, nil
	}
}

func (p *arrayParser) readSimple() []byte {
	p.unreadByte()

	if i := bytes.IndexByte(p.b[p.i:], ','); i >= 0 {
		b := p.b[p.i : p.i+i]
		p.i += i
		return b
	}

	b := p.b[p.i : len(p.b)-1]
	p.i = len(p.b) - 1
	return b
}

func (p *arrayParser) readSubstring() ([]byte, error) {
	c, err := p.readByte()
	if err != nil {
		return nil, err
	}

	p.buf = p.buf[:0]
	for {
		if c == '"' {
			break
		}

		next, err := p.readByte()
		if err != nil {
			return nil, err
		}

		if c == '\\' {
			switch next {
			case '\\', '"':
				p.buf = append(p.buf, next)

				c, err = p.readByte()
				if err != nil {
					return nil, err
				}
			default:
				p.buf = append(p.buf, '\\')
				c = next
			}
			continue
		}

		p.buf = append(p.buf, c)
		c = next
	}

	return p.buf, nil
}

func (p *arrayParser) valid() bool {
	return p.i < len(p.b)
}

func (p *arrayParser) readByte() (byte, error) {
	if p.valid() {
		c := p.b[p.i]
		p.i++
		return c, nil
	}
	return 0, io.EOF
}

func (p *arrayParser) unreadByte() {
	p.i--
}

func (p *arrayParser) peek() byte {
	if p.valid() {
		return p.b[p.i]
	}
	return 0
}

func (p *arrayParser) skipNext() {
	p.i++
}