-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
single.go
58 lines (53 loc) · 1.05 KB
/
single.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
package single
import (
"errors"
)
const (
quote = '\''
escape = '\\'
)
var ErrSyntax = errors.New("invalid syntax")
// Quote returns a single-quoted Go string literal representing s. But, nothing else escapes.
func Quote(s string) string {
out := []rune{quote}
for _, r := range s {
switch r {
case quote:
out = append(out, escape, r)
default:
out = append(out, r)
}
}
out = append(out, quote)
return string(out)
}
// Unquote interprets s as a single-quoted Go string literal, returning the string value that s quotes.
func Unquote(s string) (string, error) {
if len(s) < 2 {
return "", ErrSyntax
}
if s[0] != quote || s[len(s)-1] != quote {
return "", ErrSyntax
}
out := []rune{}
escaped := false
for _, r := range s[1 : len(s)-1] {
switch r {
case escape:
escaped = !escaped
if !escaped {
out = append(out, escape, escape)
}
case quote:
if !escaped {
return "", ErrSyntax
}
out = append(out, r)
escaped = false
default:
out = append(out, r)
escaped = false
}
}
return string(out), nil
}