UNPKG

1.99 kBJavaScriptView Raw
1// string literal characters cannot contain control codes
2var CONTROL_CODES = [0, // null
37, // bell
48, // backspace
59, // horizontal
610, // line feed
711, // vertical tab
812, // form feed
913, // carriage return
1026, // Control-Z
1127, // escape
12127 // delete
13]; // escaped sequences can either be a two character hex value, or one of the
14// following single character codes
15
16function 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
40var ESCAPE_CHAR = 92; // backslash
41
42var 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
46export 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}
\No newline at end of file