Projekt

Obecné

Profil

Stáhnout (2.05 KB) Statistiky
| Větev: | Revize:
1
"use strict";
2

    
3
Object.defineProperty(exports, "__esModule", {
4
  value: true
5
});
6
exports.parseString = parseString;
7
// string literal characters cannot contain control codes
8
var CONTROL_CODES = [0, // null
9
7, // bell
10
8, // backspace
11
9, // horizontal
12
10, // line feed
13
11, // vertical tab
14
12, // form feed
15
13, // carriage return
16
26, // Control-Z
17
27, // escape
18
127 // delete
19
]; // escaped sequences can either be a two character hex value, or one of the
20
// following single character codes
21

    
22
function decodeControlCharacter(char) {
23
  switch (char) {
24
    case "t":
25
      return 0x09;
26

    
27
    case "n":
28
      return 0x0a;
29

    
30
    case "r":
31
      return 0x0d;
32

    
33
    case '"':
34
      return 0x22;
35

    
36
    case "":
37
      return 0x27;
38

    
39
    case "\\":
40
      return 0x5c;
41
  }
42

    
43
  return -1;
44
}
45

    
46
var ESCAPE_CHAR = 92; // backslash
47

    
48
var QUOTE_CHAR = 34; // backslash
49
// parse string as per the spec:
50
// https://webassembly.github.io/spec/core/multipage/text/values.html#text-string
51

    
52
function parseString(value) {
53
  var byteArray = [];
54
  var index = 0;
55

    
56
  while (index < value.length) {
57
    var charCode = value.charCodeAt(index);
58

    
59
    if (CONTROL_CODES.indexOf(charCode) !== -1) {
60
      throw new Error("ASCII control characters are not permitted within string literals");
61
    }
62

    
63
    if (charCode === QUOTE_CHAR) {
64
      throw new Error("quotes are not permitted within string literals");
65
    }
66

    
67
    if (charCode === ESCAPE_CHAR) {
68
      var firstChar = value.substr(index + 1, 1);
69
      var decodedControlChar = decodeControlCharacter(firstChar);
70

    
71
      if (decodedControlChar !== -1) {
72
        // single character escaped values, e.g. \r
73
        byteArray.push(decodedControlChar);
74
        index += 2;
75
      } else {
76
        // hex escaped values, e.g. \2a
77
        var hexValue = value.substr(index + 1, 2);
78

    
79
        if (!/^[0-9A-F]{2}$/i.test(hexValue)) {
80
          throw new Error("invalid character encoding");
81
        }
82

    
83
        byteArray.push(parseInt(hexValue, 16));
84
        index += 3;
85
      }
86
    } else {
87
      // ASCII encoded values
88
      byteArray.push(charCode);
89
      index++;
90
    }
91
  }
92

    
93
  return byteArray;
94
}
(4-4/5)