/
util.js
1518 lines (1409 loc) · 36.6 KB
/
util.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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Utility functions for web applications.
*
* @author Dave Longley
*
* Copyright (c) 2010-2012 Digital Bazaar, Inc.
*/
(function() {
// define forge
if(typeof(window) !== 'undefined') {
var forge = window.forge = window.forge || {};
forge.util = {};
}
// define node.js module
else if(typeof(module) !== 'undefined' && module.exports) {
var forge = {};
module.exports = forge.util = {};
}
/* Utilities API */
var util = forge.util;
/**
* Constructor for a byte buffer.
*
* @param b the bytes to wrap (as a UTF-8 string) (optional).
*/
util.ByteBuffer = function(b) {
// the data in this buffer
this.data = b || '';
// the pointer for reading from this buffer
this.read = 0;
};
/**
* Gets the number of bytes in this buffer.
*
* @return the number of bytes in this buffer.
*/
util.ByteBuffer.prototype.length = function() {
return this.data.length - this.read;
};
/**
* Gets whether or not this buffer is empty.
*
* @return true if this buffer is empty, false if not.
*/
util.ByteBuffer.prototype.isEmpty = function() {
return (this.data.length - this.read) === 0;
};
/**
* Puts a byte in this buffer.
*
* @param b the byte to put.
*/
util.ByteBuffer.prototype.putByte = function(b) {
this.data += String.fromCharCode(b);
};
/**
* Puts a byte in this buffer N times.
*
* @param b the byte to put.
* @param n the number of bytes of value b to put.
*/
util.ByteBuffer.prototype.fillWithByte = function(b, n) {
b = String.fromCharCode(b);
var d = this.data;
while(n > 0) {
if(n & 1) {
d += b;
}
n >>>= 1;
if(n > 0) {
b += b;
}
}
this.data = d;
};
/**
* Puts bytes in this buffer.
*
* @param bytes the bytes (as a UTF-8 encoded string) to put.
*/
util.ByteBuffer.prototype.putBytes = function(bytes) {
this.data += bytes;
};
/**
* Puts a UTF-16 encoded string into this buffer.
*
* @param str the string to put.
*/
util.ByteBuffer.prototype.putString = function(str) {
this.data += util.encodeUtf8(str);
};
/**
* Puts a 16-bit integer in this buffer in big-endian order.
*
* @param i the 16-bit integer.
*/
util.ByteBuffer.prototype.putInt16 = function(i) {
this.data +=
String.fromCharCode(i >> 8 & 0xFF) +
String.fromCharCode(i & 0xFF);
};
/**
* Puts a 24-bit integer in this buffer in big-endian order.
*
* @param i the 24-bit integer.
*/
util.ByteBuffer.prototype.putInt24 = function(i) {
this.data +=
String.fromCharCode(i >> 16 & 0xFF) +
String.fromCharCode(i >> 8 & 0xFF) +
String.fromCharCode(i & 0xFF);
};
/**
* Puts a 32-bit integer in this buffer in big-endian order.
*
* @param i the 32-bit integer.
*/
util.ByteBuffer.prototype.putInt32 = function(i) {
this.data +=
String.fromCharCode(i >> 24 & 0xFF) +
String.fromCharCode(i >> 16 & 0xFF) +
String.fromCharCode(i >> 8 & 0xFF) +
String.fromCharCode(i & 0xFF);
};
/**
* Puts a 16-bit integer in this buffer in little-endian order.
*
* @param i the 16-bit integer.
*/
util.ByteBuffer.prototype.putInt16Le = function(i) {
this.data +=
String.fromCharCode(i & 0xFF) +
String.fromCharCode(i >> 8 & 0xFF);
};
/**
* Puts a 24-bit integer in this buffer in little-endian order.
*
* @param i the 24-bit integer.
*/
util.ByteBuffer.prototype.putInt24Le = function(i) {
this.data +=
String.fromCharCode(i & 0xFF) +
String.fromCharCode(i >> 8 & 0xFF) +
String.fromCharCode(i >> 16 & 0xFF);
};
/**
* Puts a 32-bit integer in this buffer in little-endian order.
*
* @param i the 32-bit integer.
*/
util.ByteBuffer.prototype.putInt32Le = function(i) {
this.data +=
String.fromCharCode(i & 0xFF) +
String.fromCharCode(i >> 8 & 0xFF) +
String.fromCharCode(i >> 16 & 0xFF) +
String.fromCharCode(i >> 24 & 0xFF);
};
/**
* Puts an n-bit integer in this buffer in big-endian order.
*
* @param i the n-bit integer.
* @param n the number of bits in the integer.
*/
util.ByteBuffer.prototype.putInt = function(i, n) {
do {
n -= 8;
this.data += String.fromCharCode((i >> n) & 0xFF);
}
while(n > 0);
};
/**
* Puts the given buffer into this buffer.
*
* @param buffer the buffer to put into this one.
*/
util.ByteBuffer.prototype.putBuffer = function(buffer) {
this.data += buffer.getBytes();
};
/**
* Gets a byte from this buffer and advances the read pointer by 1.
*
* @return the byte.
*/
util.ByteBuffer.prototype.getByte = function() {
return this.data.charCodeAt(this.read++);
};
/**
* Gets a uint16 from this buffer in big-endian order and advances the read
* pointer by 2.
*
* @return the uint16.
*/
util.ByteBuffer.prototype.getInt16 = function() {
var rval = (
this.data.charCodeAt(this.read) << 8 ^
this.data.charCodeAt(this.read + 1));
this.read += 2;
return rval;
};
/**
* Gets a uint24 from this buffer in big-endian order and advances the read
* pointer by 3.
*
* @return the uint24.
*/
util.ByteBuffer.prototype.getInt24 = function() {
var rval = (
this.data.charCodeAt(this.read) << 16 ^
this.data.charCodeAt(this.read + 1) << 8 ^
this.data.charCodeAt(this.read + 2));
this.read += 3;
return rval;
};
/**
* Gets a uint32 from this buffer in big-endian order and advances the read
* pointer by 4.
*
* @return the word.
*/
util.ByteBuffer.prototype.getInt32 = function() {
var rval = (
this.data.charCodeAt(this.read) << 24 ^
this.data.charCodeAt(this.read + 1) << 16 ^
this.data.charCodeAt(this.read + 2) << 8 ^
this.data.charCodeAt(this.read + 3));
this.read += 4;
return rval;
};
/**
* Gets a uint16 from this buffer in little-endian order and advances the read
* pointer by 2.
*
* @return the uint16.
*/
util.ByteBuffer.prototype.getInt16Le = function() {
var rval = (
this.data.charCodeAt(this.read) ^
this.data.charCodeAt(this.read + 1) << 8);
this.read += 2;
return rval;
};
/**
* Gets a uint24 from this buffer in little-endian order and advances the read
* pointer by 3.
*
* @return the uint24.
*/
util.ByteBuffer.prototype.getInt24Le = function() {
var rval = (
this.data.charCodeAt(this.read) ^
this.data.charCodeAt(this.read + 1) << 8 ^
this.data.charCodeAt(this.read + 2) << 16);
this.read += 3;
return rval;
};
/**
* Gets a uint32 from this buffer in little-endian order and advances the read
* pointer by 4.
*
* @return the word.
*/
util.ByteBuffer.prototype.getInt32Le = function() {
var rval = (
this.data.charCodeAt(this.read) ^
this.data.charCodeAt(this.read + 1) << 8 ^
this.data.charCodeAt(this.read + 2) << 16 ^
this.data.charCodeAt(this.read + 3) << 24);
this.read += 4;
return rval;
};
/**
* Gets an n-bit integer from this buffer in big-endian order and advances the
* read pointer by n/8.
*
* @param n the number of bits in the integer.
*
* @return the integer.
*/
util.ByteBuffer.prototype.getInt = function(n) {
var rval = 0;
do {
rval = (rval << n) + this.data.charCodeAt(this.read++);
n -= 8;
}
while(n > 0);
return rval;
};
/**
* Reads bytes out into a UTF-8 string and clears them from the buffer.
*
* @param count the number of bytes to read, undefined, null or 0 for all.
*
* @return a UTF-8 string of bytes.
*/
util.ByteBuffer.prototype.getBytes = function(count) {
var rval;
if(count) {
// read count bytes
count = Math.min(this.length(), count);
rval = this.data.slice(this.read, this.read + count);
this.read += count;
}
else if(count === 0) {
rval = '';
}
else {
// read all bytes, optimize to only copy when needed
rval = (this.read === 0) ? this.data : this.data.slice(this.read);
this.clear();
}
return rval;
};
/**
* Gets a UTF-8 encoded string of the bytes from this buffer without modifying
* the read pointer.
*
* @param count the number of bytes to get, omit to get all.
*
* @return a string full of UTF-8 encoded characters.
*/
util.ByteBuffer.prototype.bytes = function(count) {
return (typeof(count) === 'undefined' ?
this.data.slice(this.read) :
this.data.slice(this.read, this.read + count));
};
/**
* Gets a byte at the given index without modifying the read pointer.
*
* @param i the byte index.
*
* @return the byte.
*/
util.ByteBuffer.prototype.at = function(i) {
return this.data.charCodeAt(this.read + i);
};
/**
* Puts a byte at the given index without modifying the read pointer.
*
* @param i the byte index.
* @param b the byte to put.
*/
util.ByteBuffer.prototype.setAt = function(i, b) {
this.data = this.data.substr(0, this.read + i) +
String.fromCharCode(b) +
this.data.substr(this.read + i + 1);
};
/**
* Gets the last byte without modifying the read pointer.
*
* @return the last byte.
*/
util.ByteBuffer.prototype.last = function() {
return this.data.charCodeAt(this.data.length - 1);
};
/**
* Creates a copy of this buffer.
*
* @return the copy.
*/
util.ByteBuffer.prototype.copy = function() {
var c = util.createBuffer(this.data);
c.read = this.read;
return c;
};
/**
* Compacts this buffer.
*/
util.ByteBuffer.prototype.compact = function() {
if(this.read > 0) {
this.data = this.data.slice(this.read);
this.read = 0;
}
};
/**
* Clears this buffer.
*/
util.ByteBuffer.prototype.clear = function() {
this.data = '';
this.read = 0;
};
/**
* Shortens this buffer by triming bytes off of the end of this buffer.
*
* @param count the number of bytes to trim off.
*/
util.ByteBuffer.prototype.truncate = function(count) {
var len = Math.max(0, this.length() - count);
this.data = this.data.substr(this.read, len);
this.read = 0;
};
/**
* Converts this buffer to a hexadecimal string.
*
* @return a hexadecimal string.
*/
util.ByteBuffer.prototype.toHex = function() {
var rval = '';
for(var i = this.read; i < this.data.length; ++i) {
var b = this.data.charCodeAt(i);
if(b < 16) {
rval += '0';
}
rval += b.toString(16);
}
return rval;
};
/**
* Converts this buffer to a UTF-16 string (standard JavaScript string).
*
* @return a UTF-16 string.
*/
util.ByteBuffer.prototype.toString = function() {
return util.decodeUtf8(this.bytes());
};
/**
* Creates a buffer that stores bytes. A value may be given to put into the
* buffer that is either a string of bytes or a UTF-16 string that will
* be encoded using UTF-8 (to do the latter, specify 'utf8' as the encoding).
*
* @param [input] the bytes to wrap (as a string) or a UTF-16 string to encode
* as UTF-8.
* @param [encoding] (default: 'raw', other: 'utf8').
*/
util.createBuffer = function(input, encoding) {
encoding = encoding || 'raw';
if(input !== undefined && encoding === 'utf8') {
input = util.encodeUtf8(input);
}
return new util.ByteBuffer(input);
};
/**
* Fills a string with a particular value. If you want the string to be a byte
* string, pass in String.fromCharCode(theByte).
*
* @param c the character to fill the string with, use String.fromCharCode
* to fill the string with a byte value.
* @param n the number of characters of value c to fill with.
*
* @return the filled string.
*/
util.fillString = function(c, n) {
var s = '';
while(n > 0) {
if(n & 1) {
s += c;
}
n >>>= 1;
if(n > 0) {
c += c;
}
}
return s;
};
/**
* Performs a per byte XOR between two byte strings and returns the result as a
* string of bytes.
*
* @param s1 first string of bytes.
* @param s2 second string of bytes.
* @param n the number of bytes to XOR.
*
* @return the XOR'd result.
*/
util.xorBytes = function(s1, s2, n) {
var s3 = '';
var b = '';
var t = '';
var i = 0;
var c = 0;
for(; n > 0; --n, ++i) {
b = s1.charCodeAt(i) ^ s2.charCodeAt(i);
if(c >= 10) {
s3 += t;
t = '';
c = 0;
}
t += String.fromCharCode(b);
++c;
}
s3 += t;
return s3;
};
/**
* Converts a hex string into a UTF-8 string of bytes.
*
* @param hex the hexadecimal string to convert.
*
* @return the string of bytes.
*/
util.hexToBytes = function(hex) {
var rval = '';
var i = 0;
if(hex.length & 1 == 1) {
// odd number of characters, convert first character alone
i = 1;
rval += String.fromCharCode(parseInt(hex[0], 16));
}
// convert 2 characters (1 byte) at a time
for(; i < hex.length; i += 2) {
rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
}
return rval;
};
/**
* Converts a UTF-8 byte string into a string of hexadecimal characters.
*
* @param bytes the byte string to convert.
*
* @return the string of hexadecimal characters.
*/
util.bytesToHex = function(bytes) {
return util.createBuffer(bytes).toHex();
};
/**
* Converts an 32-bit integer to 4-big-endian byte string.
*
* @param i the integer.
*
* @return the byte string.
*/
util.int32ToBytes = function(i) {
return (
String.fromCharCode(i >> 24 & 0xFF) +
String.fromCharCode(i >> 16 & 0xFF) +
String.fromCharCode(i >> 8 & 0xFF) +
String.fromCharCode(i & 0xFF));
};
// base64 characters, reverse mapping
var _base64 =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var _base64Idx = [
/*43 -43 = 0*/
/*'+', 1, 2, 3,'/' */
62, -1, -1, -1, 63,
/*'0','1','2','3','4','5','6','7','8','9' */
52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
/*15, 16, 17,'=', 19, 20, 21 */
-1, -1, -1, 64, -1, -1, -1,
/*65 - 43 = 22*/
/*'A','B','C','D','E','F','G','H','I','J','K','L','M', */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
/*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
/*91 - 43 = 48 */
/*48, 49, 50, 51, 52, 53 */
-1, -1, -1, -1, -1, -1,
/*97 - 43 = 54*/
/*'a','b','c','d','e','f','g','h','i','j','k','l','m' */
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
/*'n','o','p','q','r','s','t','u','v','w','x','y','z' */
39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
];
/**
* Base64 encodes a UTF-8 string of bytes.
*
* @param input the UTF-8 string of bytes to encode.
* @param maxline the maximum number of encoded bytes per line to use,
* defaults to none.
*
* @return the base64-encoded output.
*/
util.encode64 = function(input, maxline) {
var line = '';
var output = '';
var chr1, chr2, chr3;
var i = 0;
while(i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
// encode 4 character group
line += _base64.charAt(chr1 >> 2);
line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4));
if(isNaN(chr2)) {
line += '==';
}
else {
line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6));
line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63);
}
if(maxline && line.length > maxline) {
output += line.substr(0, maxline) + '\r\n';
line = line.substr(maxline);
}
}
output += line;
return output;
};
/**
* Base64 decodes a string into a UTF-8 string of bytes.
*
* @param input the base64-encoded input.
*
* @return the raw bytes.
*/
util.decode64 = function(input) {
// remove all non-base64 characters
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
var output = '';
var enc1, enc2, enc3, enc4;
var i = 0;
while(i < input.length) {
enc1 = _base64Idx[input.charCodeAt(i++) - 43];
enc2 = _base64Idx[input.charCodeAt(i++) - 43];
enc3 = _base64Idx[input.charCodeAt(i++) - 43];
enc4 = _base64Idx[input.charCodeAt(i++) - 43];
output += String.fromCharCode((enc1 << 2) | (enc2 >> 4));
if(enc3 !== 64) {
// decoded at least 2 bytes
output += String.fromCharCode(((enc2 & 15) << 4) | (enc3 >> 2));
if(enc4 !== 64) {
// decoded 3 bytes
output += String.fromCharCode(((enc3 & 3) << 6) | enc4);
}
}
}
return output;
};
/**
* UTF-8 encodes the given UTF-16 encoded string (a standard JavaScript
* string). Non-ASCII characters will be encoded as multiple bytes according
* to UTF-8.
*
* @param str the string to encode.
*
* @return the UTF-8 encoded string.
*/
util.encodeUtf8 = function(str) {
return unescape(encodeURIComponent(str));
};
/**
* Decodes a UTF-8 encoded string into a UTF-16 string.
*
* @param str the string to encode.
*
* @return the UTF-16 encoded string (standard JavaScript string).
*/
util.decodeUtf8 = function(str) {
return decodeURIComponent(escape(str));
};
/**
* Deflates the given data using a flash interface.
*
* @param api the flash interface.
* @param bytes the data.
* @param raw true to return only raw deflate data, false to include zlib
* header and trailer.
*
* @return the deflated data as a string.
*/
util.deflate = function(api, bytes, raw) {
bytes = util.decode64(api.deflate(util.encode64(bytes)).rval);
// strip zlib header and trailer if necessary
if(raw) {
// zlib header is 2 bytes (CMF,FLG) where FLG indicates that
// there is a 4-byte DICT (alder-32) block before the data if
// its 5th bit is set
var start = 2;
var flg = bytes.charCodeAt(1);
if(flg & 0x20) {
start = 6;
}
// zlib trailer is 4 bytes of adler-32
bytes = bytes.substring(start, bytes.length - 4);
}
return bytes;
};
/**
* Inflates the given data using a flash interface.
*
* @param api the flash interface.
* @param bytes the data.
* @param raw true if the incoming data has no zlib header or trailer and is
* raw DEFLATE data.
*
* @return the inflated data as a string, null on error.
*/
util.inflate = function(api, bytes, raw) {
// TODO: add zlib header and trailer if necessary/possible
var rval = api.inflate(util.encode64(bytes)).rval;
return (rval === null) ? null : util.decode64(rval);
};
/**
* Sets a storage object.
*
* @param api the storage interface.
* @param id the storage ID to use.
* @param obj the storage object, null to remove.
*/
var _setStorageObject = function(api, id, obj) {
if(!api) {
throw {
message: 'WebStorage not available.'
};
}
var rval;
if(obj === null) {
rval = api.removeItem(id);
}
else {
// json-encode and base64-encode object
obj = util.encode64(JSON.stringify(obj));
rval = api.setItem(id, obj);
}
// handle potential flash error
if(typeof(rval) !== 'undefined' && rval.rval !== true) {
throw rval.error;
}
};
/**
* Gets a storage object.
*
* @param api the storage interface.
* @param id the storage ID to use.
*
* @return the storage object entry or null if none exists.
*/
var _getStorageObject = function(api, id) {
if(!api) {
throw {
message: 'WebStorage not available.'
};
}
// get the existing entry
var rval = api.getItem(id);
/* Note: We check api.init because we can't do (api == localStorage)
on IE because of "Class doesn't support Automation" exception. Only
the flash api has an init method so this works too, but we need a
better solution in the future. */
// flash returns item wrapped in an object, handle special case
if(api.init) {
if(rval.rval === null) {
if(rval.error) {
throw rval.error;
}
// no error, but also no item
rval = null;
}
else {
rval = rval.rval;
}
}
// handle decoding
if(rval !== null) {
// base64-decode and json-decode data
rval = JSON.parse(util.decode64(rval));
}
return rval;
};
/**
* Stores an item in local storage.
*
* @param api the storage interface.
* @param id the storage ID to use.
* @param key the key for the item.
* @param data the data for the item (any javascript object/primitive).
*/
var _setItem = function(api, id, key, data) {
// get storage object
var obj = _getStorageObject(api, id);
if(obj === null) {
// create a new storage object
obj = {};
}
// update key
obj[key] = data;
// set storage object
_setStorageObject(api, id, obj);
};
/**
* Gets an item from local storage.
*
* @param api the storage interface.
* @param id the storage ID to use.
* @param key the key for the item.
*
* @return the item.
*/
var _getItem = function(api, id, key) {
// get storage object
var rval = _getStorageObject(api, id);
if(rval !== null) {
// return data at key
rval = (key in rval) ? rval[key] : null;
}
return rval;
};
/**
* Removes an item from local storage.
*
* @param api the storage interface.
* @param id the storage ID to use.
* @param key the key for the item.
*/
var _removeItem = function(api, id, key) {
// get storage object
var obj = _getStorageObject(api, id);
if(obj !== null && key in obj) {
// remove key
delete obj[key];
// see if entry has no keys remaining
var empty = true;
for(var prop in tmp) {
empty = false;
break;
}
if(empty) {
// remove entry entirely if no keys are left
obj = null;
}
// set storage object
_setStorageObject(api, id, obj);
}
};
/**
* Clears the local disk storage identified by the given ID.
*
* @param api the storage interface.
* @param id the storage ID to use.
*/
var _clearItems = function(api, id) {
_setStorageObject(api, id, null);
};
/**
* Calls a storage function.
*
* @param func the function to call.
* @param args the arguments for the function.
* @param location the location argument.
*
* @return the return value from the function.
*/
var _callStorageFunction = function(func, args, location) {
var rval = null;
// default storage types
if(typeof(location) === 'undefined') {
location = ['web', 'flash'];
}
// apply storage types in order of preference
var type;
var done = false;
var exception = null;
for(var idx in location) {
type = location[idx];
try {
if(type === 'flash' || type === 'both') {
if(args[0] === null) {
throw {
message: 'Flash local storage not available.'
};
}
else {
rval = func.apply(this, args);
done = (type === 'flash');
}
}
if(type === 'web' || type === 'both') {
args[0] = localStorage;
rval = func.apply(this, args);
done = true;
}
}
catch(ex) {
exception = ex;
}
if(done) {
break;
}
}
if(!done) {
throw exception;
}
return rval;
};
/**
* Stores an item on local disk.
*
* The available types of local storage include 'flash', 'web', and 'both'.
*
* The type 'flash' refers to flash local storage (SharedObject). In order
* to use flash local storage, the 'api' parameter must be valid. The type
* 'web' refers to WebStorage, if supported by the browser. The type 'both'
* refers to storing using both 'flash' and 'web', not just one or the
* other.
*
* The location array should list the storage types to use in order of
* preference:
*
* ['flash']: flash only storage
* ['web']: web only storage
* ['both']: try to store in both
* ['flash','web']: store in flash first, but if not available, 'web'
* ['web','flash']: store in web first, but if not available, 'flash'
*
* The location array defaults to: ['web', 'flash']
*
* @param api the flash interface, null to use only WebStorage.
* @param id the storage ID to use.
* @param key the key for the item.
* @param data the data for the item (any javascript object/primitive).
* @param location an array with the preferred types of storage to use.
*/
util.setItem = function(api, id, key, data, location) {
_callStorageFunction(_setItem, arguments, location);
};
/**
* Gets an item on local disk.
*
* Set setItem() for details on storage types.
*
* @param api the flash interface, null to use only WebStorage.