-
Notifications
You must be signed in to change notification settings - Fork 0
/
codec.go
87 lines (77 loc) · 1.71 KB
/
codec.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
86
87
//
// Copyright (C) 2020 Dmitry Kolesnikov
//
// This file may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
// https://github.com/fogfish/curie
//
package curie
import (
"net/url"
"unicode"
"unicode/utf8"
)
// Decode converts URIs to IRIs as defined by RFC 3987
// https://www.rfc-editor.org/rfc/rfc3987#section-3.2
func Decode(uri string) string {
return string(decode([]byte(uri)))
}
func decode(uri []byte) []byte {
var iri []byte
decodeLastRune := func() {
r, size := utf8.DecodeLastRune(iri)
if !unicode.IsGraphic(r) && r != utf8.RuneError {
esc := url.PathEscape(string(r))
iri = append(iri[:len(iri)-size], []byte(esc)...)
}
}
for i := 0; i < len(uri); {
switch {
case uri[i] == '%' && i+2 <= len(uri) && ishex(uri[i+1]) && ishex(uri[i+2]):
b := unhex(uri[i+1])<<4 | unhex(uri[i+2])
if checkReserved(b) {
iri = append(iri, uri[i:i+3]...)
} else {
iri = append(iri, b)
decodeLastRune()
}
i += 3
default:
iri = append(iri, uri[i])
decodeLastRune()
i++
}
}
return iri
}
func checkReserved(b byte) bool {
return b == ':' ||
b == '/' || b == '?' || b == '#' ||
b == '[' || b == ']' || b == '@' ||
b == '!' || b == '$' || b == '&' ||
b == '\'' || b == '(' || b == ')' ||
b == '*' || b == '+' || b == ',' ||
b == ';' || b == '='
}
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
}