-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdarts-clone.ex.h
1621 lines (1370 loc) · 41.5 KB
/
darts-clone.ex.h
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
#ifndef DARTS_H_
#define DARTS_H_
// A clone of the Darts (Double-ARray Trie System)
//
// Copyright (C) 2008-2009 Susumu Yata <[email protected]>
// All rights reserved.
#define DARTS_VERSION "0.32"
#define DARTS_CLONE_VERSION "0.32f-ex"
#ifdef _MSC_VER
#include <stdio.h>
#include <share.h>
#endif // _MSC_VER
#include <cstdio>
#include <exception>
#include <stack>
#include <vector>
// Defines macros for debugging.
#ifdef _DEBUG
#include <iostream>
#define LOG (std::cerr << "DEBUG:" << __LINE__ << ": ")
#define LOG_VALUE(value) (LOG << # value << " = " << value << '\n')
#else // _DEBUG
#define LOG
#define LOG_VALUE(value)
#endif // _DEBUG
// Defines macros for throwing exceptions with line numbers.
#define THROW(msg) THROW_RELAY(__LINE__, msg)
#define THROW_RELAY(line, msg) THROW_FINAL(line, msg)
#define THROW_FINAL(line, msg) throw \
DoubleArrayException("darts-clone-" DARTS_CLONE_VERSION \
" [" # line "]: " msg)
namespace Darts
{
// This class provides basic types used in this library.
class DoubleArrayBasicTypes
{
public:
typedef char char_type;
typedef unsigned char uchar_type;
// Must be a 32-bit unsigned integer type.
typedef unsigned int base_type;
typedef std::size_t size_type;
// Must be a 32-bit signed integer type.
typedef int value_type;
private:
// No objects.
DoubleArrayBasicTypes();
};
// Exception class.
class DoubleArrayException : public std::exception
{
private:
const char *msg_;
public:
// A constant string should be passed.
template <int Size>
explicit DoubleArrayException(const char (&msg)[Size]) : msg_(msg) {}
const char *what() const throw() { return msg_; }
};
// File I/O.
class DoubleArrayFile
{
public:
typedef DoubleArrayBasicTypes::size_type size_type;
private:
std::FILE *file_;
// Copies are not allowed.
DoubleArrayFile(const DoubleArrayFile &);
DoubleArrayFile &operator=(const DoubleArrayFile &);
public:
DoubleArrayFile(const char *file_name, const char *mode) : file_(0)
{
if (!file_name)
THROW("null file name");
else if (!mode)
THROW("null file mode");
#ifdef _MSC_VER
// To avoid warnings against std::fopen().
file_ = _fsopen(file_name, mode, _SH_DENYWR);
#else
file_ = std::fopen(file_name, mode);
#endif
}
~DoubleArrayFile() { is_open() && std::fclose(file_); }
// Moves a file pointer.
bool seek(size_type offset, int whence = SEEK_SET)
{ return std::fseek(file_, static_cast<long>(offset), whence) == 0; }
// Gets the file size.
bool size(size_type &file_size)
{
long current_position = ftell(file_);
if (current_position == -1L || !seek(0, SEEK_END))
return false;
long pos_end = ftell(file_);
if (pos_end == -1L || !seek(current_position, SEEK_SET))
return false;
file_size = static_cast<size_type>(pos_end);
return true;
}
// Reads units from a file.
template <typename T>
bool read(T *buf, size_type nmemb)
{ return std::fread(buf, sizeof(T), nmemb, file_) == nmemb; }
// Writes units to a file.
template <typename T>
bool write(const T *buf, size_type nmemb)
{ return std::fwrite(buf, sizeof(T), nmemb, file_) == nmemb; }
// Checks if a file is opened or not.
bool is_open() const { return file_ ? true : false; }
};
// A range for keys.
class DoubleArrayKeyRange
{
public:
typedef DoubleArrayBasicTypes::base_type base_type;
typedef DoubleArrayBasicTypes::size_type size_type;
public:
DoubleArrayKeyRange(size_type begin, size_type end, size_type depth)
: begin_(begin), end_(end), depth_(depth), index_(0) {}
void set_index(base_type index) { index_ = index; }
size_type begin() const { return begin_; }
size_type end() const { return end_; }
size_type depth() const { return depth_; }
base_type index() const { return index_; }
private:
size_type begin_;
size_type end_;
size_type depth_;
base_type index_;
};
// An object pool for building a dawg.
template <typename ValueType>
class DoubleArrayPool
{
public:
typedef ValueType value_type;
typedef DoubleArrayBasicTypes::base_type base_type;
typedef DoubleArrayBasicTypes::size_type size_type;
// Number of nodes in each block.
enum { BLOCK_SIZE = 1024 };
private:
std::vector<value_type *> blocks_;
base_type size_;
// Copies are not allowed.
DoubleArrayPool(const DoubleArrayPool &);
DoubleArrayPool &operator=(const DoubleArrayPool &);
public:
DoubleArrayPool() : blocks_(), size_(0) {}
~DoubleArrayPool() { clear(); }
// Deletes all blocks.
void clear()
{
for (size_type i = 0; i < blocks_.size(); ++i)
delete [] blocks_[i];
size_ = 0;
std::vector<value_type *>(0).swap(blocks_);
}
// Gets a new object.
base_type get()
{
if (size_ == static_cast<base_type>(BLOCK_SIZE * blocks_.size()))
blocks_.push_back(new value_type[BLOCK_SIZE]);
return size_++;
}
// Reads the number of values.
base_type size() const { return size_; }
// Accesses a value.
value_type &operator[](base_type index)
{ return blocks_[index / BLOCK_SIZE][index % BLOCK_SIZE]; }
// Accesses a value.
const value_type &operator[](base_type index) const
{ return blocks_[index / BLOCK_SIZE][index % BLOCK_SIZE]; }
};
// Directed Acyclic Word Graph (DAWG).
class DoubleArrayDawg
{
public:
typedef DoubleArrayBasicTypes::char_type char_type;
typedef DoubleArrayBasicTypes::base_type base_type;
typedef DoubleArrayBasicTypes::size_type size_type;
typedef DoubleArrayBasicTypes::value_type value_type;
typedef std::pair<base_type, base_type> pair_type;
typedef DoubleArrayPool<pair_type> pair_pool_type;
typedef DoubleArrayPool<char_type> char_pool_type;
private:
pair_pool_type state_pool_;
char_pool_type label_pool_;
pair_pool_type node_pool_;
std::stack<base_type> recycle_stack_;
base_type num_of_merged_states_;
// Copies are not allowed.
DoubleArrayDawg(const DoubleArrayDawg &);
DoubleArrayDawg &operator=(const DoubleArrayDawg &);
public:
DoubleArrayDawg() : state_pool_(), label_pool_(), node_pool_(),
recycle_stack_(), num_of_merged_states_(0) {}
// Builds a dawg.
void build(size_type num_of_keys, const char_type * const *keys,
const size_type *lengths, const value_type *values,
int (*progress_func)(size_type, size_type))
{
// For the root state and the root node.
get();
set_label(0, 0);
// Inserts and merges keys.
size_type key_id = num_of_keys;
size_type max_progress = num_of_keys + num_of_keys / 4;
while (key_id--)
{
const char_type *key = keys[key_id];
size_type length = lengths ? lengths[key_id] : length_of(key);
value_type value = values[key_id];
insert_key(key, length, value);
if (progress_func)
progress_func(num_of_keys - key_id, max_progress);
}
// Merges states corresponding to the first key.
merge(0);
node_pool_.clear();
LOG_VALUE(state_pool_.size());
LOG_VALUE(recycle_stack_.size());
LOG_VALUE(num_of_merged_states_);
}
// Gets the size of a state pool.
base_type size() const
{ return static_cast<base_type>(state_pool_.size()); }
// Gets the number of states.
base_type num_of_states() const
{ return static_cast<base_type>(size() - recycle_stack_.size()); }
public:
// Clears a state.
void clear_state(base_type index)
{ state_pool_[index] = pair_type(0, 0); }
// Sets an index of a next state.
void set_child(base_type index, base_type child)
{ state_pool_[index].first = child << 1; }
// Sets an index of a sibling state.
void set_sibling(base_type index, base_type sibling)
{ state_pool_[index].second = sibling << 1; }
// Sets a value of a leaf state.
void set_value(base_type index, value_type value)
{ state_pool_[index].first = (value << 1) | 1; }
// Sets a label.
void set_label(base_type index, char_type label)
{ label_pool_[index] = label; }
// Reads an index of a next state.
base_type child(base_type index) const
{ return get_value(state_pool_[index].first); }
// Reads an index of a sibling state.
base_type sibling(base_type index) const
{ return get_value(state_pool_[index].second); }
// Checks if a state is a leaf or not.
bool is_leaf(base_type index) const
{ return get_bit(state_pool_[index].first); }
// Reads a value of a leaf state.
value_type value(base_type index) const
{ return get_value(state_pool_[index].first); }
// Reads a label.
char_type label(base_type index) const
{ return label_pool_[index]; }
private:
// Clears a node.
void clear_node(base_type index)
{ node_pool_[index] = pair_type(0, 0); }
// Sets an index of the root node.
void set_root_node(base_type root_node)
{ set_right(0, root_node); }
// Sets a node color of a red-black tree.
void set_is_red(base_type index, bool is_red)
{
if (is_red)
node_pool_[index].first |= 1;
else
node_pool_[index].first &= ~static_cast<base_type>(1);
}
// Reads an index of a left node.
void set_left(base_type index, base_type left)
{
node_pool_[index].first &= 1;
node_pool_[index].first |= left << 1;
}
// Reads an index of a right node.
void set_right(base_type index, base_type right)
{ node_pool_[index].second = right; }
// Reads an index of the root node.
base_type root_node() const
{ return right(0); }
// Checks if a node of a red-black tree is red or not.
bool is_red(base_type index) const
{ return get_bit(node_pool_[index].first); }
// Reads an index of a left node.
base_type left(base_type index) const
{ return get_value(node_pool_[index].first); }
// Reads an index of a right node.
base_type right(base_type index) const
{ return node_pool_[index].second; }
private:
// Keys should be inserted in reverse order.
void insert_key(const char_type *key, size_type length, value_type value)
{
base_type index = 0;
base_type key_pos = 0;
// Finds a separate state.
for ( ; key_pos <= length; ++key_pos)
{
base_type child_index = child(index);
if (!child_index)
break;
else if (label(child_index) != get_key_label(key, length, key_pos))
{
set_child(index, merge(child_index));
break;
}
index = child_index;
}
// Adds new states.
for ( ; key_pos <= length; ++key_pos)
{
base_type child_index = get();
set_sibling(child_index, child(index));
set_label(child_index, get_key_label(key, length, key_pos));
set_child(index, child_index);
index = child_index;
}
set_value(index, value);
}
// Merges common states recursively.
base_type merge(base_type index)
{
if (child(index) && !is_leaf(index))
{
base_type child_index = merge(child(index));
set_child(index, child_index);
}
base_type matched_index = find_state(index);
if (matched_index)
{
unget(index);
index = matched_index;
++num_of_merged_states_;
}
else
insert_state(index);
return index;
}
private:
// Finds a state from a red-black tree.
base_type find_state(base_type index)
{
base_type node = root_node();
while (node)
{
int cmp = compare_states(index, node);
if (!cmp)
return node;
else if (cmp < 0)
node = left(node);
else
node = right(node);
}
return 0;
}
// Inserts a state into a red-black tree.
void insert_state(base_type index)
{ set_root_node(insert_state(root_node(), index)); }
// Inserts a state into a red-black tree.
base_type insert_state(base_type node, base_type index)
{
if (!node)
{
set_is_red(index, true);
return index;
}
if (is_red(left(node)) && is_red(right(node)))
color_flip(node);
int cmp = compare_states(index, node);
if (cmp < 0)
set_left(node, insert_state(left(node), index));
else if (cmp > 0)
set_right(node, insert_state(right(node), index));
if (is_red(right(node)))
node = rotate_left(node);
if (is_red(left(node)) && is_red(left(left(node))))
node = rotate_right(node);
return node;
}
// Compares a pair of states.
int compare_states(base_type lhs, base_type rhs) const
{
const pair_type &lhs_state = state_pool_[lhs];
const pair_type &rhs_state = state_pool_[rhs];
if (lhs_state.first < rhs_state.first)
return -1;
else if (lhs_state.first > rhs_state.first)
return 1;
if (lhs_state.second < rhs_state.second)
return -1;
else if (lhs_state.second > rhs_state.second)
return 1;
return label_pool_[lhs] - label_pool_[rhs];
}
// Rotation for a red-black tree.
base_type rotate_left(base_type index)
{
base_type x_index = right(index);
set_right(index, left(x_index));
set_left(x_index, index);
set_is_red(x_index, is_red(index));
set_is_red(index, true);
return x_index;
}
// Rotation for a red-black tree.
base_type rotate_right(base_type index)
{
base_type x_index = left(index);
set_left(index, right(x_index));
set_right(x_index, index);
set_is_red(x_index, is_red(index));
set_is_red(index, true);
return x_index;
}
// Flips a color.
void color_flip(base_type index)
{
set_is_red(index, !is_red(index));
set_is_red(left(index), !is_red(left(index)));
set_is_red(right(index), !is_red(right(index)));
}
private:
// Gets new objects.
base_type get()
{
base_type index = 0;
if (recycle_stack_.empty())
{
index = state_pool_.get();
label_pool_.get();
node_pool_.get();
}
else
{
index = recycle_stack_.top();
recycle_stack_.pop();
}
clear_state(index);
clear_node(index);
return index;
}
// Ungets latest objects.
void unget(base_type index) { recycle_stack_.push(index); }
// Gets a least significant bit.
static bool get_bit(base_type value) { return (value & 1) ? true : false; }
// Gets a value except for a least significant bit.
static base_type get_value(base_type value) { return value >> 1; }
// Gets a byte from a key.
static char_type get_key_label(const char_type *key,
size_type length, size_type key_pos)
{ return (key_pos < length) ? key[key_pos] : 0; }
// Scans a given key and returns its length.
static size_type length_of(const char_type *key)
{
size_type count = 0;
while (key[count])
++count;
return count;
}
};
// A unit of a double-array.
class DoubleArrayUnit
{
public:
typedef DoubleArrayBasicTypes::uchar_type uchar_type;
typedef DoubleArrayBasicTypes::base_type base_type;
typedef DoubleArrayBasicTypes::value_type value_type;
static const base_type OFFSET_MAX = static_cast<base_type>(1) << 21;
static const base_type IS_LEAF_BIT = static_cast<base_type>(1) << 31;
static const base_type HAS_LEAF_BIT = static_cast<base_type>(1) << 8;
static const base_type EXTENSION_BIT = static_cast<base_type>(1) << 9;
private:
base_type base_;
public:
DoubleArrayUnit() : base_(0) {}
// Sets a flag to show that a unit has a leaf as a child.
void set_has_leaf() { base_ |= HAS_LEAF_BIT; }
// Sets a value to a leaf unit.
void set_value(value_type value)
{ base_ = static_cast<base_type>(value) | IS_LEAF_BIT; }
// Sets a label to a non-leaf unit.
void set_label(uchar_type label)
{ base_ = (base_ & ~static_cast<base_type>(0xFF)) | label; }
// Sets an offset to a non-leaf unit.
void set_offset(base_type offset)
{
if (offset >= (OFFSET_MAX << 8))
THROW("too large offset");
base_ &= IS_LEAF_BIT | HAS_LEAF_BIT | 0xFF;
if (offset < OFFSET_MAX)
base_ |= (offset << 10);
else
base_ |= (offset << 2) | EXTENSION_BIT;
}
// Checks if a unit is a leaf or not.
bool is_leaf() const { return (base_ & IS_LEAF_BIT) ? true : false; }
// Checks if a unit has a leaf as a child or not.
bool has_leaf() const { return (base_ & HAS_LEAF_BIT) ? true : false; }
// Checks if a unit corresponds to a leaf or not.
value_type value() const
{ return static_cast<value_type>(base_ & ~IS_LEAF_BIT); }
// Reads a label with a leaf flag from a non-leaf unit.
base_type label() const { return base_ & (IS_LEAF_BIT | 0xFF); }
// Reads an offset to child units from a non-leaf unit.
base_type offset() const
{ return (base_ >> 10) << ((base_ & EXTENSION_BIT) >> 6); }
// Reads an offset to child units from a non-leaf unit by using if.
base_type offset_if() const
{ return (base_ & EXTENSION_BIT) ? ((base_ >> 10) << 8) : (base_ >> 10); }
};
// A link in a double-array.
class DoubleArrayLink
{
public:
typedef DoubleArrayBasicTypes::uchar_type uchar_type;
private:
uchar_type child_;
uchar_type bros_;
public:
DoubleArrayLink() : child_(0), bros_(0) {}
void set_child(uchar_type child) { child_ = child; }
void set_bros(uchar_type bros) { bros_ = bros; }
uchar_type child() const { return child_; }
uchar_type bros() const { return bros_; }
};
// An extra information which are used for building a double-array.
class DoubleArrayExtra
{
public:
typedef DoubleArrayBasicTypes::base_type base_type;
private:
base_type lo_values_;
base_type hi_values_;
public:
DoubleArrayExtra() : lo_values_(0), hi_values_(0) {}
void clear() { lo_values_ = hi_values_ = 0; }
// Sets if a unit is fixed or not.
void set_is_fixed() { lo_values_ |= 1; }
// Sets an index of the next unused unit.
void set_next(base_type next)
{ lo_values_ = (lo_values_ & 1) | (next << 1); }
// Sets if an index is used as an offset or not.
void set_is_used() { hi_values_ |= 1; }
// Sets an index of the previous unused unit.
void set_prev(base_type prev)
{ hi_values_ = (hi_values_ & 1) | (prev << 1); }
// Reads if a unit is fixed or not.
bool is_fixed() const { return (lo_values_ & 1) == 1; }
// Reads an index of the next unused unit.
base_type next() const { return lo_values_ >> 1; }
// Reads if an index is used as an offset or not.
bool is_used() const { return (hi_values_ & 1) == 1; }
// Reads an index of the previous unused unit.
base_type prev() const { return hi_values_ >> 1; }
};
// A class for building a double-array.
class DoubleArrayBuilder
{
public:
typedef DoubleArrayBasicTypes::char_type char_type;
typedef DoubleArrayBasicTypes::uchar_type uchar_type;
typedef DoubleArrayBasicTypes::base_type base_type;
typedef DoubleArrayBasicTypes::size_type size_type;
typedef DoubleArrayBasicTypes::value_type value_type;
typedef DoubleArrayKeyRange range_type;
typedef DoubleArrayDawg dawg_type;
typedef DoubleArrayUnit unit_type;
typedef DoubleArrayLink link_type;
typedef DoubleArrayExtra extra_type;
enum
{
BLOCK_SIZE = 256,
NUM_OF_UNFIXED_BLOCKS = 16,
UNFIXED_SIZE = BLOCK_SIZE * NUM_OF_UNFIXED_BLOCKS,
};
private:
// Masks for offsets.
static const base_type LOWER_MASK = unit_type::OFFSET_MAX - 1;
static const base_type UPPER_MASK = ~LOWER_MASK;
private:
size_type num_of_keys_;
const char_type * const *keys_;
const size_type *lengths_;
const value_type *values_;
int (*progress_func_)(size_type, size_type);
size_type progress_;
size_type max_progress_;
std::vector<unit_type> units_;
std::vector<link_type> links_;
std::vector<extra_type *> extras_;
std::vector<uchar_type> labels_;
base_type unfixed_index_;
size_type num_of_unused_units_;
// Copies are not allowed.
DoubleArrayBuilder(const DoubleArrayBuilder &);
DoubleArrayBuilder &operator=(const DoubleArrayBuilder &);
public:
DoubleArrayBuilder() : num_of_keys_(0), keys_(0), lengths_(0), values_(0),
progress_func_(0), progress_(0), max_progress_(0),
units_(), links_(), extras_(),
labels_(), unfixed_index_(0), num_of_unused_units_(0) {}
~DoubleArrayBuilder()
{
for (size_type i = 0; i < extras_.size(); ++i)
delete [] extras_[i];
}
// Copies parameters and builds a double-array.
bool build(size_type num_of_keys, const char_type * const *keys,
const size_type *lengths, const value_type *values,
int (*progress_func)(size_type, size_type))
{
// Copies parameters.
num_of_keys_ = num_of_keys;
keys_ = keys;
lengths_ = lengths;
values_ = values;
progress_func_ = progress_func;
test_keys();
LOG_VALUE(num_of_keys_);
// Builds a naive trie.
if (!values_)
build_trie();
else
build_dawg();
LOG_VALUE(num_of_units());
// Shrinks a double-array.
std::vector<unit_type>(units_).swap(units_);
std::vector<link_type>(links_).swap(links_);
return true;
}
// Return references to buffers.
std::vector<unit_type> &units_buf() { return units_; }
std::vector<link_type> &links_buf() { return links_; }
private:
// Builds a trie.
void build_trie()
{
// 0 is reserved for the root.
reserve_unit(0);
// To avoid invalid transitions.
extras(0).set_is_used();
units(0).set_offset(1);
units(0).set_label(0);
progress_ = 0;
max_progress_ = num_of_keys_;
if (num_of_keys_)
build_double_array();
// Adjusts all unfixed blocks.
fix_all_blocks();
}
// Builds a double-array.
void build_double_array()
{
std::stack<range_type> range_stack;
range_stack.push(range_type(0, num_of_keys_, 0));
std::vector<range_type> child_ranges;
while (!range_stack.empty())
{
range_type range = range_stack.top();
range_stack.pop();
// Lists labels to child units.
size_type child_begin = range.begin();
labels_.push_back(keys(child_begin, range.depth()));
for (size_type i = range.begin() + 1; i != range.end(); ++i)
{
if (!labels_.back())
progress();
if (keys(i, range.depth()) != labels_.back())
{
labels_.push_back(keys(i, range.depth()));
child_ranges.push_back(
range_type(child_begin, i, range.depth() + 1));
child_begin = i;
}
}
if (!labels_.back())
progress();
child_ranges.push_back(
range_type(child_begin, range.end(), range.depth() + 1));
// Finds a good offset.
base_type offset = find_offset(range.index());
units(range.index()).set_offset(range.index() ^ offset);
links(range.index()).set_child(labels_[0]);
for (size_type i = child_ranges.size(); i > 0; )
{
// Reserves a child unit.
base_type child = offset ^ labels_[--i];
reserve_unit(child);
if (i + 1 < labels_.size())
links(child).set_bros(labels_[i] ^ labels_[i + 1]);
if (!labels_[i])
{
// Sets a value for a leaf unit.
units(range.index()).set_has_leaf();
units(child).set_value(values_ ? values_[range.begin() + i]
: static_cast<value_type>(range.begin() + i));
}
else
{
units(child).set_label(labels_[i]);
child_ranges[i].set_index(child);
range_stack.push(child_ranges[i]);
}
}
extras(offset).set_is_used();
labels_.clear();
child_ranges.clear();
}
}
private:
// Builds a dawg.
void build_dawg()
{
dawg_type dawg;
dawg.build(num_of_keys_, keys_, lengths_, values_, progress_func_);
std::vector<base_type> offset_values(dawg.size(), 0);
// 0 is reserved for the root.
reserve_unit(0);
// To avoid invalid transitions.
extras(0).set_is_used();
units(0).set_offset(1);
units(0).set_label(0);
progress_ = dawg.num_of_states() * 4;
max_progress_ = dawg.num_of_states() * 5;
build_double_array(dawg, offset_values, 0, 0);
// Fixes remaining blocks.
fix_all_blocks();
}
// Builds a double-array.
void build_double_array(const dawg_type &dawg,
std::vector<base_type> &offset_values,
base_type dawg_index, base_type da_index)
{
progress();
if (dawg.is_leaf(dawg_index))
return;
// Already arranged.
base_type dawg_child_index = dawg.child(dawg_index);
if (offset_values[dawg_child_index])
{
base_type offset = offset_values[dawg_child_index] ^ da_index;
if (!(offset & LOWER_MASK) || !(offset & UPPER_MASK))
{
if (dawg.label(dawg_child_index) == '\0')
units(da_index).set_has_leaf();
units(da_index).set_offset(offset);
return;
}
}
// Finds a good offset.
base_type offset = arrange_child_nodes(dawg, dawg_index, da_index);
offset_values[dawg_child_index] = offset;
// Builds a double-array in depth-first order.
do
{
base_type da_child_index =
offset ^ static_cast<uchar_type>(dawg.label(dawg_child_index));
build_double_array(dawg, offset_values,
dawg_child_index, da_child_index);
dawg_child_index = dawg.sibling(dawg_child_index);
} while (dawg_child_index);
}
// Arranges child nodes.
base_type arrange_child_nodes(const dawg_type &dawg,
base_type dawg_index, base_type da_index)
{
labels_.clear();
base_type dawg_child_index = dawg.child(dawg_index);
while (dawg_child_index)
{
labels_.push_back(
static_cast<uchar_type>(dawg.label(dawg_child_index)));
dawg_child_index = dawg.sibling(dawg_child_index);
}
// Finds a good offset.
base_type offset = find_offset(da_index);
units(da_index).set_offset(da_index ^ offset);
links(da_index).set_child(labels_[0]);
dawg_child_index = dawg.child(dawg_index);
for (size_type i = 0; i < labels_.size(); ++i)
{
base_type da_child_index = offset ^ labels_[i];
reserve_unit(da_child_index);
if (i + 1 < labels_.size())
links(da_child_index).set_bros(labels_[i] ^ labels_[i + 1]);
if (dawg.is_leaf(dawg_child_index))
{
units(da_index).set_has_leaf();
units(da_child_index).set_value(dawg.value(dawg_child_index));
}
else
units(da_child_index).set_label(labels_[i]);
dawg_child_index = dawg.sibling(dawg_child_index);
}
extras(offset).set_is_used();
return offset;
}
private:
// Finds a good offset.
base_type find_offset(base_type index) const
{
if (unfixed_index_ >= num_of_units())
return num_of_units() | (index & 0xFF);
// Scans unused units to find a good offset.
base_type unfixed_index = unfixed_index_;
do
{
base_type offset = unfixed_index ^ labels_[0];
if (is_good_offset(index, offset))
return offset;
unfixed_index = extras(unfixed_index).next();
} while (unfixed_index != unfixed_index_);
return num_of_units() | (index & 0xFF);
}
// Checks if a given offset is valid or not.
bool is_good_offset(base_type index, base_type offset) const
{
static const base_type LOWER_MASK = unit_type::OFFSET_MAX - 1;
static const base_type UPPER_MASK = ~LOWER_MASK;
if (extras(offset).is_used())
return false;
base_type relative_offset = index ^ offset;
if ((relative_offset & LOWER_MASK) && (relative_offset & UPPER_MASK))
return false;
// Finds a collision.
for (size_type i = 1; i < labels_.size(); ++i)
{
if (extras(offset ^ labels_[i]).is_fixed())
return false;
}
return true;
}
// Reserves an unused unit.
void reserve_unit(base_type index)
{
if (index >= num_of_units())