-
Notifications
You must be signed in to change notification settings - Fork 0
/
delim.go
80 lines (61 loc) · 1.17 KB
/
delim.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
package beard
import (
"bytes"
)
type matchLevel int
const (
_ matchLevel = iota
noMatch
paMatch
exMatch
)
type Delim interface {
Match([]byte) ([]byte, matchLevel)
// Value should return the actual Delimeter value in []byte, eg {{ or }}
Value() []byte
}
var (
ldelim = &Ldelim{Delim: []byte("{{")}
rdelim = &Rdelim{Delim: []byte("}}")}
)
type Ldelim struct {
Delim []byte
}
var _ Delim = &Ldelim{}
func (d *Ldelim) Match(b []byte) ([]byte, matchLevel) {
return matchDelim(b, d.Delim)
}
func (d *Ldelim) Value() []byte {
return d.Delim
}
type Rdelim struct {
Delim []byte
}
var _ Delim = &Rdelim{}
func (d *Rdelim) Match(b []byte) ([]byte, matchLevel) {
return matchDelim(b, d.Delim)
}
func (d *Rdelim) Value() []byte {
return d.Delim
}
func matchDelim(b, del []byte) ([]byte, matchLevel) {
lenb := len(b)
lendel := len(del)
// find the delim in full
if i := bytes.Index(b, del); i != -1 {
return b[:i+lendel], exMatch
}
// find a partial match
z := lendel - 1
for ; z > 0; z-- {
i := bytes.Index(b, del[:z])
if i == -1 {
continue
}
// match must be at the end of the byte array
if i+z == lenb {
return b, paMatch
}
}
return b, noMatch
}