-
Notifications
You must be signed in to change notification settings - Fork 0
/
contains.go
65 lines (58 loc) · 1.28 KB
/
contains.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
package triegun
import (
"io"
"text/template"
)
func (p *Plant) genContains(w io.Writer, st *state) error {
allowSubmatch(st)
states := allStatesUpToGoal(st)
return tmplContains.Execute(w, map[string]interface{}{
"TagName": p.TagName,
"Start": states[0],
"States": states[1:],
})
}
var tmplContains = template.Must(template.New("contains").Parse(`
func Contains{{ .TagName }}String(str string) bool {
return Contains{{ .TagName}}(*(*[]byte)(unsafe.Pointer(&str)))
}
func Contains{{ .TagName }}(bytes []byte) bool {
defer func(){
recover() // Must be "index out of range" error for string.
// Ignore and return false.
}()
i := 0
{{ $start := .Start }}
STATE_{{ $start.Id }}:
{{ if .IsGoal }}
return true
{{ else }}
switch bytes[i] {
{{ range $key, $next := $start.Nexts }}
case {{ printf "%q" $key }}:
i++
goto STATE_{{ $next.Id }}
{{ end }}
default:
i++
goto STATE_{{ $start.Id }}
}
{{ end }}
{{ range .States }}
STATE_{{ .Id }}:
{{ if .IsGoal }}
return true
{{ else }}
switch bytes[i] {
{{ range $key, $next := .Nexts }}
case {{ printf "%q" $key }}:
i++
goto STATE_{{ $next.Id }}
{{ end }}
default:
goto STATE_{{ $start.Id }}
}
{{ end }}
{{ end }}
}
`))