-
Notifications
You must be signed in to change notification settings - Fork 6
/
escaper.go
48 lines (41 loc) · 894 Bytes
/
escaper.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
package ddprom
import "strings"
func newEscaper(escapedChars []escapedChar) escaper {
return escaper{
escapedChars: escapedChars,
}
}
type escapedChar struct {
char byte
escaped string
}
type escaper struct {
escapedChars []escapedChar
}
func (em *escaper) escape(str string) string {
for _, e := range em.escapedChars {
str = strings.ReplaceAll(str, string(e.char), e.escaped)
}
return str
}
func (em *escaper) unescape(str string) string {
sb := strings.Builder{}
for i := 0; i < len(str); {
if char, l, ok := em.escapedPrefix(str[i:]); ok {
sb.WriteByte(char)
i += l
} else {
sb.WriteByte(str[i])
i++
}
}
return sb.String()
}
func (em *escaper) escapedPrefix(str string) (char byte, l int, ok bool) {
for _, e := range em.escapedChars {
if strings.HasPrefix(str, e.escaped) {
return e.char, len(e.escaped), true
}
}
return 0, 0, false
}