-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
91 lines (84 loc) · 2.08 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
package fastparse
import (
"errors"
"io"
)
// Parser is used to define an argument parser from the ParserManager. Note this (and functions on provided arguments) are not thread safe.
type Parser struct {
initProperly bool
pad *scratchpad
r io.ReadSeeker
argId int
}
// Done should be called when you are done with a scratchpad.
func (p *Parser) Done() {
if !p.initProperly {
panic("Parser objects should be created from a ParserManager")
}
p.pad.readd()
}
// Remainder is used to get the remainder of the reader as a string, ignoring arguments.
func (p *Parser) Remainder() (string, error) {
if !p.initProperly {
return "", errors.New("parser objects should be created from a ParserManager")
}
defer p.pad.reset()
n, err := p.r.Read(p.pad.slice)
if err != nil {
return "", err
}
p.pad.len = n
return p.pad.String(), nil
}
// Gets the raw argument information which we can use to create the Argument struct.
func (p *Parser) getRawArgInfo() (string, int) {
defer p.pad.reset()
raw := 0
first := true
quote := false
ob := make([]byte, 1)
for {
// Read a char.
_, err := p.r.Read(ob)
if err != nil {
// Return the current argument and raw length.
return p.pad.String(), raw
}
raw++
if ob[0] == '"' {
if first {
// Handle the start of a quote.
quote = true
} else if quote {
// If this is within the quote, return the arg.
return p.pad.String(), raw
}
} else if ob[0] == ' ' {
// If this is the beginning, continue. If this isn't a quote, return. If it is, add to it.
if first {
continue
} else if quote {
_ = p.pad.AddByte(' ')
} else {
return p.pad.String(), raw
}
} else {
// Just add to the argument.
_ = p.pad.AddByte(ob[0])
}
// Set first to false.
first = false
}
}
// GetNextArg is used to get the next argument. If there are no additional arguments, the pointer will be nil.
func (p *Parser) GetNextArg() *Argument {
if !p.initProperly {
return nil
}
s, rawLen := p.getRawArgInfo()
if rawLen == 0 {
return nil
}
p.argId++
return &Argument{Text: s, rawLen: rawLen, argId: p.argId, p: p}
}