-
Notifications
You must be signed in to change notification settings - Fork 1
/
decode.go
85 lines (69 loc) · 1.47 KB
/
decode.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
81
82
83
84
85
package utils
import "errors"
func UnHex(c byte) byte {
switch {
case '0' <= c && c <= '9':
return c - '0'
case 'a' <= c && c <= 'f':
return c - 'a' + 10
case 'A' <= c && c <= 'F':
return c - 'A' + 10
}
return 0
}
func IsHex(c byte) bool {
switch {
case '0' <= c && c <= '9':
return true
case 'a' <= c && c <= 'f':
return true
case 'A' <= c && c <= 'F':
return true
}
return false
}
var ErrEscape = errors.New("invalid URL escape")
func DecodeQueryUnsafeString(src []byte) (string, error) {
n, err := DecodeQuery(src, src)
if err != nil {
return "", err
}
return UnsafeString(src[:n]), nil
}
func DecodeQueryUnsafe(src []byte) ([]byte, error) {
n, err := DecodeQuery(src, src)
if err != nil {
return nil, err
}
return src[:n], nil
}
func DecodeQuery(dst []byte, src []byte) (int, error) {
writer := 0
ptr := src
writer = 0
for reader := 0; reader < len(ptr); reader++ {
switch ptr[reader] {
case '%':
// DO WHILE
if reader+2 >= len(ptr) || !IsHex(ptr[reader+1]) || !IsHex(ptr[reader+2]) {
return 0, ErrEscape
}
data := UnHex(ptr[reader+1])<<4 | UnHex(ptr[reader+2])
reader += 2
for data == '%' {
if reader+2 >= len(ptr) || !IsHex(ptr[reader+1]) || !IsHex(ptr[reader+2]) {
return 0, ErrEscape
}
data = UnHex(ptr[reader+1])<<4 | UnHex(ptr[reader+2])
reader += 2
}
dst[writer] = data
case '+':
dst[writer] = ' '
default:
dst[writer] = ptr[reader]
}
writer++
}
return writer, nil
}