forked from go-pg/pg
/
tag.go
91 lines (74 loc) · 1.22 KB
/
tag.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
package orm
import (
"github.com/go-pg/pg/internal/parser"
)
type tag struct {
Name string
Options map[string]string
}
func parseTag(s string) *tag {
p := &tagParser{
Parser: parser.NewString(s),
}
p.parseKey()
return &p.tag
}
type tagParser struct {
*parser.Parser
tag tag
key string
}
func (p *tagParser) setTagOption(key, value string) {
if p.tag.Options == nil {
p.tag.Options = make(map[string]string)
}
p.tag.Options[key] = value
}
func (p *tagParser) parseKey() {
start := p.Position()
end := minIndex(p.PositionByte(','), p.PositionByte(':'))
b := p.Slice(start, end)
c := p.Read()
if c == ':' {
p.key = string(b)
p.parseValue()
return
}
if start == 0 {
p.tag.Name = string(b)
} else {
p.setTagOption(string(b), "")
}
if p.Valid() {
p.parseKey()
}
}
func (p *tagParser) parseValue() {
c := p.Peek()
quote := c == '\''
start := p.Position()
if quote {
start++
p.Advance()
}
var end int
if quote {
end = p.PositionByte('\'')
} else {
end = p.PositionByte(',')
}
value := p.Slice(start, end)
p.setTagOption(p.key, string(value))
if quote {
p.Skip('\'')
}
if p.Valid() {
p.parseKey()
}
}
func minIndex(a, b int) int {
if a <= b {
return a
}
return b
}