-
Notifications
You must be signed in to change notification settings - Fork 3
/
until.go
68 lines (64 loc) · 1.24 KB
/
until.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
package parse
type untilParser[T, D any] struct {
Parser Parser[T]
Delimiter Parser[D]
AllowEOF bool
}
func (p untilParser[T, D]) Parse(in *Input) (match []T, ok bool, err error) {
start := in.Index()
if _, ok = in.Peek(1); !ok && p.AllowEOF {
ok = true
return
}
var m T
m, ok, err = p.Parser.Parse(in)
if err != nil {
return
}
if !ok {
return
}
match = append(match, m)
for {
beforeDelimiter := in.Index()
_, ok, err = p.Delimiter.Parse(in)
if err != nil {
in.Seek(start)
return
}
if ok {
in.Seek(beforeDelimiter)
return
}
if _, ok = in.Peek(1); !ok && p.AllowEOF {
ok = true
return
}
var m T
m, ok, err = p.Parser.Parse(in)
if err != nil {
in.Seek(start)
return
}
if !ok {
in.Seek(start)
return
}
match = append(match, m)
}
}
// Until matches until the delimiter is reached.
func Until[T, D any](parser Parser[T], delimiter Parser[D]) Parser[[]T] {
return untilParser[T, D]{
Parser: parser,
Delimiter: delimiter,
}
}
// UntilEOF matches until the delimiter or the end of the file is reached.
func UntilEOF[T, D any](parser Parser[T], delimiter Parser[D]) Parser[[]T] {
return untilParser[T, D]{
Parser: parser,
Delimiter: delimiter,
AllowEOF: true,
}
}