-
Notifications
You must be signed in to change notification settings - Fork 8
/
parser.go
109 lines (98 loc) · 1.76 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
package httpsign
import (
"bytes"
"io"
)
type parser struct {
input string
pos int
ch byte
}
func newParser(input string) *parser {
p := &parser{input: input, pos: -1}
p.readChar()
return p
}
func (p *parser) readChar() {
if p.pos+1 >= len(p.input) {
p.ch = 0
} else {
p.ch = p.input[p.pos+1]
}
p.pos++
}
func (p *parser) peekChar() byte {
if p.pos+1 >= len(p.input) {
return 0
}
return p.input[p.pos+1]
}
func (p *parser) nextParam() (string, string, error) {
var (
key = bytes.NewBuffer(nil)
keyParsed = false
val = bytes.NewBuffer(nil)
valParsed = false
)
if p.ch == 0 {
return "", "", io.EOF
}
for {
switch p.ch {
case ',', 0:
if !valParsed {
return "", "", ErrUnterminatedParameter
}
p.readChar()
return key.String(), val.String(), nil
case '"':
if !keyParsed {
return "", "", ErrMisingEqualCharacter
}
if p.peekChar() != ',' && p.peekChar() != 0 {
if err := val.WriteByte(p.ch); err != nil {
return "", "", err
}
} else {
valParsed = true
}
p.readChar()
case '=':
if !keyParsed {
p.readChar()
if p.ch != '"' {
return "", "", ErrMisingDoubleQuote
}
keyParsed = true
} else {
if err := val.WriteByte(p.ch); err != nil {
return "", "", err
}
}
p.readChar()
default:
if !keyParsed {
if err := key.WriteByte(p.ch); err != nil {
return "", "", err
}
} else {
if err := val.WriteByte(p.ch); err != nil {
return "", "", err
}
}
p.readChar()
}
}
}
func (p *parser) parse() (map[string]string, error) {
params := make(map[string]string)
for {
key, val, err := p.nextParam()
if err == io.EOF {
return params, nil
} else if err != nil {
return nil, err
}
params[key] = val
}
}