forked from JobLeonard/lz-string
-
Notifications
You must be signed in to change notification settings - Fork 2
/
lz-string-unsafe.js
394 lines (347 loc) · 12.4 KB
/
lz-string-unsafe.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
var LZStringUnsafe = (function () {
// private property
var i = 0,
reverseDict = {},
fromCharCode = String.fromCharCode,
streamData,
streamDataVal,
streamDataPosition,
streamBitsPerChar,
streamGetCharFromInt,
base = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+",
Base64CharArray = (base + "/=").split(''),
UriSafeCharArray = (base + "-$").split('');
while (i < 65) {
if (i > 62) {
reverseDict[UriSafeCharArray[i].charCodeAt(0)] = i;
}
reverseDict[Base64CharArray[i].charCodeAt(0)] = i++;
}
function streamBits(value, numBitsMask) {
for (var i = 0; numBitsMask >>= 1; i++) {
// shifting has precedence over bitmasking
streamDataVal = value >> i & 1 | streamDataVal << 1;
if (++streamDataPosition === streamBitsPerChar) {
streamDataPosition = 0;
streamData.push(streamGetCharFromInt(streamDataVal));
streamDataVal = 0;
}
}
}
function getCharFromBase64(a) { return Base64CharArray[a]; }
function getCharFromURISafe(a) { return UriSafeCharArray[a]; }
function getCharFromUTF16(a) { return fromCharCode(a + 32); }
function _compress(uncompressed, bitsPerChar, getCharFromInt) {
// data - empty stream
streamData = [];
if (uncompressed != null) {
// davaVal
streamDataVal = 0;
// dataPosition
streamDataPosition = 0;
streamBitsPerChar = bitsPerChar;
streamGetCharFromInt = getCharFromInt;
var j = 0, k = 0, value = 0,
node = [3], // first node will always be initialised like this.
// we should never output the root anyway,
// so we initiate with terminating token
// Also, dictionary[1] will be overwritten
// by the first charCode
dictionary = [2, 2, node],
freshNode = true,
c = 0,
dictSize = 3,
numBitsMask = 0b100;
if (uncompressed.length) {
// If there is a string, the first charCode is guaranteed to
// be new, so we write it to output stream, and add it to the
// dictionary. For the same reason we can initialize freshNode
// as true, and new_node, node and dictSize as if
// it was already added to the dictionary (see above).
c = uncompressed.charCodeAt(0);
// == Write first charCode token to output ==
// 8 or 16 bit?
value = c < 256 ? 0 : 1
// insert "new 8/16 bit charCode" token
// into bitstream (value 1)
streamBits(value, numBitsMask);
streamBits(c, value ? 0b10000000000000000 : 0b100000000);
// Add charCode to the dictionary.
dictionary[1] = c;
nextchar:
for (j = 1; j < uncompressed.length; j++) {
c = uncompressed.charCodeAt(j);
// does the new charCode match an existing prefix?
for (k = 1; k < node.length; k += 2) {
if (node[k] == c) {
node = node[k + 1];
continue nextchar;
}
}
// we only end up here if there is no matching char
// Prefix+charCode does not exist in trie yet.
// We write the prefix to the bitstream, and add
// the new charCode to the dictionary if it's new
// Then we set `node` to the root node matching
// the charCode.
if (freshNode) {
// Prefix is a freshly added character token,
// which was already written to the bitstream
freshNode = false;
} else {
// write out the current prefix token
streamBits(node[0], numBitsMask);
}
// Is the new charCode a new character
// that needs to be stored at the root?
k = 1;
while (dictionary[k] != c && k < dictionary.length) {
k += 2;
}
if (k == dictionary.length) {
// increase token bitlength if necessary
if (++dictSize >= numBitsMask) {
numBitsMask <<= 1;
}
// insert "new 8/16 bit charCode" token,
// see comments above for explanation
value = c < 256 ? 0 : 1
streamBits(value, numBitsMask);
streamBits(c, value ? 0b10000000000000000 : 0b100000000);
dictionary.push(c);
dictionary.push([dictSize]);
// Note of that we already wrote
// the charCode token to the bitstream
freshNode = true;
}
// add node representing prefix + new charCode to trie
node.push(c);
node.push([++dictSize]);
// increase token bitlength if necessary
if (dictSize >= numBitsMask) {
numBitsMask <<= 1;
}
// set node to first charCode of new prefix
// k is guaranteed to be at the current charCode,
// since we either broke out of the while loop
// when it matched, or just added the new charCode
node = dictionary[k + 1];
}
// === Write last prefix to output ===
if (freshNode) {
// character token already written to output
freshNode = false;
} else {
// write out the prefix token
streamBits(node[0], numBitsMask);
}
// Is c a new character?
k = 1;
while (dictionary[k] != c && k < dictionary.length) {
k += 2;
}
if (k == dictionary.length) {
// increase token bitlength if necessary
if (++dictSize >= numBitsMask) {
numBitsMask <<= 1;
}
// insert "new 8/16 bit charCode" token,
// see comments above for explanation
value = c < 256 ? 0 : 1
streamBits(value, numBitsMask);
streamBits(c, value ? 0b10000000000000000 : 0b100000000);
}
// increase token bitlength if necessary
if (++dictSize >= numBitsMask) {
numBitsMask <<= 1;
}
}
// Mark the end of the stream
streamBits(2, numBitsMask);
// Flush the last char
streamDataVal <<= streamBitsPerChar - streamDataPosition;
streamData.push(streamGetCharFromInt(streamDataVal));
}
return streamData;
}
function _decompress(length, resetBits, getNextValue) {
var dictionary = [0, 1, 2],
enlargeIn = 4,
dictSize = 4,
numBits = 3,
entry = "",
result = [],
w = "",
bits = 0,
maxpower = 2,
power = 0,
c = "",
data_val = getNextValue(0),
data_position = resetBits,
data_index = 1;
// Get first token, guaranteed to be either
// a new character token (8 or 16 bits)
// or end of stream token.
while (power != maxpower) {
// shifting has precedence over bitmasking
bits += (data_val >> --data_position & 1) << power++;
if (data_position == 0) {
data_position = resetBits;
data_val = getNextValue(data_index++);
}
}
// if end of stream token, return empty string
if (bits == 2) {
return "";
}
// else, get character
maxpower = bits * 8 + 8;
bits = power = 0;
while (power != maxpower) {
// shifting has precedence over bitmasking
bits += (data_val >> --data_position & 1) << power++;
if (data_position == 0) {
data_position = resetBits;
data_val = getNextValue(data_index++);
}
}
c = fromCharCode(bits);
dictionary[3] = c;
w = c;
result.push(c);
// read rest of string
while (data_index <= length) {
// read out next token
maxpower = numBits;
bits = power = 0;
while (power != maxpower) {
// shifting has precedence over bitmasking
bits += (data_val >> --data_position & 1) << power++;
if (data_position == 0) {
data_position = resetBits;
data_val = getNextValue(data_index++);
}
}
// 0 or 1 implies new character token
if (bits < 2) {
maxpower = (8 + 8 * bits);
bits = power = 0;
while (power != maxpower) {
// shifting has precedence over bitmasking
bits += (data_val >> --data_position & 1) << power++;
if (data_position == 0) {
data_position = resetBits;
data_val = getNextValue(data_index++);
}
}
dictionary[dictSize] = fromCharCode(bits);
bits = dictSize++;
if (--enlargeIn == 0) {
enlargeIn = 1 << numBits++;
}
} else if (bits == 2) {
// end of stream token
return result.join('');
}
if (bits > dictionary.length) {
return null;
}
entry = bits < dictionary.length ? dictionary[bits] : w + w.charAt(0);
result.push(entry);
// Add w+entry[0] to the dictionary.
dictionary[dictSize++] = w + entry.charAt(0);
w = entry;
if (--enlargeIn == 0) {
enlargeIn = 1 << numBits++;
}
}
return "";
}
function _compressToArray(uncompressed) {
return _compress(uncompressed, 16, fromCharCode);
}
function _decompressFromArray(compressed) {
if (compressed == null) return "";
if (compressed.length == 0) return null;
return _decompress(compressed.length, 16, function (index) { return compressed[index].charCodeAt(0); });
}
return {
compressToBase64: function (input) {
if (input == null) return "";
var res = _compress(input, 6, getCharFromBase64),
i = res.length % 4; // To produce valid Base64
while (i--) {
res.push("=");
}
return res.join('');
},
decompressFromBase64: function (input) {
if (input == null) return "";
if (input == "") return null;
return _decompress(input.length, 6, function (index) { return reverseDict[input.charCodeAt(index)]; });
},
compressToUTF16: function (input) {
if (input == null) return "";
var compressed = _compress(input, 15, getCharFromUTF16);
compressed.push(" ");
return compressed.join('');
},
decompressFromUTF16: function (compressed) {
if (compressed == null) return "";
if (compressed == "") return null;
return _decompress(compressed.length, 15, function (index) { return compressed.charCodeAt(index) - 32; });
},
//compress into uint8array (UCS-2 big endian format)
compressToUint8Array: function (uncompressed) {
var compressed = _compressToArray(uncompressed);
var buf = new Uint8Array(compressed.length * 2); // 2 bytes per character
for (var i = 0, TotalLen = compressed.length; i < TotalLen; i++) {
var current_value = compressed[i].charCodeAt(0);
buf[i * 2] = current_value >>> 8;
buf[i * 2 + 1] = current_value & 0xFF;
}
return buf;
},
//decompress from uint8array (UCS-2 big endian format)
decompressFromUint8Array: function (compressed) {
if (compressed === null || compressed === undefined) {
return _decompressFromArray(compressed);
} else if (compressed.length == 0) {
return null;
}
return _decompress(compressed.length, 8, function (index) { return compressed[index]; });
},
//compress into a string that is already URI encoded
compressToEncodedURIComponent: function (input) {
if (input == null) return "";
return _compress(input, 6, getCharFromURISafe).join('');
},
//decompress from an output of compressToEncodedURIComponent
decompressFromEncodedURIComponent: function (input) {
if (input == null) return "";
if (input == "") return null;
input = input.replace(/ /g, "+");
return _decompress(input.length, 6, function (index) { return reverseDict[input.charCodeAt(index)]; });
},
compress: function (uncompressed) {
return _compressToArray(uncompressed).join('');
},
compressToArray: _compressToArray,
decompress: function (compressed) {
if (compressed == null) return "";
if (compressed == "") return null;
return _decompress(compressed.length, 16, function (index) { return compressed.charCodeAt(index); });
},
decompressFromArray: _decompressFromArray
};
})();
if (typeof define === 'function' && define.amd) {
define(function () { return LZStringUnsafe; });
} else if (typeof module !== 'undefined' && module != null) {
module.exports = LZStringUnsafe
} else if (typeof angular !== 'undefined' && angular != null) {
angular.module('LZStringUnsafe', [])
.factory('LZStringUnsafe', function () {
return LZStringUnsafe;
});
}