- Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathdoublearray.js
More file actions
Latest commit
791 lines (658 loc) · 24 KB
/
Copy pathdoublearray.js
File metadata and controls
791 lines (658 loc) · 24 KB
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
// Copyright (c) 2014 Takuya Asano All Rights Reserved.
(function(){
"use strict";
varTERM_CHAR="\u0000",// terminal character
TERM_CODE=0,// terminal character code
ROOT_ID=0,// index of root node
NOT_FOUND=-1,// traverse() returns if no nodes found
BASE_SIGNED=true,
CHECK_SIGNED=true,
BASE_BYTES=4,
CHECK_BYTES=4,
MEMORY_EXPAND_RATIO=2;
varnewBC=function(initial_size){
if(initial_size==null){
initial_size=1024;
}
varinitBase=function(_base,start,end){// 'end' index does not include
for(vari=start;i<end;i++){
_base[i]=-i+1;// inversed previous empty node index
}
if(0<check.array[check.array.length-1]){
varlast_used_id=check.array.length-2;
while(0<check.array[last_used_id]){
last_used_id--;
}
_base[start]=-last_used_id;
}
};
varinitCheck=function(_check,start,end){
for(vari=start;i<end;i++){
_check[i]=-i-1;// inversed next empty node index
}
};
varrealloc=function(min_size){
// expand arrays size by given ratio
varnew_size=min_size*MEMORY_EXPAND_RATIO;
// console.log('re-allocate memory to ' + new_size);
varbase_new_array=newArrayBuffer(base.signed,base.bytes,new_size);
initBase(base_new_array,base.array.length,new_size);// init BASE in new range
base_new_array.set(base.array);
base.array=null;// explicit GC
base.array=base_new_array;
varcheck_new_array=newArrayBuffer(check.signed,check.bytes,new_size);
initCheck(check_new_array,check.array.length,new_size);// init CHECK in new range
check_new_array.set(check.array);
check.array=null;// explicit GC
check.array=check_new_array;
};
varfirst_unused_node=ROOT_ID+1;
varbase={
signed: BASE_SIGNED,
bytes: BASE_BYTES,
array: newArrayBuffer(BASE_SIGNED,BASE_BYTES,initial_size)
};
varcheck={
signed: CHECK_SIGNED,
bytes: CHECK_BYTES,
array: newArrayBuffer(CHECK_SIGNED,CHECK_BYTES,initial_size)
};
// init root node
base.array[ROOT_ID]=1;
check.array[ROOT_ID]=ROOT_ID;
// init BASE
initBase(base.array,ROOT_ID+1,base.array.length);
// init CHECK
initCheck(check.array,ROOT_ID+1,check.array.length);
return{
getBaseBuffer: function(){
returnbase.array;
},
getCheckBuffer: function(){
returncheck.array;
},
loadBaseBuffer: function(base_buffer){
base.array=base_buffer;
returnthis;
},
loadCheckBuffer: function(check_buffer){
check.array=check_buffer;
returnthis;
},
size: function(){
returnMath.max(base.array.length,check.array.length);
},
getBase: function(index){
if(base.array.length-1<index){
return-index+1;
// realloc(index);
}
// if (!Number.isFinite(base.array[index])) {
// console.log('getBase:' + index);
// throw 'getBase' + index;
// }
returnbase.array[index];
},
getCheck: function(index){
if(check.array.length-1<index){
return-index-1;
// realloc(index);
}
// if (!Number.isFinite(check.array[index])) {
// console.log('getCheck:' + index);
// throw 'getCheck' + index;
// }
returncheck.array[index];
},
setBase: function(index,base_value){
if(base.array.length-1<index){
realloc(index);
}
base.array[index]=base_value;
},
setCheck: function(index,check_value){
if(check.array.length-1<index){
realloc(index);
}
check.array[index]=check_value;
},
setFirstUnusedNode: function(index){
// if (!Number.isFinite(index)) {
// throw 'assertion error: setFirstUnusedNode ' + index + ' is not finite number';
// }
first_unused_node=index;
},
getFirstUnusedNode: function(){
// if (!Number.isFinite(first_unused_node)) {
// throw 'assertion error: getFirstUnusedNode ' + first_unused_node + ' is not finite number';
// }
returnfirst_unused_node;
},
shrink: function(){
varlast_index=this.size()-1;
while(true){
if(0<=check.array[last_index]){
break;
}
last_index--;
}
base.array=base.array.subarray(0,last_index+2);// keep last unused node
check.array=check.array.subarray(0,last_index+2);// keep last unused node
},
calc: function(){
varunused_count=0;
varsize=check.array.length;
for(vari=0;i<size;i++){
if(check.array[i]<0){
unused_count++;
}
}
return{
all: size,
unused: unused_count,
efficiency: (size-unused_count)/size
};
},
dump: function(){
// for debug
vardump_base="";
vardump_check="";
vari;
for(i=0;i<base.array.length;i++){
dump_base=dump_base+" "+this.getBase(i);
}
for(i=0;i<check.array.length;i++){
dump_check=dump_check+" "+this.getCheck(i);
}
console.log("base:"+dump_base);
console.log("chck:"+dump_check);
return"base:"+dump_base+" chck:"+dump_check;
}
};
};
/**
* Factory method of double array
*/
functionDoubleArrayBuilder(initial_size){
this.bc=newBC(initial_size);// BASE and CHECK
this.keys=[];
}
/**
* Append a key to initialize set
* (This method should be called by dictionary ordered key)
*
* @param {String} key
* @param {Number} value Integer value from 0 to max signed integer number - 1
*/
DoubleArrayBuilder.prototype.append=function(key,record){
this.keys.push({k: key,v: record});
returnthis;
};
/**
* Build double array for given keys
*
* @param {Array} keys Array of keys. A key is a Object which has properties 'k', 'v'.
* 'k' is a key string, 'v' is a record assigned to that key.
* @return {DoubleArray} Compiled double array
*/
DoubleArrayBuilder.prototype.build=function(keys,sorted){
if(keys==null){
keys=this.keys;
}
if(keys==null){
returnnewDoubleArray(this.bc);
}
if(sorted==null){
sorted=false;
}
// Convert key string to ArrayBuffer
varbuff_keys=
keys.map(function(k){
return{
k: stringToUtf8Bytes(k.k+TERM_CHAR),
v: k.v
};
});
// Sort keys by byte order
if(sorted){
this.keys=buff_keys;
}else{
this.keys=
buff_keys.sort(function(k1,k2){
varb1=k1.k;
varb2=k2.k;
varmin_length=Math.min(b1.length,b2.length);
for(varpos=0;pos<min_length;pos++){
if(b1[pos]===b2[pos]){
continue;
}
returnb1[pos]-b2[pos];
}
returnb1.length-b2.length;
});
}
buff_keys=null;// explicit GC
this._build(ROOT_ID,0,0,this.keys.length);
returnnewDoubleArray(this.bc);
};
/**
* Append nodes to BASE and CHECK array recursively
*/
DoubleArrayBuilder.prototype._build=function(parent_index,position,start,length){
varchildren_info=this.getChildrenInfo(position,start,length);
var_base=this.findAllocatableBase(children_info);
this.setBC(parent_index,children_info,_base);
for(vari=0;i<children_info.length;i=i+3){
varchild_code=children_info[i];
if(child_code===TERM_CODE){
continue;
}
varchild_start=children_info[i+1];
varchild_len=children_info[i+2];
varchild_index=_base+child_code;
this._build(child_index,position+1,child_start,child_len);
}
};
DoubleArrayBuilder.prototype.getChildrenInfo=function(position,start,length){
varcurrent_char=this.keys[start].k[position];
vari=0;
varchildren_info=newInt32Array(length*3);
children_info[i++]=current_char;// char (current)
children_info[i++]=start;// start index (current)
varnext_pos=start;
varstart_pos=start;
for(;next_pos<start+length;next_pos++){
varnext_char=this.keys[next_pos].k[position];
if(current_char!==next_char){
children_info[i++]=next_pos-start_pos;// length (current)
children_info[i++]=next_char;// char (next)
children_info[i++]=next_pos;// start index (next)
current_char=next_char;
start_pos=next_pos;
}
}
children_info[i++]=next_pos-start_pos;
children_info=children_info.subarray(0,i);
returnchildren_info;
};
DoubleArrayBuilder.prototype.setBC=function(parent_id,children_info,_base){
varbc=this.bc;
bc.setBase(parent_id,_base);// Update BASE of parent node
vari;
for(i=0;i<children_info.length;i=i+3){
varcode=children_info[i];
varchild_id=_base+code;
// Update linked list of unused nodes
// Assertion
// if (child_id < 0) {
// throw 'assertion error: child_id is negative'
// }
varprev_unused_id=-bc.getBase(child_id);
varnext_unused_id=-bc.getCheck(child_id);
// if (prev_unused_id < 0) {
// throw 'assertion error: setBC'
// }
// if (next_unused_id < 0) {
// throw 'assertion error: setBC'
// }
if(child_id!==bc.getFirstUnusedNode()){
bc.setCheck(prev_unused_id,-next_unused_id);
}else{
// Update first_unused_node
bc.setFirstUnusedNode(next_unused_id);
}
bc.setBase(next_unused_id,-prev_unused_id);
varcheck=parent_id;// CHECK is parent node index
bc.setCheck(child_id,check);// Update CHECK of child node
// Update record
if(code===TERM_CODE){
varstart_pos=children_info[i+1];
// var len = children_info[i + 2];
// if (len != 1) {
// throw 'assertion error: there are multiple terminal nodes. len:' + len;
// }
varvalue=this.keys[start_pos].v;
if(value==null){
value=0;
}
varbase=-value-1;// BASE is inverted record value
bc.setBase(child_id,base);// Update BASE of child(leaf) node
}
}
};
/**
* Find BASE value that all children are allocatable in double array's region
*/
DoubleArrayBuilder.prototype.findAllocatableBase=function(children_info){
varbc=this.bc;
// Assertion: keys are sorted by byte order
// var c = -1;
// for (var i = 0; i < children_info.length; i = i + 3) {
// if (children_info[i] < c) {
// throw 'assertion error: not sort key'
// }
// c = children_info[i];
// }
// iterate linked list of unused nodes
var_base;
varcurr=bc.getFirstUnusedNode();// current index
// if (curr < 0) {
// throw 'assertion error: getFirstUnusedNode returns negative value'
// }
while(true){
_base=curr-children_info[0];
if(_base<0){
curr=-bc.getCheck(curr);// next
// if (curr < 0) {
// throw 'assertion error: getCheck returns negative value'
// }
continue;
}
varempty_area_found=true;
for(vari=0;i<children_info.length;i=i+3){
varcode=children_info[i];
varcandidate_id=_base+code;
if(!this.isUnusedNode(candidate_id)){
// candidate_id is used node
// next
curr=-bc.getCheck(curr);
// if (curr < 0) {
// throw 'assertion error: getCheck returns negative value'
// }
empty_area_found=false;
break;
}
}
if(empty_area_found){
// Area is free
return_base;
}
}
};
/**
* Check this double array index is unused or not
*/
DoubleArrayBuilder.prototype.isUnusedNode=function(index){
varbc=this.bc;
varcheck=bc.getCheck(index);
// if (index < 0) {
// throw 'assertion error: isUnusedNode index:' + index;
// }
if(index===ROOT_ID){
// root node
returnfalse;
}
if(check<0){
// unused
returntrue;
}
// used node (incl. leaf)
returnfalse;
};
/**
* Factory method of double array
*/
functionDoubleArray(bc){
this.bc=bc;// BASE and CHECK
this.bc.shrink();
}
/**
* Look up a given key in this trie
*
* @param {String} key
* @return {Boolean} True if this trie contains a given key
*/
DoubleArray.prototype.contain=function(key){
varbc=this.bc;
key+=TERM_CHAR;
varbuffer=stringToUtf8Bytes(key);
varparent=ROOT_ID;
varchild=NOT_FOUND;
for(vari=0;i<buffer.length;i++){
varcode=buffer[i];
child=this.traverse(parent,code);
if(child===NOT_FOUND){
returnfalse;
}
if(bc.getBase(child)<=0){
// leaf node
returntrue;
}else{
// not leaf
parent=child;
continue;
}
}
returnfalse;
};
/**
* Look up a given key in this trie
*
* @param {String} key
* @return {Number} Record value assgned to this key, -1 if this key does not contain
*/
DoubleArray.prototype.lookup=function(key){
key+=TERM_CHAR;
varbuffer=stringToUtf8Bytes(key);
varparent=ROOT_ID;
varchild=NOT_FOUND;
for(vari=0;i<buffer.length;i++){
varcode=buffer[i];
child=this.traverse(parent,code);
if(child===NOT_FOUND){
returnNOT_FOUND;
}
parent=child;
}
varbase=this.bc.getBase(child);
if(base<=0){
// leaf node
return-base-1;
}else{
// not leaf
returnNOT_FOUND;
}
};
/**
* Common prefix search
*
* @param {String} key
* @return {Array} Each result object has 'k' and 'v' (key and record,
* respectively) properties assigned to matched string
*/
DoubleArray.prototype.commonPrefixSearch=function(key){
varbuffer=stringToUtf8Bytes(key);
varparent=ROOT_ID;
varchild=NOT_FOUND;
varresult=[];
for(vari=0;i<buffer.length;i++){
varcode=buffer[i];
child=this.traverse(parent,code);
if(child!==NOT_FOUND){
parent=child;
// look forward by terminal character code to check this node is a leaf or not
vargrand_child=this.traverse(child,TERM_CODE);
if(grand_child!==NOT_FOUND){
varbase=this.bc.getBase(grand_child);
varr={};
if(base<=0){
// If child is a leaf node, add record to result
r.v=-base-1;
}
// If child is a leaf node, add word to result
r.k=utf8BytesToString(arrayCopy(buffer,0,i+1));
result.push(r);
}
continue;
}else{
break;
}
}
returnresult;
};
DoubleArray.prototype.traverse=function(parent,code){
varchild=this.bc.getBase(parent)+code;
if(this.bc.getCheck(child)===parent){
returnchild;
}else{
returnNOT_FOUND;
}
};
DoubleArray.prototype.size=function(){
returnthis.bc.size();
};
DoubleArray.prototype.calc=function(){
returnthis.bc.calc();
};
DoubleArray.prototype.dump=function(){
returnthis.bc.dump();
};
// Array utility functions
varnewArrayBuffer=function(signed,bytes,size){
if(signed){
switch(bytes){
case1:
returnnewInt8Array(size);
case2:
returnnewInt16Array(size);
case4:
returnnewInt32Array(size);
default:
thrownewRangeError("Invalid newArray parameter element_bytes:"+bytes);
}
}else{
switch(bytes){
case1:
returnnewUint8Array(size);
case2:
returnnewUint16Array(size);
case4:
returnnewUint32Array(size);
default:
thrownewRangeError("Invalid newArray parameter element_bytes:"+bytes);
}
}
};
vararrayCopy=function(src,src_offset,length){
varbuffer=newArrayBuffer(length);
vardstU8=newUint8Array(buffer,0,length);
varsrcU8=src.subarray(src_offset,length);
dstU8.set(srcU8);
returndstU8;
};
/**
* Convert String (UTF-16) to UTF-8 ArrayBuffer
*
* @param {String} str UTF-16 string to convert
* @return {Uint8Array} Byte sequence encoded by UTF-8
*/
varstringToUtf8Bytes=function(str){
// Max size of 1 character is 4 bytes
varbytes=newUint8Array(newArrayBuffer(str.length*4));
vari=0,j=0;
while(i<str.length){
varunicode_code;
varutf16_code=str.charCodeAt(i++);
if(utf16_code>=0xD800&&utf16_code<=0xDBFF){
// surrogate pair
varupper=utf16_code;// high surrogate
varlower=str.charCodeAt(i++);// low surrogate
if(lower>=0xDC00&&lower<=0xDFFF){
unicode_code=
(upper-0xD800)*(1<<10)+(1<<16)+
(lower-0xDC00);
}else{
// malformed surrogate pair
returnnull;
}
}else{
// not surrogate code
unicode_code=utf16_code;
}
if(unicode_code<0x80){
// 1-byte
bytes[j++]=unicode_code;
}elseif(unicode_code<(1<<11)){
// 2-byte
bytes[j++]=(unicode_code>>>6)|0xC0;
bytes[j++]=(unicode_code&0x3F)|0x80;
}elseif(unicode_code<(1<<16)){
// 3-byte
bytes[j++]=(unicode_code>>>12)|0xE0;
bytes[j++]=((unicode_code>>6)&0x3f)|0x80;
bytes[j++]=(unicode_code&0x3F)|0x80;
}elseif(unicode_code<(1<<21)){
// 4-byte
bytes[j++]=(unicode_code>>>18)|0xF0;
bytes[j++]=((unicode_code>>12)&0x3F)|0x80;
bytes[j++]=((unicode_code>>6)&0x3F)|0x80;
bytes[j++]=(unicode_code&0x3F)|0x80;
}else{
// malformed UCS4 code
}
}
returnbytes.subarray(0,j);
};
/**
* Convert UTF-8 ArrayBuffer to String (UTF-16)
*
* @param {Uint8Array} bytes UTF-8 byte sequence to convert
* @return {String} String encoded by UTF-16
*/
varutf8BytesToString=function(bytes){
varstr="";
varcode,b1,b2,b3,b4,upper,lower;
vari=0;
while(i<bytes.length){
b1=bytes[i++];
if(b1<0x80){
// 1 byte
code=b1;
}elseif((b1>>5)===0x06){
// 2 bytes
b2=bytes[i++];
code=((b1&0x1f)<<6)|(b2&0x3f);
}elseif((b1>>4)===0x0e){
// 3 bytes
b2=bytes[i++];
b3=bytes[i++];
code=((b1&0x0f)<<12)|((b2&0x3f)<<6)|(b3&0x3f);
}else{
// 4 bytes
b2=bytes[i++];
b3=bytes[i++];
b4=bytes[i++];
code=((b1&0x07)<<18)|((b2&0x3f)<<12)|((b3&0x3f)<<6)|(b4&0x3f);
}
if(code<0x10000){
str+=String.fromCharCode(code);
}else{
// surrogate pair
code-=0x10000;
upper=(0xD800|(code>>10));
lower=(0xDC00|(code&0x3FF));
str+=String.fromCharCode(upper,lower);
}
}
returnstr;
};
// public methods
vardoublearray={
builder: function(initial_size){
returnnewDoubleArrayBuilder(initial_size);
},
load: function(base_buffer,check_buffer){
varbc=newBC(0);
bc.loadBaseBuffer(base_buffer);
bc.loadCheckBuffer(check_buffer);
returnnewDoubleArray(bc);
}
};
if("undefined"===typeofmodule){
// In browser
window.doublearray=doublearray;
}else{
// In node
module.exports=doublearray;
}
})();