1
|
// string literal characters cannot contain control codes
|
2
|
var CONTROL_CODES = [0, // null
|
3
|
7, // bell
|
4
|
8, // backspace
|
5
|
9, // horizontal
|
6
|
10, // line feed
|
7
|
11, // vertical tab
|
8
|
12, // form feed
|
9
|
13, // carriage return
|
10
|
26, // Control-Z
|
11
|
27, // escape
|
12
|
127 // delete
|
13
|
]; // escaped sequences can either be a two character hex value, or one of the
|
14
|
// following single character codes
|
15
|
|
16
|
function decodeControlCharacter(char) {
|
17
|
switch (char) {
|
18
|
case "t":
|
19
|
return 0x09;
|
20
|
|
21
|
case "n":
|
22
|
return 0x0a;
|
23
|
|
24
|
case "r":
|
25
|
return 0x0d;
|
26
|
|
27
|
case '"':
|
28
|
return 0x22;
|
29
|
|
30
|
case "′":
|
31
|
return 0x27;
|
32
|
|
33
|
case "\\":
|
34
|
return 0x5c;
|
35
|
}
|
36
|
|
37
|
return -1;
|
38
|
}
|
39
|
|
40
|
var ESCAPE_CHAR = 92; // backslash
|
41
|
|
42
|
var QUOTE_CHAR = 34; // backslash
|
43
|
// parse string as per the spec:
|
44
|
// https://webassembly.github.io/spec/core/multipage/text/values.html#text-string
|
45
|
|
46
|
export function parseString(value) {
|
47
|
var byteArray = [];
|
48
|
var index = 0;
|
49
|
|
50
|
while (index < value.length) {
|
51
|
var charCode = value.charCodeAt(index);
|
52
|
|
53
|
if (CONTROL_CODES.indexOf(charCode) !== -1) {
|
54
|
throw new Error("ASCII control characters are not permitted within string literals");
|
55
|
}
|
56
|
|
57
|
if (charCode === QUOTE_CHAR) {
|
58
|
throw new Error("quotes are not permitted within string literals");
|
59
|
}
|
60
|
|
61
|
if (charCode === ESCAPE_CHAR) {
|
62
|
var firstChar = value.substr(index + 1, 1);
|
63
|
var decodedControlChar = decodeControlCharacter(firstChar);
|
64
|
|
65
|
if (decodedControlChar !== -1) {
|
66
|
// single character escaped values, e.g. \r
|
67
|
byteArray.push(decodedControlChar);
|
68
|
index += 2;
|
69
|
} else {
|
70
|
// hex escaped values, e.g. \2a
|
71
|
var hexValue = value.substr(index + 1, 2);
|
72
|
|
73
|
if (!/^[0-9A-F]{2}$/i.test(hexValue)) {
|
74
|
throw new Error("invalid character encoding");
|
75
|
}
|
76
|
|
77
|
byteArray.push(parseInt(hexValue, 16));
|
78
|
index += 3;
|
79
|
}
|
80
|
} else {
|
81
|
// ASCII encoded values
|
82
|
byteArray.push(charCode);
|
83
|
index++;
|
84
|
}
|
85
|
}
|
86
|
|
87
|
return byteArray;
|
88
|
}
|