Debian Codegraph @

tests/inputs/TypeScript.ts

raw
1 //
2 // Copyright (c) Microsoft Corporation. All rights reserved.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15
16 module TypeScript {
17 class Base64Format {
18 static encodedValues = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
19 static encode(inValue: number) {
20 if (inValue < 64) {
21 return Base64Format.encodedValues.charAt(inValue);
22 }
23 throw TypeError(inValue + ": not a 64 based value");
24 }
25
26 static decodeChar(inChar: string) {
27 if (inChar.length === 1) {
28 return Base64Format.encodedValues.indexOf(inChar);
29 } else {
30 throw TypeError('"' + inChar + '" must have length 1');
31 }
32 }
33 }
34
35 export class Base64VLQFormat {
36 static encode(inValue: number) {
37 // Add a new least significant bit that has the sign of the value.
38 // if negative number the least significant bit that gets added to the number has value 1
39 // else least significant bit value that gets added is 0
40 // eg. -1 changes to binary : 01 [1] => 3
41 // +1 changes to binary : 01 [0] => 2
42 if (inValue < 0) {
43 inValue = ((-inValue) << 1) + 1;
44 }
45 else {
46 inValue = inValue << 1;
47 }
48
49 // Encode 5 bits at a time starting from least significant bits
50 var encodedStr = "";
51 do {
52 var currentDigit = inValue & 31; // 11111
53 inValue = inValue >> 5;
54 if (inValue > 0) {
55 // There are still more digits to decode, set the msb (6th bit)
56 currentDigit = currentDigit | 32;
57 }
58 encodedStr = encodedStr + Base64Format.encode(currentDigit);
59 } while (inValue > 0);
60
61 return encodedStr;
62 }
63
64 static decode(inString: string) {
65 var result = 0;
66 var negative = false;
67
68 var shift = 0;
69 for (var i = 0; i < inString.length; i++) {
70 var byte = Base64Format.decodeChar(inString[i]);
71 if (i === 0) {
72 // Sign bit appears in the LSBit of the first value
73 if ((byte & 1) === 1) {
74 negative = true;
75 }
76 result = (byte >> 1) & 15; // 1111x
77 } else {
78 result = result | ((byte & 31) << shift); // 11111
79 }
80
81 shift += (i === 0) ? 4 : 5;
82
83 if ((byte & 32) === 32) {
84 // Continue
85 } else {
86 return { value: negative ? -(result) : result, rest: inString.substr(i + 1) };
87 }
88 }
89
90 throw new Error(getDiagnosticMessage(DiagnosticCode.Base64_value_0_finished_with_a_continuation_bit, [inString]));
91 }
92 }
93 }
94