This repository has been archived by the owner on May 2, 2023. It is now read-only.
forked from heerme/seql-sequence-learner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
darts.h
1837 lines (1649 loc) · 56.6 KB
/
darts.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_
#include <cstdio>
#include <exception>
#include <new>
#define DARTS_VERSION "0.32"
// DARTS_THROW() throws a <Darts::Exception> whose message starts with the
// file name and the line number. For example, DARTS_THROW("error message") at
// line 123 of "darts.h" throws a <Darts::Exception> which has a pointer to
// "darts.h:123: exception: error message". The message is available by using
// what() as well as that of <std::exception>.
#define DARTS_INT_TO_STR(value) #value
#define DARTS_LINE_TO_STR(line) DARTS_INT_TO_STR(line)
#define DARTS_LINE_STR DARTS_LINE_TO_STR(__LINE__)
#define DARTS_THROW(msg) throw Darts::Details::Exception( \
__FILE__ ":" DARTS_LINE_STR ": exception: " msg)
namespace Darts {
// The following namespace hides the internal types and classes.
namespace Details {
// This header assumes that <int> and <unsigned int> are 32-bit integer types.
//
// Darts-clone keeps values associated with keys. The type of the values is
// <value_type>. Note that the values must be positive integers because the
// most significant bit (MSB) of each value is used to represent whether the
// corresponding unit is a leaf or not. Also, the keys are represented by
// sequences of <char_type>s. <uchar_type> is the unsigned type of <char_type>.
typedef char char_type;
typedef unsigned char uchar_type;
typedef int value_type;
// The main structure of Darts-clone is an array of <DoubleArrayUnit>s, and the
// unit type is actually a wrapper of <id_type>.
typedef unsigned int id_type;
// <progress_func_type> is the type of callback functions for reporting the
// progress of building a dictionary. See also build() of <DoubleArray>.
// The 1st argument receives the progress value and the 2nd argument receives
// the maximum progress value. A usage example is to show the progress
// percentage, 100.0 * (the 1st argument) / (the 2nd argument).
typedef int (*progress_func_type)(std::size_t, std::size_t);
// <DoubleArrayUnit> is the type of double-array units and it is a wrapper of
// <id_type> in practice.
class DoubleArrayUnit {
public:
DoubleArrayUnit() : unit_() {}
// has_leaf() returns whether a leaf unit is immediately derived from the
// unit (true) or not (false).
bool has_leaf() const {
return ((unit_ >> 8) & 1) == 1;
}
// value() returns the value stored in the unit, and thus value() is
// available when and only when the unit is a leaf unit.
value_type value() const {
return static_cast<value_type>(unit_ & ((1U << 31) - 1));
}
// label() returns the label associted with the unit. Note that a leaf unit
// always returns an invalid label. For this feature, leaf unit's label()
// returns an <id_type> that has the MSB of 1.
id_type label() const {
return unit_ & ((1U << 31) | 0xFF);
}
// offset() returns the offset from the unit to its derived units.
id_type offset() const {
return (unit_ >> 10) << ((unit_ & (1U << 9)) >> 6);
}
private:
id_type unit_;
// Copyable.
};
// Darts-clone throws an <Exception> for memory allocation failure, invalid
// arguments or a too large offset. The last case means that there are too many
// keys in the given set of keys. Note that the `msg' of <Exception> must be a
// constant or static string because an <Exception> keeps only a pointer to
// that string.
class Exception : public std::exception {
public:
explicit Exception(const char *msg = NULL) throw() : msg_(msg) {}
Exception(const Exception &rhs) throw() : msg_(rhs.msg_) {}
virtual ~Exception() throw() {}
// <Exception> overrides what() of <std::exception>.
virtual const char *what() const throw() {
return (msg_ != NULL) ? msg_ : "";
}
private:
const char *msg_;
// Disallows operator=.
Exception &operator=(const Exception &);
};
} // namespace Details
// <DoubleArrayImpl> is the interface of Darts-clone. Note that other
// classes should not be accessed from outside.
//
// <DoubleArrayImpl> has 4 template arguments but only the 3rd one is used as
// the type of values. Note that the given <T> is used only from outside, and
// the internal value type is not changed from <Darts::Details::value_type>.
// In build(), given values are casted from <T> to <Darts::Details::value_type>
// by using static_cast. On the other hand, values are casted from
// <Darts::Details::value_type> to <T> in searching dictionaries.
template <typename, typename, typename T, typename>
class DoubleArrayImpl {
public:
// Even if this <value_type> is changed, the internal value type is still
// <Darts::Details::value_type>. Other types, such as 64-bit integer types
// and floating-point number types, should not be used.
typedef T value_type;
// A key is reprenseted by a sequence of <key_type>s. For example,
// exactMatchSearch() takes a <const key_type *>.
typedef Details::char_type key_type;
// In searching dictionaries, the values associated with the matched keys are
// stored into or returned as <result_type>s.
typedef value_type result_type;
// <result_pair_type> enables applications to get the lengths of the matched
// keys in addition to the values.
struct result_pair_type {
value_type value;
std::size_t length;
};
// The constructor initializes member variables with 0 and NULLs.
DoubleArrayImpl() : size_(0), array_(NULL), buf_(NULL) {}
// The destructor frees memory allocated for units and then initializes
// member variables with 0 and NULLs.
virtual ~DoubleArrayImpl() {
clear();
}
// <DoubleArrayImpl> has 2 kinds of set_result()s. The 1st set_result() is to
// set a value to a <value_type>. The 2nd set_result() is to set a value and
// a length to a <result_pair_type>. By using set_result()s, search methods
// can return the 2 kinds of results in the same way.
// Why the set_result()s are non-static? It is for compatibility.
//
// The 1st set_result() takes a length as the 3rd argument but it is not
// used. If a compiler does a good job, codes for getting the length may be
// removed.
void set_result(value_type *result, value_type value, std::size_t) const {
*result = value;
}
// The 2nd set_result() uses both `value' and `length'.
void set_result(result_pair_type *result,
value_type value, std::size_t length) const {
result->value = value;
result->length = length;
}
// set_array() calls clear() in order to free memory allocated to the old
// array and then sets a new array. This function is useful to set a memory-
// mapped array. Note that the array set by set_array() is not freed in
// clear() and the destructor of <DoubleArrayImpl>.
// set_array() can also set the size of the new array but the size is not
// used in search methods. So it works well even if the 2nd argument is 0 or
// omitted. Remember that size() and total_size() returns 0 in such a case.
void set_array(const void *ptr, std::size_t size = 0) {
clear();
array_ = static_cast<const unit_type *>(ptr);
size_ = size;
}
// array() returns a pointer to the array of units.
const void *array() const {
return array_;
}
// clear() frees memory allocated to units and then initializes member
// variables with 0 and NULLs. Note that clear() does not free memory if the
// array of units was set by set_array(). In such a case, `array_' is not
// NULL and `buf_' is NULL.
void clear() {
size_ = 0;
array_ = NULL;
if (buf_ != NULL) {
delete[] buf_;
buf_ = NULL;
}
}
// unit_size() returns the size of each unit. The size must be 4 bytes.
std::size_t unit_size() const {
return sizeof(unit_type);
}
// size() returns the number of units. It can be 0 if set_array() is used.
std::size_t size() const {
return size_;
}
// total_size() returns the number of bytes allocated to the array of units.
// It can be 0 if set_array() is used.
std::size_t total_size() const {
return unit_size() * size();
}
// nonzero_size() exists for compatibility. It always returns the number of
// units because it takes long time to count the number of non-zero units.
std::size_t nonzero_size() const {
return size();
}
// build() constructs a dictionary from given key-value pairs. If `lengths'
// is NULL, `keys' is handled as an array of zero-terminated strings. If
// `values' is NULL, the index in `keys' is associated with each key, i.e.
// the ith key has (i - 1) as its value.
// Note that the key-value pairs must be arranged in key order and the values
// must not be negative. Also, if there are duplicate keys, only the first
// pair will be stored in the resultant dictionary.
// `progress_func' is a pointer to a callback function. If it is not NULL,
// it will be called in build() so that the caller can check the progress of
// dictionary construction. For details, please see the definition of
// <Darts::Details::progress_func_type>.
// The return value of build() is 0, and it indicates the success of the
// operation. Otherwise, build() throws a <Darts::Exception>, which is a
// derived class of <std::exception>.
// build() uses another construction algorithm if `values' is not NULL. In
// this case, Darts-clone uses a Directed Acyclic Word Graph (DAWG) instead
// of a trie because a DAWG is likely to be more compact than a trie.
int build(std::size_t num_keys, const key_type *const *keys,
const std::size_t *lengths = NULL, const value_type *values = NULL,
Details::progress_func_type progress_func = NULL);
// open() reads an array of units from the specified file. And if it goes
// well, the old array will be freed and replaced with the new array read
// from the file. `offset' specifies the number of bytes to be skipped before
// reading an array. `size' specifies the number of bytes to be read from the
// file. If the `size' is 0, the whole file will be read.
// open() returns 0 iff the operation succeeds. Otherwise, it returns a
// non-zero value or throws a <Darts::Exception>. The exception is thrown
// when and only when a memory allocation fails.
int open(const char *file_name, const char *mode = "rb",
std::size_t offset = 0, std::size_t size = 0);
// save() writes the array of units into the specified file. `offset'
// specifies the number of bytes to be skipped before writing the array.
// open() returns 0 iff the operation succeeds. Otherwise, it returns a
// non-zero value.
int save(const char *file_name, const char *mode = "wb",
std::size_t offset = 0) const;
// The 1st exactMatchSearch() tests whether the given key exists or not, and
// if it exists, its value and length are set to `result'. Otherwise, the
// value and the length of `result' are set to -1 and 0 respectively.
// Note that if `length' is 0, `key' is handled as a zero-terminated string.
// `node_pos' specifies the start position of matching. This argument enables
// the combination of exactMatchSearch() and traverse(). For example, if you
// want to test "xyzA", "xyzBC", and "xyzDE", you can use traverse() to get
// the node position corresponding to "xyz" and then you can use
// exactMatchSearch() to test "A", "BC", and "DE" from that position.
// Note that the length of `result' indicates the length from the `node_pos'.
// In the above example, the lengths are { 1, 2, 2 }, not { 4, 5, 5 }.
template <class U>
void exactMatchSearch(const key_type *key, U &result,
std::size_t length = 0, std::size_t node_pos = 0) const {
result = exactMatchSearch<U>(key, length, node_pos);
}
// The 2nd exactMatchSearch() returns a result instead of updating the 2nd
// argument. So, the following exactMatchSearch() has only 3 arguments.
template <class U>
inline U exactMatchSearch(const key_type *key, std::size_t length = 0,
std::size_t node_pos = 0) const;
// commonPrefixSearch() searches for keys which match a prefix of the given
// string. If `length' is 0, `key' is handled as a zero-terminated string.
// The values and the lengths of at most `max_num_results' matched keys are
// stored in `results'. commonPrefixSearch() returns the number of matched
// keys. Note that the return value can be larger than `max_num_results' if
// there are more than `max_num_results' matches. If you want to get all the
// results, allocate more spaces and call commonPrefixSearch() again.
// `node_pos' works as well as in exactMatchSearch().
template <class U>
inline std::size_t commonPrefixSearch(const key_type *key, U *results,
std::size_t max_num_results, std::size_t length = 0,
std::size_t node_pos = 0) const;
// In Darts-clone, a dictionary is a deterministic finite-state automaton
// (DFA) and traverse() tests transitions on the DFA. The initial state is
// `node_pos' and traverse() chooses transitions labeled key[key_pos],
// key[key_pos + 1], ... in order. If there is not a transition labeled
// key[key_pos + i], traverse() terminates the transitions at that state and
// returns -2. Otherwise, traverse() ends without a termination and returns
// -1 or a nonnegative value, -1 indicates that the final state was not an
// accept state. When a nonnegative value is returned, it is the value
// associated with the final accept state. That is, traverse() returns the
// value associated with the given key if it exists. Note that traverse()
// updates `node_pos' and `key_pos' after each transition.
inline value_type traverse(const key_type *key, std::size_t &node_pos,
std::size_t &key_pos, std::size_t length = 0) const;
private:
typedef Details::uchar_type uchar_type;
typedef Details::id_type id_type;
typedef Details::DoubleArrayUnit unit_type;
std::size_t size_;
const unit_type *array_;
unit_type *buf_;
// Disallows copy and assignment.
DoubleArrayImpl(const DoubleArrayImpl &);
DoubleArrayImpl &operator=(const DoubleArrayImpl &);
};
// <DoubleArray> is the typical instance of <DoubleArrayImpl>. It uses <int>
// as the type of values and it is suitable for most cases.
typedef DoubleArrayImpl<void, void, int, void> DoubleArray;
// The interface section ends here. For using Darts-clone, there is no need
// to read the remaining section, which gives the implementation of
// Darts-clone.
//
// Member functions of DoubleArrayImpl (except build()).
//
template <typename A, typename B, typename T, typename C>
int DoubleArrayImpl<A, B, T, C>::open(const char *file_name,
const char *mode, std::size_t offset, std::size_t size) {
#ifdef _MSC_VER
std::FILE *file;
if (::fopen_s(&file, file_name, mode) != 0) {
return -1;
}
#else
std::FILE *file = std::fopen(file_name, mode);
if (file == NULL) {
return -1;
}
#endif
if (size == 0) {
if (std::fseek(file, 0, SEEK_END) != 0) {
std::fclose(file);
return -1;
}
size = std::ftell(file) - offset;
}
size /= unit_size();
if (size < 256 || (size & 0xFF) != 0) {
std::fclose(file);
return -1;
}
if (std::fseek(file, offset, SEEK_SET) != 0) {
std::fclose(file);
return -1;
}
unit_type units[256];
if (std::fread(units, unit_size(), 256, file) != 256) {
std::fclose(file);
return -1;
}
if (units[0].label() != '\0' || units[0].has_leaf() ||
units[0].offset() == 0 || units[0].offset() >= 512) {
std::fclose(file);
return -1;
}
for (id_type i = 1; i < 256; ++i) {
if (units[i].label() <= 0xFF && units[i].offset() >= size) {
std::fclose(file);
return -1;
}
}
unit_type *buf;
try {
buf = new unit_type[size];
for (id_type i = 0; i < 256; ++i) {
buf[i] = units[i];
}
} catch (const std::bad_alloc &) {
std::fclose(file);
DARTS_THROW("failed to open double-array: std::bad_alloc");
}
if (size > 256) {
if (std::fread(buf + 256, unit_size(), size - 256, file) != size - 256) {
std::fclose(file);
delete[] buf;
return -1;
}
}
std::fclose(file);
clear();
size_ = size;
array_ = buf;
buf_ = buf;
return 0;
}
template <typename A, typename B, typename T, typename C>
int DoubleArrayImpl<A, B, T, C>::save(const char *file_name,
const char *mode, std::size_t offset) const {
if (size() == 0) {
return -1;
}
#ifdef _MSC_VER
std::FILE *file;
if (::fopen_s(&file, file_name, mode) != 0) {
return -1;
}
#else
std::FILE *file = std::fopen(file_name, mode);
if (file == NULL) {
return -1;
}
#endif
if (std::fseek(file, offset, SEEK_SET) != 0) {
std::fclose(file);
return -1;
}
if (std::fwrite(array_, unit_size(), size(), file) != size()) {
std::fclose(file);
return -1;
}
std::fclose(file);
return 0;
}
template <typename A, typename B, typename T, typename C>
template <typename U>
inline U DoubleArrayImpl<A, B, T, C>::exactMatchSearch(const key_type *key,
std::size_t length, std::size_t node_pos) const {
U result;
set_result(&result, static_cast<value_type>(-1), 0);
unit_type unit = array_[node_pos];
if (length != 0) {
for (std::size_t i = 0; i < length; ++i) {
node_pos ^= unit.offset() ^ static_cast<uchar_type>(key[i]);
unit = array_[node_pos];
if (unit.label() != static_cast<uchar_type>(key[i])) {
return result;
}
}
} else {
for (; key[length] != '\0'; ++length) {
node_pos ^= unit.offset() ^ static_cast<uchar_type>(key[length]);
unit = array_[node_pos];
if (unit.label() != static_cast<uchar_type>(key[length])) {
return result;
}
}
}
if (!unit.has_leaf()) {
return result;
}
unit = array_[node_pos ^ unit.offset()];
set_result(&result, static_cast<value_type>(unit.value()), length);
return result;
}
template <typename A, typename B, typename T, typename C>
template <typename U>
inline std::size_t DoubleArrayImpl<A, B, T, C>::commonPrefixSearch(
const key_type *key, U *results, std::size_t max_num_results,
std::size_t length, std::size_t node_pos) const {
std::size_t num_results = 0;
unit_type unit = array_[node_pos];
node_pos ^= unit.offset();
if (length != 0) {
for (std::size_t i = 0; i < length; ++i) {
node_pos ^= static_cast<uchar_type>(key[i]);
unit = array_[node_pos];
if (unit.label() != static_cast<uchar_type>(key[i])) {
return num_results;
}
node_pos ^= unit.offset();
if (unit.has_leaf()) {
if (num_results < max_num_results) {
set_result(&results[num_results], static_cast<value_type>(
array_[node_pos].value()), i + 1);
}
++num_results;
}
}
} else {
for (; key[length] != '\0'; ++length) {
node_pos ^= static_cast<uchar_type>(key[length]);
unit = array_[node_pos];
if (unit.label() != static_cast<uchar_type>(key[length])) {
return num_results;
}
node_pos ^= unit.offset();
if (unit.has_leaf()) {
if (num_results < max_num_results) {
set_result(&results[num_results], static_cast<value_type>(
array_[node_pos].value()), length + 1);
}
++num_results;
}
}
}
return num_results;
}
template <typename A, typename B, typename T, typename C>
inline typename DoubleArrayImpl<A, B, T, C>::value_type
DoubleArrayImpl<A, B, T, C>::traverse(const key_type *key,
std::size_t &node_pos, std::size_t &key_pos, std::size_t length) const {
id_type id = static_cast<id_type>(node_pos);
unit_type unit = array_[id];
if (length != 0) {
for (; key_pos < length; ++key_pos) {
id ^= unit.offset() ^ static_cast<uchar_type>(key[key_pos]);
unit = array_[id];
if (unit.label() != static_cast<uchar_type>(key[key_pos])) {
return static_cast<value_type>(-2);
}
node_pos = id;
}
} else {
for (; key[key_pos] != '\0'; ++key_pos) {
id ^= unit.offset() ^ static_cast<uchar_type>(key[key_pos]);
unit = array_[id];
if (unit.label() != static_cast<uchar_type>(key[key_pos])) {
return static_cast<value_type>(-2);
}
node_pos = id;
}
}
if (!unit.has_leaf()) {
return static_cast<value_type>(-1);
}
unit = array_[id ^ unit.offset()];
return static_cast<value_type>(unit.value());
}
namespace Details {
//
// Memory management of array.
//
template <typename T>
class AutoArray {
public:
explicit AutoArray(T *array = NULL) : array_(array) {}
~AutoArray() {
clear();
}
const T &operator[](std::size_t id) const {
return array_[id];
}
T &operator[](std::size_t id) {
return array_[id];
}
bool empty() const {
return array_ == NULL;
}
void clear() {
if (array_ != NULL) {
delete[] array_;
array_ = NULL;
}
}
void swap(AutoArray *array) {
T *temp = array_;
array_ = array->array_;
array->array_ = temp;
}
void reset(T *array = NULL) {
AutoArray(array).swap(this);
}
private:
T *array_;
// Disallows copy and assignment.
AutoArray(const AutoArray &);
AutoArray &operator=(const AutoArray &);
};
//
// Memory management of resizable array.
//
template <typename T>
class AutoPool {
public:
AutoPool() : buf_(), size_(0), capacity_(0) {}
~AutoPool() {
clear();
}
const T &operator[](std::size_t id) const {
return *(reinterpret_cast<const T *>(&buf_[0]) + id);
}
T &operator[](std::size_t id) {
return *(reinterpret_cast<T *>(&buf_[0]) + id);
}
bool empty() const {
return size_ == 0;
}
std::size_t size() const {
return size_;
}
void clear() {
resize(0);
buf_.clear();
size_ = 0;
capacity_ = 0;
}
void push_back(const T &value) {
append(value);
}
void pop_back() {
(*this)[--size_].~T();
}
void append() {
if (size_ == capacity_) {
resize_buf(size_ + 1);
}
new(&(*this)[size_++]) T;
}
void append(const T &value) {
if (size_ == capacity_) {
resize_buf(size_ + 1);
}
new(&(*this)[size_++]) T(value);
}
void resize(std::size_t size) {
while (size_ > size) {
(*this)[--size_].~T();
}
if (size > capacity_) {
resize_buf(size);
}
while (size_ < size) {
new(&(*this)[size_++]) T;
}
}
void resize(std::size_t size, const T &value) {
while (size_ > size) {
(*this)[--size_].~T();
}
if (size > capacity_) {
resize_buf(size);
}
while (size_ < size) {
new(&(*this)[size_++]) T(value);
}
}
void reserve(std::size_t size) {
if (size > capacity_) {
resize_buf(size);
}
}
private:
AutoArray<char> buf_;
std::size_t size_;
std::size_t capacity_;
// Disallows copy and assignment.
AutoPool(const AutoPool &);
AutoPool &operator=(const AutoPool &);
void resize_buf(std::size_t size);
};
template <typename T>
void AutoPool<T>::resize_buf(std::size_t size) {
std::size_t capacity;
if (size >= capacity_ * 2) {
capacity = size;
} else {
capacity = 1;
while (capacity < size) {
capacity <<= 1;
}
}
AutoArray<char> buf;
try {
buf.reset(new char[sizeof(T) * capacity]);
} catch (const std::bad_alloc &) {
DARTS_THROW("failed to resize pool: std::bad_alloc");
}
if (size_ > 0) {
T *src = reinterpret_cast<T *>(&buf_[0]);
T *dest = reinterpret_cast<T *>(&buf[0]);
for (std::size_t i = 0; i < size_; ++i) {
new(&dest[i]) T(src[i]);
src[i].~T();
}
}
buf_.swap(&buf);
capacity_ = capacity;
}
//
// Memory management of stack.
//
template <typename T>
class AutoStack {
public:
AutoStack() : pool_() {}
~AutoStack() {
clear();
}
const T &top() const {
return pool_[size() - 1];
}
T &top() {
return pool_[size() - 1];
}
bool empty() const {
return pool_.empty();
}
std::size_t size() const {
return pool_.size();
}
void push(const T &value) {
pool_.push_back(value);
}
void pop() {
pool_.pop_back();
}
void clear() {
pool_.clear();
}
private:
AutoPool<T> pool_;
// Disallows copy and assignment.
AutoStack(const AutoStack &);
AutoStack &operator=(const AutoStack &);
};
//
// Succinct bit vector.
//
class BitVector {
public:
BitVector() : units_(), ranks_(), num_ones_(0), size_(0) {}
~BitVector() {
clear();
}
bool operator[](std::size_t id) const {
return (units_[id / UNIT_SIZE] >> (id % UNIT_SIZE) & 1) == 1;
}
id_type rank(std::size_t id) const {
std::size_t unit_id = id / UNIT_SIZE;
return ranks_[unit_id] + pop_count(units_[unit_id]
& (~0U >> (UNIT_SIZE - (id % UNIT_SIZE) - 1)));
}
void set(std::size_t id, bool bit) {
if (bit) {
units_[id / UNIT_SIZE] |= 1U << (id % UNIT_SIZE);
} else {
units_[id / UNIT_SIZE] &= ~(1U << (id % UNIT_SIZE));
}
}
bool empty() const {
return units_.empty();
}
std::size_t num_ones() const {
return num_ones_;
}
std::size_t size() const {
return size_;
}
void append() {
if ((size_ % UNIT_SIZE) == 0) {
units_.append(0);
}
++size_;
}
void build();
void clear() {
units_.clear();
ranks_.clear();
}
private:
enum { UNIT_SIZE = sizeof(id_type) * 8 };
AutoPool<id_type> units_;
AutoArray<id_type> ranks_;
std::size_t num_ones_;
std::size_t size_;
// Disallows copy and assignment.
BitVector(const BitVector &);
BitVector &operator=(const BitVector &);
static id_type pop_count(id_type unit) {
unit = ((unit & 0xAAAAAAAA) >> 1) + (unit & 0x55555555);
unit = ((unit & 0xCCCCCCCC) >> 2) + (unit & 0x33333333);
unit = ((unit >> 4) + unit) & 0x0F0F0F0F;
unit += unit >> 8;
unit += unit >> 16;
return unit & 0xFF;
}
};
inline void BitVector::build() {
try {
ranks_.reset(new id_type[units_.size()]);
} catch (const std::bad_alloc &) {
DARTS_THROW("failed to build rank index: std::bad_alloc");
}
num_ones_ = 0;
for (std::size_t i = 0; i < units_.size(); ++i) {
ranks_[i] = num_ones_;
num_ones_ += pop_count(units_[i]);
}
}
//
// Keyset.
//
template <typename T>
class Keyset {
public:
Keyset(std::size_t num_keys, const char_type *const *keys,
const std::size_t *lengths, const T *values) :
num_keys_(num_keys), keys_(keys), lengths_(lengths), values_(values) {}
std::size_t num_keys() const {
return num_keys_;
}
const char_type *keys(std::size_t id) const {
return keys_[id];
}
uchar_type keys(std::size_t key_id, std::size_t char_id) const {
if (has_lengths() && char_id >= lengths_[key_id]) {
return '\0';
}
return keys_[key_id][char_id];
}
bool has_lengths() const {
return lengths_ != NULL;
}
std::size_t lengths(std::size_t id) const {
if (has_lengths()) {
return lengths_[id];
}
std::size_t length = 0;
while (keys_[id][length] != '\0') {
++length;
}
return length;
}
bool has_values() const {
return values_ != NULL;
}
value_type values(std::size_t id) const {
if (has_values()) {
return static_cast<value_type>(values_[id]);
}
return static_cast<value_type>(id);
}
private:
std::size_t num_keys_;
const char_type *const *keys_;
const std::size_t *lengths_;
const T *values_;
// Disallows copy and assignment.
Keyset(const Keyset &);
Keyset &operator=(const Keyset &);
};
//
// Node of Directed Acyclic Word Graph (DAWG).
//
class DawgNode {
public:
DawgNode() : child_(0), sibling_(0), label_('\0'),
is_state_(false), has_sibling_(false) {}
void set_child(id_type child) {
child_ = child;
}
void set_sibling(id_type sibling) {
sibling_ = sibling;
}
void set_value(value_type value) {
child_ = value;
}
void set_label(uchar_type label) {
label_ = label;
}
void set_is_state(bool is_state) {
is_state_ = is_state;
}
void set_has_sibling(bool has_sibling) {
has_sibling_ = has_sibling;
}
id_type child() const {
return child_;
}
id_type sibling() const {
return sibling_;
}
value_type value() const {
return static_cast<value_type>(child_);
}
uchar_type label() const {
return label_;
}
bool is_state() const {
return is_state_;
}
bool has_sibling() const {
return has_sibling_;
}
id_type unit() const {
if (label_ == '\0') {
return (child_ << 1) | (has_sibling_ ? 1 : 0);
}
return (child_ << 2) | (is_state_ ? 2 : 0) | (has_sibling_ ? 1 : 0);
}
private:
id_type child_;
id_type sibling_;
uchar_type label_;
bool is_state_;
bool has_sibling_;
// Copyable.
};
//
// Fixed unit of Directed Acyclic Word Graph (DAWG).
//
class DawgUnit {
public:
explicit DawgUnit(id_type unit = 0) : unit_(unit) {}
DawgUnit(const DawgUnit &unit) : unit_(unit.unit_) {}
DawgUnit &operator=(id_type unit) {
unit_ = unit;
return *this;
}
id_type unit() const {
return unit_;
}
id_type child() const {
return unit_ >> 2;
}
bool has_sibling() const {
return (unit_ & 1) == 1;
}
value_type value() const {
return static_cast<value_type>(unit_ >> 1);
}
bool is_state() const {
return (unit_ & 2) == 2;
}
private:
id_type unit_;
// Copyable.
};
//
// Directed Acyclic Word Graph (DAWG) builder.
//