This repository has been archived by the owner on Dec 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcharclass.go
77 lines (69 loc) · 1.74 KB
/
charclass.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
package httpheader
import "strings"
// classify scans s to determine how it can be represented on the wire.
// tokenOK means s is a simple RFC 7230 token.
// quotedOK means s consists entirely of characters that can be represented in
// an RFC 7230 quoted-string, with the exception of bytes 0x80..0xFF (obs-text),
// which are poorly supported (at best, they are interpreted as ISO-8859-1, which
// is unlikely to be useful).
// quotedSafe means that, in addition to quotedOK, s doesn't contain delimiters
// that are known to confuse naive parsers (which in practice is most parsers).
func classify(s string) (tokenOK, quotedSafe, quotedOK bool) {
if s == "" {
return false, true, true
}
tokenOK, quotedSafe, quotedOK = true, true, true
for i := 0; i < len(s); i++ {
switch byteClass[s[i]] {
case cUnsafe:
return false, false, false
case cQuotedOK:
quotedSafe, tokenOK = false, false
case cQuotedSafe:
tokenOK = false
case cTokenOK:
}
}
return
}
func isToken(s string) bool {
for i := 0; i < len(s); i++ {
if byteClass[s[i]] > cTokenOK {
return false
}
}
return s != ""
}
func isLower(s string) bool {
for i := 0; i < len(s); i++ {
if 'A' <= s[i] && s[i] <= 'Z' {
return false
}
}
return true
}
type charClass int
const (
cTokenOK charClass = iota
cQuotedSafe
cQuotedOK
cUnsafe
)
var byteClass [256]charClass
func init() {
for i := 0; i < 0xFF; i++ {
b := byte(i)
switch {
case b < 0x20 || b > 0x7E:
byteClass[b] = cUnsafe
case (b >= '0' && b <= '9') ||
(b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') ||
strings.ContainsRune("!#$%&'*+-.^_`|~", rune(b)):
byteClass[b] = cTokenOK
case b == ',' || b == ';' || b == '"':
byteClass[b] = cQuotedOK
default:
byteClass[b] = cQuotedSafe
}
}
}