-
Notifications
You must be signed in to change notification settings - Fork 16
/
encodeProtocol.js
57 lines (42 loc) · 1.2 KB
/
encodeProtocol.js
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
const valid_chars = "!#$%&'*+-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz|~";
const reserved_chars = "%";
export function validProtocol(protocol){
protocol = protocol.toString();
for(let i = 0; i < protocol.length; i++){
const char = protocol[i];
if(!valid_chars.includes(char)){
return false;
}
}
return true;
}
export function encodeProtocol(protocol){
protocol = protocol.toString();
let result = '';
for(let i = 0; i < protocol.length; i++){
const char = protocol[i];
if(valid_chars.includes(char) && !reserved_chars.includes(char)){
result += char;
}else{
const code = char.charCodeAt();
result += '%' + code.toString(16).padStart(2, 0);
}
}
return result;
}
export function decodeProtocol(protocol){
if(typeof protocol != 'string')throw new TypeError('protocol must be a string');
let result = '';
for(let i = 0; i < protocol.length; i++){
const char = protocol[i];
if(char == '%'){
const code = parseInt(protocol.slice(i + 1, i + 3), 16);
const decoded = String.fromCharCode(code);
result += decoded;
i += 2;
}else{
result += char;
}
}
return result;
}