Debian Codegraph @

deps/darts-clone-0.32h/include/darts.h

raw symbols SCIP
1 #ifndef DARTS_H_
2 #define DARTS_H_
3
4 #include <cstdio>
5 #include <cstring>
6 #include <exception>
7 #include <new>
8
9 #define DARTS_VERSION "0.32"
10
11 // DARTS_THROW() throws a <Darts::Exception> whose message starts with the
12 // file name and the line number. For example, DARTS_THROW("error message") at
13 // line 123 of "darts.h" throws a <Darts::Exception> which has a pointer to
14 // "darts.h:123: exception: error message". The message is available by using
15 // what() as well as that of <std::exception>.
16 #define DARTS_INT_TO_STR(value) #value
17 #define DARTS_LINE_TO_STR(line) DARTS_INT_TO_STR(line)
18 #define DARTS_LINE_STR DARTS_LINE_TO_STR(__LINE__)
19 #define DARTS_THROW(msg) throw Darts::Details::Exception( \
20 __FILE__ ":" DARTS_LINE_STR ": exception: " msg)
21
22 namespace Darts {
23
24 // The following namespace hides the internal types and classes.
25 namespace Details {
26
27 // This header assumes that <int> and <unsigned int> are 32-bit integer types.
28 //
29 // Darts-clone keeps values associated with keys. The type of the values is
30 // <value_type>. Note that the values must be positive integers because the
31 // most significant bit (MSB) of each value is used to represent whether the
32 // corresponding unit is a leaf or not. Also, the keys are represented by
33 // sequences of <char_type>s. <uchar_type> is the unsigned type of <char_type>.
34 typedef char char_type;
35 typedef unsigned char uchar_type;
36 typedef int value_type;
37
38 // The main structure of Darts-clone is an array of <DoubleArrayUnit>s, and the
39 // unit type is actually a wrapper of <id_type>.
40 typedef unsigned int id_type;
41
42 // <progress_func_type> is the type of callback functions for reporting the
43 // progress of building a dictionary. See also build() of <DoubleArray>.
44 // The 1st argument receives the progress value and the 2nd argument receives
45 // the maximum progress value. A usage example is to show the progress
46 // percentage, 100.0 * (the 1st argument) / (the 2nd argument).
47 typedef int (*progress_func_type)(std::size_t, std::size_t);
48
49 // <DoubleArrayUnit> is the type of double-array units and it is a wrapper of
50 // <id_type> in practice.
51 class DoubleArrayUnit {
52 public:
53 DoubleArrayUnit() : unit_() {}
54
55 // has_leaf() returns whether a leaf unit is immediately derived from the
56 // unit (true) or not (false).
57 bool has_leaf() const {
58 return ((unit_ >> 8) & 1) == 1;
59 }
60 // value() returns the value stored in the unit, and thus value() is
61 // available when and only when the unit is a leaf unit.
62 value_type value() const {
63 return static_cast<value_type>(unit_ & ((1U << 31) - 1));
64 }
65
66 // label() returns the label associted with the unit. Note that a leaf unit
67 // always returns an invalid label. For this feature, leaf unit's label()
68 // returns an <id_type> that has the MSB of 1.
69 id_type label() const {
70 return unit_ & ((1U << 31) | 0xFF);
71 }
72 // offset() returns the offset from the unit to its derived units.
73 id_type offset() const {
74 return (unit_ >> 10) << ((unit_ & (1U << 9)) >> 6);
75 }
76
77 private:
78 id_type unit_;
79
80 // Copyable.
81 };
82
83 // Darts-clone throws an <Exception> for memory allocation failure, invalid
84 // arguments or a too large offset. The last case means that there are too many
85 // keys in the given set of keys. Note that the `msg' of <Exception> must be a
86 // constant or static string because an <Exception> keeps only a pointer to
87 // that string.
88 class Exception : public std::exception {
89 public:
90 explicit Exception(const char *msg = NULL) throw() : msg_(msg) {}
91 Exception(const Exception &rhs) throw() : msg_(rhs.msg_) {}
92 virtual ~Exception() throw() {}
93
94 // <Exception> overrides what() of <std::exception>.
95 virtual const char *what() const throw() {
96 return (msg_ != NULL) ? msg_ : "";
97 }
98
99 private:
100 const char *msg_;
101
102 // Disallows operator=.
103 Exception &operator=(const Exception &);
104 };
105
106 } // namespace Details
107
108 // <DoubleArrayImpl> is the interface of Darts-clone. Note that other
109 // classes should not be accessed from outside.
110 //
111 // <DoubleArrayImpl> has 4 template arguments but only the 3rd one is used as
112 // the type of values. Note that the given <T> is used only from outside, and
113 // the internal value type is not changed from <Darts::Details::value_type>.
114 // In build(), given values are casted from <T> to <Darts::Details::value_type>
115 // by using static_cast. On the other hand, values are casted from
116 // <Darts::Details::value_type> to <T> in searching dictionaries.
117 template <typename, typename, typename T, typename>
118 class DoubleArrayImpl {
119 public:
120 // Even if this <value_type> is changed, the internal value type is still
121 // <Darts::Details::value_type>. Other types, such as 64-bit integer types
122 // and floating-point number types, should not be used.
123 typedef T value_type;
124 // A key is reprenseted by a sequence of <key_type>s. For example,
125 // exactMatchSearch() takes a <const key_type *>.
126 typedef Details::char_type key_type;
127 // In searching dictionaries, the values associated with the matched keys are
128 // stored into or returned as <result_type>s.
129 typedef value_type result_type;
130
131 // <result_pair_type> enables applications to get the lengths of the matched
132 // keys in addition to the values.
133 struct result_pair_type {
134 value_type value;
135 std::size_t length;
136 };
137
138 // The constructor initializes member variables with 0 and NULLs.
139 DoubleArrayImpl() : size_(0), array_(NULL), buf_(NULL) {}
140 // The destructor frees memory allocated for units and then initializes
141 // member variables with 0 and NULLs.
142 virtual ~DoubleArrayImpl() {
143 clear();
144 }
145
146 // <DoubleArrayImpl> has 2 kinds of set_result()s. The 1st set_result() is to
147 // set a value to a <value_type>. The 2nd set_result() is to set a value and
148 // a length to a <result_pair_type>. By using set_result()s, search methods
149 // can return the 2 kinds of results in the same way.
150 // Why the set_result()s are non-static? It is for compatibility.
151 //
152 // The 1st set_result() takes a length as the 3rd argument but it is not
153 // used. If a compiler does a good job, codes for getting the length may be
154 // removed.
155 void set_result(value_type *result, value_type value, std::size_t) const {
156 *result = value;
157 }
158 // The 2nd set_result() uses both `value' and `length'.
159 void set_result(result_pair_type *result,
160 value_type value, std::size_t length) const {
161 result->value = value;
162 result->length = length;
163 }
164
165 // set_array() calls clear() in order to free memory allocated to the old
166 // array and then sets a new array. This function is useful to set a memory-
167 // mapped array. Note that the array set by set_array() is not freed in
168 // clear() and the destructor of <DoubleArrayImpl>.
169 // set_array() can also set the size of the new array but the size is not
170 // used in search methods. So it works well even if the 2nd argument is 0 or
171 // omitted. Remember that size() and total_size() returns 0 in such a case.
172 void set_array(const void *ptr, std::size_t size = 0) {
173 clear();
174 array_ = static_cast<const unit_type *>(ptr);
175 size_ = size;
176 }
177 void copy_array(const void* ptr, std::size_t num_bytes) {
178 clear();
179 const std::size_t extra_padding = num_bytes % unit_size() == 0 ? 0 : 1;
180 size_ = num_bytes / unit_size() + extra_padding;
181 buf_ = new unit_type[size_];
182 std::memcpy(buf_, ptr, num_bytes);
183 array_ = buf_;
184 }
185 // array() returns a pointer to the array of units.
186 const void *array() const {
187 return array_;
188 }
189
190 // clear() frees memory allocated to units and then initializes member
191 // variables with 0 and NULLs. Note that clear() does not free memory if the
192 // array of units was set by set_array(). In such a case, `array_' is not
193 // NULL and `buf_' is NULL.
194 void clear() {
195 size_ = 0;
196 array_ = NULL;
197 if (buf_ != NULL) {
198 delete[] buf_;
199 buf_ = NULL;
200 }
201 }
202
203 // unit_size() returns the size of each unit. The size must be 4 bytes.
204 std::size_t unit_size() const {
205 return sizeof(unit_type);
206 }
207 // size() returns the number of units. It can be 0 if set_array() is used.
208 std::size_t size() const {
209 return size_;
210 }
211 // total_size() returns the number of bytes allocated to the array of units.
212 // It can be 0 if set_array() is used.
213 std::size_t total_size() const {
214 return unit_size() * size();
215 }
216 // nonzero_size() exists for compatibility. It always returns the number of
217 // units because it takes long time to count the number of non-zero units.
218 std::size_t nonzero_size() const {
219 return size();
220 }
221
222 // build() constructs a dictionary from given key-value pairs. If `lengths'
223 // is NULL, `keys' is handled as an array of zero-terminated strings. If
224 // `values' is NULL, the index in `keys' is associated with each key, i.e.
225 // the ith key has (i - 1) as its value.
226 // Note that the key-value pairs must be arranged in key order and the values
227 // must not be negative. Also, if there are duplicate keys, only the first
228 // pair will be stored in the resultant dictionary.
229 // `progress_func' is a pointer to a callback function. If it is not NULL,
230 // it will be called in build() so that the caller can check the progress of
231 // dictionary construction. For details, please see the definition of
232 // <Darts::Details::progress_func_type>.
233 // The return value of build() is 0, and it indicates the success of the
234 // operation. Otherwise, build() throws a <Darts::Exception>, which is a
235 // derived class of <std::exception>.
236 // build() uses another construction algorithm if `values' is not NULL. In
237 // this case, Darts-clone uses a Directed Acyclic Word Graph (DAWG) instead
238 // of a trie because a DAWG is likely to be more compact than a trie.
239 int build(std::size_t num_keys, const key_type * const *keys,
240 const std::size_t *lengths = NULL, const value_type *values = NULL,
241 Details::progress_func_type progress_func = NULL);
242
243 // open() reads an array of units from the specified file. And if it goes
244 // well, the old array will be freed and replaced with the new array read
245 // from the file. `offset' specifies the number of bytes to be skipped before
246 // reading an array. `size' specifies the number of bytes to be read from the
247 // file. If the `size' is 0, the whole file will be read.
248 // open() returns 0 iff the operation succeeds. Otherwise, it returns a
249 // non-zero value or throws a <Darts::Exception>. The exception is thrown
250 // when and only when a memory allocation fails.
251 int open(const char *file_name, const char *mode = "rb",
252 std::size_t offset = 0, std::size_t size = 0);
253 // save() writes the array of units into the specified file. `offset'
254 // specifies the number of bytes to be skipped before writing the array.
255 // open() returns 0 iff the operation succeeds. Otherwise, it returns a
256 // non-zero value.
257 int save(const char *file_name, const char *mode = "wb",
258 std::size_t offset = 0) const;
259
260 // The 1st exactMatchSearch() tests whether the given key exists or not, and
261 // if it exists, its value and length are set to `result'. Otherwise, the
262 // value and the length of `result' are set to -1 and 0 respectively.
263 // Note that if `length' is 0, `key' is handled as a zero-terminated string.
264 // `node_pos' specifies the start position of matching. This argument enables
265 // the combination of exactMatchSearch() and traverse(). For example, if you
266 // want to test "xyzA", "xyzBC", and "xyzDE", you can use traverse() to get
267 // the node position corresponding to "xyz" and then you can use
268 // exactMatchSearch() to test "A", "BC", and "DE" from that position.
269 // Note that the length of `result' indicates the length from the `node_pos'.
270 // In the above example, the lengths are { 1, 2, 2 }, not { 4, 5, 5 }.
271 template <class U>
272 void exactMatchSearch(const key_type *key, U &result,
273 std::size_t length = 0, std::size_t node_pos = 0) const {
274 result = exactMatchSearch<U>(key, length, node_pos);
275 }
276 // The 2nd exactMatchSearch() returns a result instead of updating the 2nd
277 // argument. So, the following exactMatchSearch() has only 3 arguments.
278 template <class U>
279 inline U exactMatchSearch(const key_type *key, std::size_t length = 0,
280 std::size_t node_pos = 0) const;
281
282 // commonPrefixSearch() searches for keys which match a prefix of the given
283 // string. If `length' is 0, `key' is handled as a zero-terminated string.
284 // The values and the lengths of at most `max_num_results' matched keys are
285 // stored in `results'. commonPrefixSearch() returns the number of matched
286 // keys. Note that the return value can be larger than `max_num_results' if
287 // there are more than `max_num_results' matches. If you want to get all the
288 // results, allocate more spaces and call commonPrefixSearch() again.
289 // `node_pos' works as well as in exactMatchSearch().
290 template <class U>
291 inline std::size_t commonPrefixSearch(const key_type *key, U *results,
292 std::size_t max_num_results, std::size_t length = 0,
293 std::size_t node_pos = 0) const;
294
295 // The 1st commonLongestPrefixSearch() earches for the longest key which
296 // matches a prefix of the given string, and if it exists, its value and
297 // length are set to `result'. Otherwise, the value and the length of
298 //`result' are set to -1 and 0 respectively. Note that if `length' is 0,
299 // `key' is handled as a zero-terminated string. `node_pos' works as well as
300 // in exactMatchSearch().
301 template <class U>
302 void commonLongestPrefixSearch(const key_type *key, U &result,
303 std::size_t length = 0, std::size_t node_pos = 0) const {
304 result = commonLongestPrefixSearch<U>(key, length, node_pos);
305 }
306 // The 2nd commonLongestPrefixSearch() returns a result instead of updating
307 // the 2nd argument. So, the following commonLongestPrefixSearch() has only
308 // 3 arguments.
309 template <class U>
310 inline U commonLongestPrefixSearch(const key_type *key,
311 std::size_t length = 0, std::size_t node_pos = 0) const;
312
313 // In Darts-clone, a dictionary is a deterministic finite-state automaton
314 // (DFA) and traverse() tests transitions on the DFA. The initial state is
315 // `node_pos' and traverse() chooses transitions labeled key[key_pos],
316 // key[key_pos + 1], ... in order. If there is not a transition labeled
317 // key[key_pos + i], traverse() terminates the transitions at that state and
318 // returns -2. Otherwise, traverse() ends without a termination and returns
319 // -1 or a nonnegative value, -1 indicates that the final state was not an
320 // accept state. When a nonnegative value is returned, it is the value
321 // associated with the final accept state. That is, traverse() returns the
322 // value associated with the given key if it exists. Note that traverse()
323 // updates `node_pos' and `key_pos' after each transition.
324 inline value_type traverse(const key_type *key, std::size_t &node_pos,
325 std::size_t &key_pos, std::size_t length = 0) const;
326
327 bool validate(value_type max_value_limit = -1) const;
328
329 private:
330 typedef Details::uchar_type uchar_type;
331 typedef Details::id_type id_type;
332 typedef Details::DoubleArrayUnit unit_type;
333
334 std::size_t size_;
335 const unit_type *array_;
336 unit_type *buf_;
337
338 // Disallows copy and assignment.
339 DoubleArrayImpl(const DoubleArrayImpl &);
340 DoubleArrayImpl &operator=(const DoubleArrayImpl &);
341 };
342
343 // <DoubleArray> is the typical instance of <DoubleArrayImpl>. It uses <int>
344 // as the type of values and it is suitable for most cases.
345 typedef DoubleArrayImpl<void, void, int, void> DoubleArray;
346
347 // The interface section ends here. For using Darts-clone, there is no need
348 // to read the remaining section, which gives the implementation of
349 // Darts-clone.
350
351 //
352 // Member functions of DoubleArrayImpl (except build()).
353 //
354
355 template <typename A, typename B, typename T, typename C>
356 int DoubleArrayImpl<A, B, T, C>::open(const char *file_name,
357 const char *mode, std::size_t offset, std::size_t size) {
358 #ifdef _MSC_VER
359 std::FILE *file;
360 if (::fopen_s(&file, file_name, mode) != 0) {
361 return -1;
362 }
363 #else
364 std::FILE *file = std::fopen(file_name, mode);
365 if (file == NULL) {
366 return -1;
367 }
368 #endif
369
370 if (size == 0) {
371 if (std::fseek(file, 0, SEEK_END) != 0) {
372 std::fclose(file);
373 return -1;
374 }
375 size = std::ftell(file) - offset;
376 }
377
378 size /= unit_size();
379 if (size < 256 || (size & 0xFF) != 0) {
380 std::fclose(file);
381 return -1;
382 }
383
384 if (std::fseek(file, offset, SEEK_SET) != 0) {
385 std::fclose(file);
386 return -1;
387 }
388
389 unit_type units[256];
390 if (std::fread(units, unit_size(), 256, file) != 256) {
391 std::fclose(file);
392 return -1;
393 }
394
395 if (units[0].label() != '\0' || units[0].has_leaf() ||
396 units[0].offset() == 0 || units[0].offset() >= 512) {
397 std::fclose(file);
398 return -1;
399 }
400 for (id_type i = 1; i < 256; ++i) {
401 if (units[i].label() <= 0xFF && units[i].offset() >= size) {
402 std::fclose(file);
403 return -1;
404 }
405 }
406
407 unit_type *buf;
408 try {
409 buf = new unit_type[size];
410 for (id_type i = 0; i < 256; ++i) {
411 buf[i] = units[i];
412 }
413 } catch (const std::bad_alloc &) {
414 std::fclose(file);
415 DARTS_THROW("failed to open double-array: std::bad_alloc");
416 }
417
418 if (size > 256) {
419 if (std::fread(buf + 256, unit_size(), size - 256, file) != size - 256) {
420 std::fclose(file);
421 delete[] buf;
422 return -1;
423 }
424 }
425 std::fclose(file);
426
427 clear();
428
429 size_ = size;
430 array_ = buf;
431 buf_ = buf;
432 return 0;
433 }
434
435 template <typename A, typename B, typename T, typename C>
436 int DoubleArrayImpl<A, B, T, C>::save(const char *file_name,
437 const char *mode, std::size_t offset) const {
438 if (size() == 0) {
439 return -1;
440 }
441
442 #ifdef _MSC_VER
443 std::FILE *file;
444 if (::fopen_s(&file, file_name, mode) != 0) {
445 return -1;
446 }
447 #else
448 std::FILE *file = std::fopen(file_name, mode);
449 if (file == NULL) {
450 return -1;
451 }
452 #endif
453
454 if (std::fseek(file, offset, SEEK_SET) != 0) {
455 std::fclose(file);
456 return -1;
457 }
458
459 if (std::fwrite(array_, unit_size(), size(), file) != size()) {
460 std::fclose(file);
461 return -1;
462 }
463 std::fclose(file);
464 return 0;
465 }
466
467 template <typename A, typename B, typename T, typename C>
468 bool DoubleArrayImpl<A, B, T, C>::validate(value_type max_value_limit) const {
469 if (size_ == 0 || array_ == NULL) {
470 return false;
471 }
472 if (array_[0].label() != '\0' || array_[0].has_leaf() ||
473 array_[0].offset() == 0 || ((0 ^ array_[0].offset()) | 0xFF) >= size_) {
474 return false;
475 }
476 for (std::size_t i = 1; i < size_; ++i) {
477 if (array_[i].label() <= 0xFF) {
478 if (((i ^ array_[i].offset()) | 0xFF) >= size_) {
479 return false;
480 }
481 } else if (max_value_limit >= 0) {
482 if (array_[i].value() >= max_value_limit) {
483 return false;
484 }
485 }
486 }
487 return true;
488 }
489
490 template <typename A, typename B, typename T, typename C>
491 template <typename U>
492 inline U DoubleArrayImpl<A, B, T, C>::exactMatchSearch(const key_type *key,
493 std::size_t length, std::size_t node_pos) const {
494 U result;
495 set_result(&result, static_cast<value_type>(-1), 0);
496
497 unit_type unit = array_[node_pos];
498 if (length != 0) {
499 for (std::size_t i = 0; i < length; ++i) {
500 node_pos ^= unit.offset() ^ static_cast<uchar_type>(key[i]);
501 unit = array_[node_pos];
502 if (unit.label() != static_cast<uchar_type>(key[i])) {
503 return result;
504 }
505 }
506 } else {
507 for ( ; key[length] != '\0'; ++length) {
508 node_pos ^= unit.offset() ^ static_cast<uchar_type>(key[length]);
509 unit = array_[node_pos];
510 if (unit.label() != static_cast<uchar_type>(key[length])) {
511 return result;
512 }
513 }
514 }
515
516 if (!unit.has_leaf()) {
517 return result;
518 }
519 unit = array_[node_pos ^ unit.offset()];
520 set_result(&result, static_cast<value_type>(unit.value()), length);
521 return result;
522 }
523
524 template <typename A, typename B, typename T, typename C>
525 template <typename U>
526 inline std::size_t DoubleArrayImpl<A, B, T, C>::commonPrefixSearch(
527 const key_type *key, U *results, std::size_t max_num_results,
528 std::size_t length, std::size_t node_pos) const {
529 std::size_t num_results = 0;
530
531 unit_type unit = array_[node_pos];
532 node_pos ^= unit.offset();
533 if (length != 0) {
534 for (std::size_t i = 0; i < length; ++i) {
535 node_pos ^= static_cast<uchar_type>(key[i]);
536 unit = array_[node_pos];
537 if (unit.label() != static_cast<uchar_type>(key[i])) {
538 return num_results;
539 }
540
541 node_pos ^= unit.offset();
542 if (unit.has_leaf()) {
543 if (num_results < max_num_results) {
544 set_result(&results[num_results], static_cast<value_type>(
545 array_[node_pos].value()), i + 1);
546 }
547 ++num_results;
548 }
549 }
550 } else {
551 for ( ; key[length] != '\0'; ++length) {
552 node_pos ^= static_cast<uchar_type>(key[length]);
553 unit = array_[node_pos];
554 if (unit.label() != static_cast<uchar_type>(key[length])) {
555 return num_results;
556 }
557
558 node_pos ^= unit.offset();
559 if (unit.has_leaf()) {
560 if (num_results < max_num_results) {
561 set_result(&results[num_results], static_cast<value_type>(
562 array_[node_pos].value()), length + 1);
563 }
564 ++num_results;
565 }
566 }
567 }
568
569 return num_results;
570 }
571
572 template <typename A, typename B, typename T, typename C>
573 template <typename U>
574 inline U DoubleArrayImpl<A, B, T, C>::commonLongestPrefixSearch(
575 const key_type *key, std::size_t length,
576 std::size_t node_pos) const {
577 U result;
578 set_result(&result, static_cast<value_type>(-1), 0);
579
580 unit_type unit = array_[node_pos];
581 node_pos ^= unit.offset();
582 if (length != 0) {
583 for (std::size_t i = 0; i < length; ++i) {
584 node_pos ^= static_cast<uchar_type>(key[i]);
585 unit = array_[node_pos];
586 if (unit.label() != static_cast<uchar_type>(key[i])) {
587 return result;
588 }
589
590 node_pos ^= unit.offset();
591 if (unit.has_leaf()) {
592 set_result(&result, static_cast<value_type>(
593 array_[node_pos].value()), i + 1);
594 }
595 }
596 } else {
597 for ( ; key[length] != '\0'; ++length) {
598 node_pos ^= static_cast<uchar_type>(key[length]);
599 unit = array_[node_pos];
600 if (unit.label() != static_cast<uchar_type>(key[length])) {
601 return result;
602 }
603
604 node_pos ^= unit.offset();
605 if (unit.has_leaf()) {
606 set_result(&result, static_cast<value_type>(
607 array_[node_pos].value()), length + 1);
608 }
609 }
610 }
611
612 return result;
613 }
614
615 template <typename A, typename B, typename T, typename C>
616 inline typename DoubleArrayImpl<A, B, T, C>::value_type
617 DoubleArrayImpl<A, B, T, C>::traverse(const key_type *key,
618 std::size_t &node_pos, std::size_t &key_pos, std::size_t length) const {
619 id_type id = static_cast<id_type>(node_pos);
620 unit_type unit = array_[id];
621
622 if (length != 0) {
623 for ( ; key_pos < length; ++key_pos) {
624 id ^= unit.offset() ^ static_cast<uchar_type>(key[key_pos]);
625 unit = array_[id];
626 if (unit.label() != static_cast<uchar_type>(key[key_pos])) {
627 return static_cast<value_type>(-2);
628 }
629 node_pos = id;
630 }
631 } else {
632 for ( ; key[key_pos] != '\0'; ++key_pos) {
633 id ^= unit.offset() ^ static_cast<uchar_type>(key[key_pos]);
634 unit = array_[id];
635 if (unit.label() != static_cast<uchar_type>(key[key_pos])) {
636 return static_cast<value_type>(-2);
637 }
638 node_pos = id;
639 }
640 }
641
642 if (!unit.has_leaf()) {
643 return static_cast<value_type>(-1);
644 }
645 unit = array_[id ^ unit.offset()];
646 return static_cast<value_type>(unit.value());
647 }
648
649 namespace Details {
650
651 //
652 // Memory management of array.
653 //
654
655 template <typename T>
656 class AutoArray {
657 public:
658 explicit AutoArray(T *array = NULL) : array_(array) {}
659 ~AutoArray() {
660 clear();
661 }
662
663 const T &operator[](std::size_t id) const {
664 return array_[id];
665 }
666 T &operator[](std::size_t id) {
667 return array_[id];
668 }
669
670 bool empty() const {
671 return array_ == NULL;
672 }
673
674 void clear() {
675 if (array_ != NULL) {
676 delete[] array_;
677 array_ = NULL;
678 }
679 }
680 void swap(AutoArray *array) {
681 T *temp = array_;
682 array_ = array->array_;
683 array->array_ = temp;
684 }
685 void reset(T *array = NULL) {
686 AutoArray(array).swap(this);
687 }
688
689 private:
690 T *array_;
691
692 // Disallows copy and assignment.
693 AutoArray(const AutoArray &);
694 AutoArray &operator=(const AutoArray &);
695 };
696
697 //
698 // Memory management of resizable array.
699 //
700
701 template <typename T>
702 class AutoPool {
703 public:
704 AutoPool() : buf_(), size_(0), capacity_(0) {}
705 ~AutoPool() { clear(); }
706
707 const T &operator[](std::size_t id) const {
708 return *(reinterpret_cast<const T *>(&buf_[0]) + id);
709 }
710 T &operator[](std::size_t id) {
711 return *(reinterpret_cast<T *>(&buf_[0]) + id);
712 }
713
714 bool empty() const {
715 return size_ == 0;
716 }
717 std::size_t size() const {
718 return size_;
719 }
720
721 void clear() {
722 resize(0);
723 buf_.clear();
724 size_ = 0;
725 capacity_ = 0;
726 }
727
728 void push_back(const T &value) {
729 append(value);
730 }
731 void pop_back() {
732 (*this)[--size_].~T();
733 }
734
735 void append() {
736 if (size_ == capacity_)
737 resize_buf(size_ + 1);
738 new(&(*this)[size_++]) T;
739 }
740 void append(const T &value) {
741 if (size_ == capacity_)
742 resize_buf(size_ + 1);
743 new(&(*this)[size_++]) T(value);
744 }
745
746 void resize(std::size_t size) {
747 while (size_ > size) {
748 (*this)[--size_].~T();
749 }
750 if (size > capacity_) {
751 resize_buf(size);
752 }
753 while (size_ < size) {
754 new(&(*this)[size_++]) T;
755 }
756 }
757 void resize(std::size_t size, const T &value) {
758 while (size_ > size) {
759 (*this)[--size_].~T();
760 }
761 if (size > capacity_) {
762 resize_buf(size);
763 }
764 while (size_ < size) {
765 new(&(*this)[size_++]) T(value);
766 }
767 }
768
769 void reserve(std::size_t size) {
770 if (size > capacity_) {
771 resize_buf(size);
772 }
773 }
774
775 private:
776 AutoArray<char> buf_;
777 std::size_t size_;
778 std::size_t capacity_;
779
780 // Disallows copy and assignment.
781 AutoPool(const AutoPool &);
782 AutoPool &operator=(const AutoPool &);
783
784 void resize_buf(std::size_t size);
785 };
786
787 template <typename T>
788 void AutoPool<T>::resize_buf(std::size_t size) {
789 std::size_t capacity;
790 if (size >= capacity_ * 2) {
791 capacity = size;
792 } else {
793 capacity = 1;
794 while (capacity < size) {
795 capacity <<= 1;
796 }
797 }
798
799 AutoArray<char> buf;
800 try {
801 buf.reset(new char[sizeof(T) * capacity]);
802 } catch (const std::bad_alloc &) {
803 DARTS_THROW("failed to resize pool: std::bad_alloc");
804 }
805
806 if (size_ > 0) {
807 T *src = reinterpret_cast<T *>(&buf_[0]);
808 T *dest = reinterpret_cast<T *>(&buf[0]);
809 for (std::size_t i = 0; i < size_; ++i) {
810 new(&dest[i]) T(src[i]);
811 src[i].~T();
812 }
813 }
814
815 buf_.swap(&buf);
816 capacity_ = capacity;
817 }
818
819 //
820 // Memory management of stack.
821 //
822
823 template <typename T>
824 class AutoStack {
825 public:
826 AutoStack() : pool_() {}
827 ~AutoStack() {
828 clear();
829 }
830
831 const T &top() const {
832 return pool_[size() - 1];
833 }
834 T &top() {
835 return pool_[size() - 1];
836 }
837
838 bool empty() const {
839 return pool_.empty();
840 }
841 std::size_t size() const {
842 return pool_.size();
843 }
844
845 void push(const T &value) {
846 pool_.push_back(value);
847 }
848 void pop() {
849 pool_.pop_back();
850 }
851
852 void clear() {
853 pool_.clear();
854 }
855
856 private:
857 AutoPool<T> pool_;
858
859 // Disallows copy and assignment.
860 AutoStack(const AutoStack &);
861 AutoStack &operator=(const AutoStack &);
862 };
863
864 //
865 // Succinct bit vector.
866 //
867
868 class BitVector {
869 public:
870 BitVector() : units_(), ranks_(), num_ones_(0), size_(0) {}
871 ~BitVector() {
872 clear();
873 }
874
875 bool operator[](std::size_t id) const {
876 return (units_[id / UNIT_SIZE] >> (id % UNIT_SIZE) & 1) == 1;
877 }
878
879 id_type rank(std::size_t id) const {
880 std::size_t unit_id = id / UNIT_SIZE;
881 return ranks_[unit_id] + pop_count(units_[unit_id]
882 & (~0U >> (UNIT_SIZE - (id % UNIT_SIZE) - 1)));
883 }
884
885 void set(std::size_t id, bool bit) {
886 if (bit) {
887 units_[id / UNIT_SIZE] |= 1U << (id % UNIT_SIZE);
888 } else {
889 units_[id / UNIT_SIZE] &= ~(1U << (id % UNIT_SIZE));
890 }
891 }
892
893 bool empty() const {
894 return units_.empty();
895 }
896 std::size_t num_ones() const {
897 return num_ones_;
898 }
899 std::size_t size() const {
900 return size_;
901 }
902
903 void append() {
904 if ((size_ % UNIT_SIZE) == 0) {
905 units_.append(0);
906 }
907 ++size_;
908 }
909 void build();
910
911 void clear() {
912 units_.clear();
913 ranks_.clear();
914 }
915
916 private:
917 enum { UNIT_SIZE = sizeof(id_type) * 8 };
918
919 AutoPool<id_type> units_;
920 AutoArray<id_type> ranks_;
921 std::size_t num_ones_;
922 std::size_t size_;
923
924 // Disallows copy and assignment.
925 BitVector(const BitVector &);
926 BitVector &operator=(const BitVector &);
927
928 static id_type pop_count(id_type unit) {
929 unit = ((unit & 0xAAAAAAAA) >> 1) + (unit & 0x55555555);
930 unit = ((unit & 0xCCCCCCCC) >> 2) + (unit & 0x33333333);
931 unit = ((unit >> 4) + unit) & 0x0F0F0F0F;
932 unit += unit >> 8;
933 unit += unit >> 16;
934 return unit & 0xFF;
935 }
936 };
937
938 inline void BitVector::build() {
939 try {
940 ranks_.reset(new id_type[units_.size()]);
941 } catch (const std::bad_alloc &) {
942 DARTS_THROW("failed to build rank index: std::bad_alloc");
943 }
944
945 num_ones_ = 0;
946 for (std::size_t i = 0; i < units_.size(); ++i) {
947 ranks_[i] = static_cast<id_type>(num_ones_);
948 num_ones_ += pop_count(units_[i]);
949 }
950 }
951
952 //
953 // Keyset.
954 //
955
956 template <typename T>
957 class Keyset {
958 public:
959 Keyset(std::size_t num_keys, const char_type * const *keys,
960 const std::size_t *lengths, const T *values) :
961 num_keys_(num_keys), keys_(keys), lengths_(lengths), values_(values) {}
962
963 std::size_t num_keys() const {
964 return num_keys_;
965 }
966 const char_type *keys(std::size_t id) const {
967 return keys_[id];
968 }
969 uchar_type keys(std::size_t key_id, std::size_t char_id) const {
970 if (has_lengths() && char_id >= lengths_[key_id])
971 return '\0';
972 return keys_[key_id][char_id];
973 }
974
975 bool has_lengths() const {
976 return lengths_ != NULL;
977 }
978 std::size_t lengths(std::size_t id) const {
979 if (has_lengths()) {
980 return lengths_[id];
981 }
982 std::size_t length = 0;
983 while (keys_[id][length] != '\0') {
984 ++length;
985 }
986 return length;
987 }
988
989 bool has_values() const {
990 return values_ != NULL;
991 }
992 const value_type values(std::size_t id) const {
993 if (has_values()) {
994 return static_cast<value_type>(values_[id]);
995 }
996 return static_cast<value_type>(id);
997 }
998
999 private:
1000 std::size_t num_keys_;
1001 const char_type * const * keys_;
1002 const std::size_t *lengths_;
1003 const T *values_;
1004
1005 // Disallows copy and assignment.
1006 Keyset(const Keyset &);
1007 Keyset &operator=(const Keyset &);
1008 };
1009
1010 //
1011 // Node of Directed Acyclic Word Graph (DAWG).
1012 //
1013
1014 class DawgNode {
1015 public:
1016 DawgNode() : child_(0), sibling_(0), label_('\0'),
1017 is_state_(false), has_sibling_(false) {}
1018
1019 void set_child(id_type child) {
1020 child_ = child;
1021 }
1022 void set_sibling(id_type sibling) {
1023 sibling_ = sibling;
1024 }
1025 void set_value(value_type value) {
1026 child_ = value;
1027 }
1028 void set_label(uchar_type label) {
1029 label_ = label;
1030 }
1031 void set_is_state(bool is_state) {
1032 is_state_ = is_state;
1033 }
1034 void set_has_sibling(bool has_sibling) {
1035 has_sibling_ = has_sibling;
1036 }
1037
1038 id_type child() const {
1039 return child_;
1040 }
1041 id_type sibling() const {
1042 return sibling_;
1043 }
1044 value_type value() const {
1045 return static_cast<value_type>(child_);
1046 }
1047 uchar_type label() const {
1048 return label_;
1049 }
1050 bool is_state() const {
1051 return is_state_;
1052 }
1053 bool has_sibling() const {
1054 return has_sibling_;
1055 }
1056
1057 id_type unit() const {
1058 if (label_ == '\0') {
1059 return (child_ << 1) | (has_sibling_ ? 1 : 0);
1060 }
1061 return (child_ << 2) | (is_state_ ? 2 : 0) | (has_sibling_ ? 1 : 0);
1062 }
1063
1064 private:
1065 id_type child_;
1066 id_type sibling_;
1067 uchar_type label_;
1068 bool is_state_;
1069 bool has_sibling_;
1070
1071 // Copyable.
1072 };
1073
1074 //
1075 // Fixed unit of Directed Acyclic Word Graph (DAWG).
1076 //
1077
1078 class DawgUnit {
1079 public:
1080 explicit DawgUnit(id_type unit = 0) : unit_(unit) {}
1081 DawgUnit(const DawgUnit &unit) : unit_(unit.unit_) {}
1082
1083 DawgUnit &operator=(id_type unit) {
1084 unit_ = unit;
1085 return *this;
1086 }
1087
1088 id_type unit() const {
1089 return unit_;
1090 }
1091
1092 id_type child() const {
1093 return unit_ >> 2;
1094 }
1095 bool has_sibling() const {
1096 return (unit_ & 1) == 1;
1097 }
1098 value_type value() const {
1099 return static_cast<value_type>(unit_ >> 1);
1100 }
1101 bool is_state() const {
1102 return (unit_ & 2) == 2;
1103 }
1104
1105 private:
1106 id_type unit_;
1107
1108 // Copyable.
1109 };
1110
1111 //
1112 // Directed Acyclic Word Graph (DAWG) builder.
1113 //
1114
1115 class DawgBuilder {
1116 public:
1117 DawgBuilder() : nodes_(), units_(), labels_(), is_intersections_(),
1118 table_(), node_stack_(), recycle_bin_(), num_states_(0) {}
1119 ~DawgBuilder() {
1120 clear();
1121 }
1122
1123 id_type root() const {
1124 return 0;
1125 }
1126
1127 id_type child(id_type id) const {
1128 return units_[id].child();
1129 }
1130 id_type sibling(id_type id) const {
1131 return units_[id].has_sibling() ? (id + 1) : 0;
1132 }
1133 int value(id_type id) const {
1134 return units_[id].value();
1135 }
1136
1137 bool is_leaf(id_type id) const {
1138 return label(id) == '\0';
1139 }
1140 uchar_type label(id_type id) const {
1141 return labels_[id];
1142 }
1143
1144 bool is_intersection(id_type id) const {
1145 return is_intersections_[id];
1146 }
1147 id_type intersection_id(id_type id) const {
1148 return is_intersections_.rank(id) - 1;
1149 }
1150
1151 std::size_t num_intersections() const {
1152 return is_intersections_.num_ones();
1153 }
1154
1155 std::size_t size() const {
1156 return units_.size();
1157 }
1158
1159 void init();
1160 void finish();
1161
1162 void insert(const char *key, std::size_t length, value_type value);
1163
1164 void clear();
1165
1166 private:
1167 enum { INITIAL_TABLE_SIZE = 1 << 10 };
1168
1169 AutoPool<DawgNode> nodes_;
1170 AutoPool<DawgUnit> units_;
1171 AutoPool<uchar_type> labels_;
1172 BitVector is_intersections_;
1173 AutoPool<id_type> table_;
1174 AutoStack<id_type> node_stack_;
1175 AutoStack<id_type> recycle_bin_;
1176 std::size_t num_states_;
1177
1178 // Disallows copy and assignment.
1179 DawgBuilder(const DawgBuilder &);
1180 DawgBuilder &operator=(const DawgBuilder &);
1181
1182 void flush(id_type id);
1183
1184 void expand_table();
1185
1186 id_type find_unit(id_type id, id_type *hash_id) const;
1187 id_type find_node(id_type node_id, id_type *hash_id) const;
1188
1189 bool are_equal(id_type node_id, id_type unit_id) const;
1190
1191 id_type hash_unit(id_type id) const;
1192 id_type hash_node(id_type id) const;
1193
1194 id_type append_node();
1195 id_type append_unit();
1196
1197 void free_node(id_type id) {
1198 recycle_bin_.push(id);
1199 }
1200
1201 static id_type hash(id_type key) {
1202 key = ~key + (key << 15); // key = (key << 15) - key - 1;
1203 key = key ^ (key >> 12);
1204 key = key + (key << 2);
1205 key = key ^ (key >> 4);
1206 key = key * 2057; // key = (key + (key << 3)) + (key << 11);
1207 key = key ^ (key >> 16);
1208 return key;
1209 }
1210 };
1211
1212 inline void DawgBuilder::init() {
1213 table_.resize(INITIAL_TABLE_SIZE, 0);
1214
1215 append_node();
1216 append_unit();
1217
1218 num_states_ = 1;
1219
1220 nodes_[0].set_label(0xFF);
1221 node_stack_.push(0);
1222 }
1223
1224 inline void DawgBuilder::finish() {
1225 flush(0);
1226
1227 units_[0] = nodes_[0].unit();
1228 labels_[0] = nodes_[0].label();
1229
1230 nodes_.clear();
1231 table_.clear();
1232 node_stack_.clear();
1233 recycle_bin_.clear();
1234
1235 is_intersections_.build();
1236 }
1237
1238 inline void DawgBuilder::insert(const char *key, std::size_t length,
1239 value_type value) {
1240 if (value < 0) {
1241 DARTS_THROW("failed to insert key: negative value");
1242 } else if (length == 0) {
1243 DARTS_THROW("failed to insert key: zero-length key");
1244 }
1245
1246 id_type id = 0;
1247 std::size_t key_pos = 0;
1248
1249 for ( ; key_pos <= length; ++key_pos) {
1250 id_type child_id = nodes_[id].child();
1251 if (child_id == 0) {
1252 break;
1253 }
1254
1255 uchar_type key_label = static_cast<uchar_type>(key[key_pos]);
1256 if (key_pos < length && key_label == '\0') {
1257 DARTS_THROW("failed to insert key: invalid null character");
1258 }
1259
1260 uchar_type unit_label = nodes_[child_id].label();
1261 if (key_label < unit_label) {
1262 DARTS_THROW("failed to insert key: wrong key order");
1263 } else if (key_label > unit_label) {
1264 nodes_[child_id].set_has_sibling(true);
1265 flush(child_id);
1266 break;
1267 }
1268 id = child_id;
1269 }
1270
1271 if (key_pos > length) {
1272 return;
1273 }
1274
1275 for ( ; key_pos <= length; ++key_pos) {
1276 uchar_type key_label = static_cast<uchar_type>(
1277 (key_pos < length) ? key[key_pos] : '\0');
1278 id_type child_id = append_node();
1279
1280 if (nodes_[id].child() == 0) {
1281 nodes_[child_id].set_is_state(true);
1282 }
1283 nodes_[child_id].set_sibling(nodes_[id].child());
1284 nodes_[child_id].set_label(key_label);
1285 nodes_[id].set_child(child_id);
1286 node_stack_.push(child_id);
1287
1288 id = child_id;
1289 }
1290 nodes_[id].set_value(value);
1291 }
1292
1293 inline void DawgBuilder::clear() {
1294 nodes_.clear();
1295 units_.clear();
1296 labels_.clear();
1297 is_intersections_.clear();
1298 table_.clear();
1299 node_stack_.clear();
1300 recycle_bin_.clear();
1301 num_states_ = 0;
1302 }
1303
1304 inline void DawgBuilder::flush(id_type id) {
1305 while (node_stack_.top() != id) {
1306 id_type node_id = node_stack_.top();
1307 node_stack_.pop();
1308
1309 if (num_states_ >= table_.size() - (table_.size() >> 2)) {
1310 expand_table();
1311 }
1312
1313 id_type num_siblings = 0;
1314 for (id_type i = node_id; i != 0; i = nodes_[i].sibling()) {
1315 ++num_siblings;
1316 }
1317
1318 id_type hash_id;
1319 id_type match_id = find_node(node_id, &hash_id);
1320 if (match_id != 0) {
1321 is_intersections_.set(match_id, true);
1322 } else {
1323 id_type unit_id = 0;
1324 for (id_type i = 0; i < num_siblings; ++i) {
1325 unit_id = append_unit();
1326 }
1327 for (id_type i = node_id; i != 0; i = nodes_[i].sibling()) {
1328 units_[unit_id] = nodes_[i].unit();
1329 labels_[unit_id] = nodes_[i].label();
1330 --unit_id;
1331 }
1332 match_id = unit_id + 1;
1333 table_[hash_id] = match_id;
1334 ++num_states_;
1335 }
1336
1337 for (id_type i = node_id, next; i != 0; i = next) {
1338 next = nodes_[i].sibling();
1339 free_node(i);
1340 }
1341
1342 nodes_[node_stack_.top()].set_child(match_id);
1343 }
1344 node_stack_.pop();
1345 }
1346
1347 inline void DawgBuilder::expand_table() {
1348 std::size_t table_size = table_.size() << 1;
1349 table_.clear();
1350 table_.resize(table_size, 0);
1351
1352 for (std::size_t i = 1; i < units_.size(); ++i) {
1353 id_type id = static_cast<id_type>(i);
1354 if (labels_[id] == '\0' || units_[id].is_state()) {
1355 id_type hash_id;
1356 find_unit(id, &hash_id);
1357 table_[hash_id] = id;
1358 }
1359 }
1360 }
1361
1362 inline id_type DawgBuilder::find_unit(id_type id, id_type *hash_id) const {
1363 *hash_id = hash_unit(id) % table_.size();
1364 for ( ; ; *hash_id = (*hash_id + 1) % table_.size()) {
1365 id_type unit_id = table_[*hash_id];
1366 if (unit_id == 0) {
1367 break;
1368 }
1369
1370 // There must not be the same unit.
1371 }
1372 return 0;
1373 }
1374
1375 inline id_type DawgBuilder::find_node(id_type node_id,
1376 id_type *hash_id) const {
1377 *hash_id = hash_node(node_id) % table_.size();
1378 for ( ; ; *hash_id = (*hash_id + 1) % table_.size()) {
1379 id_type unit_id = table_[*hash_id];
1380 if (unit_id == 0) {
1381 break;
1382 }
1383
1384 if (are_equal(node_id, unit_id)) {
1385 return unit_id;
1386 }
1387 }
1388 return 0;
1389 }
1390
1391 inline bool DawgBuilder::are_equal(id_type node_id, id_type unit_id) const {
1392 for (id_type i = nodes_[node_id].sibling(); i != 0;
1393 i = nodes_[i].sibling()) {
1394 if (units_[unit_id].has_sibling() == false) {
1395 return false;
1396 }
1397 ++unit_id;
1398 }
1399 if (units_[unit_id].has_sibling() == true) {
1400 return false;
1401 }
1402
1403 for (id_type i = node_id; i != 0; i = nodes_[i].sibling(), --unit_id) {
1404 if (nodes_[i].unit() != units_[unit_id].unit() ||
1405 nodes_[i].label() != labels_[unit_id]) {
1406 return false;
1407 }
1408 }
1409 return true;
1410 }
1411
1412 inline id_type DawgBuilder::hash_unit(id_type id) const {
1413 id_type hash_value = 0;
1414 for ( ; id != 0; ++id) {
1415 id_type unit = units_[id].unit();
1416 uchar_type label = labels_[id];
1417 hash_value ^= hash((label << 24) ^ unit);
1418
1419 if (units_[id].has_sibling() == false) {
1420 break;
1421 }
1422 }
1423 return hash_value;
1424 }
1425
1426 inline id_type DawgBuilder::hash_node(id_type id) const {
1427 id_type hash_value = 0;
1428 for ( ; id != 0; id = nodes_[id].sibling()) {
1429 id_type unit = nodes_[id].unit();
1430 uchar_type label = nodes_[id].label();
1431 hash_value ^= hash((label << 24) ^ unit);
1432 }
1433 return hash_value;
1434 }
1435
1436 inline id_type DawgBuilder::append_unit() {
1437 is_intersections_.append();
1438 units_.append();
1439 labels_.append();
1440
1441 return static_cast<id_type>(is_intersections_.size() - 1);
1442 }
1443
1444 inline id_type DawgBuilder::append_node() {
1445 id_type id;
1446 if (recycle_bin_.empty()) {
1447 id = static_cast<id_type>(nodes_.size());
1448 nodes_.append();
1449 } else {
1450 id = recycle_bin_.top();
1451 nodes_[id] = DawgNode();
1452 recycle_bin_.pop();
1453 }
1454 return id;
1455 }
1456
1457 //
1458 // Unit of double-array builder.
1459 //
1460
1461 class DoubleArrayBuilderUnit {
1462 public:
1463 DoubleArrayBuilderUnit() : unit_(0) {}
1464
1465 void set_has_leaf(bool has_leaf) {
1466 if (has_leaf) {
1467 unit_ |= 1U << 8;
1468 } else {
1469 unit_ &= ~(1U << 8);
1470 }
1471 }
1472 void set_value(value_type value) {
1473 unit_ = value | (1U << 31);
1474 }
1475 void set_label(uchar_type label) {
1476 unit_ = (unit_ & ~0xFFU) | label;
1477 }
1478 void set_offset(id_type offset) {
1479 if (offset >= 1U << 29) {
1480 DARTS_THROW("failed to modify unit: too large offset");
1481 }
1482 unit_ &= (1U << 31) | (1U << 8) | 0xFF;
1483 if (offset < 1U << 21) {
1484 unit_ |= (offset << 10);
1485 } else {
1486 unit_ |= (offset << 2) | (1U << 9);
1487 }
1488 }
1489
1490 private:
1491 id_type unit_;
1492
1493 // Copyable.
1494 };
1495
1496 //
1497 // Extra unit of double-array builder.
1498 //
1499
1500 class DoubleArrayBuilderExtraUnit {
1501 public:
1502 DoubleArrayBuilderExtraUnit() : prev_(0), next_(0),
1503 is_fixed_(false), is_used_(false) {}
1504
1505 void set_prev(id_type prev) {
1506 prev_ = prev;
1507 }
1508 void set_next(id_type next) {
1509 next_ = next;
1510 }
1511 void set_is_fixed(bool is_fixed) {
1512 is_fixed_ = is_fixed;
1513 }
1514 void set_is_used(bool is_used) {
1515 is_used_ = is_used;
1516 }
1517
1518 id_type prev() const {
1519 return prev_;
1520 }
1521 id_type next() const {
1522 return next_;
1523 }
1524 bool is_fixed() const {
1525 return is_fixed_;
1526 }
1527 bool is_used() const {
1528 return is_used_;
1529 }
1530
1531 private:
1532 id_type prev_;
1533 id_type next_;
1534 bool is_fixed_;
1535 bool is_used_;
1536
1537 // Copyable.
1538 };
1539
1540 //
1541 // DAWG -> double-array converter.
1542 //
1543
1544 class DoubleArrayBuilder {
1545 public:
1546 explicit DoubleArrayBuilder(progress_func_type progress_func)
1547 : progress_func_(progress_func), units_(), extras_(), labels_(),
1548 table_(), extras_head_(0) {}
1549 ~DoubleArrayBuilder() {
1550 clear();
1551 }
1552
1553 template <typename T>
1554 void build(const Keyset<T> &keyset);
1555 void copy(std::size_t *size_ptr, DoubleArrayUnit **buf_ptr) const;
1556
1557 void clear();
1558
1559 private:
1560 enum { BLOCK_SIZE = 256 };
1561 enum { NUM_EXTRA_BLOCKS = 16 };
1562 enum { NUM_EXTRAS = BLOCK_SIZE * NUM_EXTRA_BLOCKS };
1563
1564 enum { UPPER_MASK = 0xFF << 21 };
1565 enum { LOWER_MASK = 0xFF };
1566
1567 typedef DoubleArrayBuilderUnit unit_type;
1568 typedef DoubleArrayBuilderExtraUnit extra_type;
1569
1570 progress_func_type progress_func_;
1571 AutoPool<unit_type> units_;
1572 AutoArray<extra_type> extras_;
1573 AutoPool<uchar_type> labels_;
1574 AutoArray<id_type> table_;
1575 id_type extras_head_;
1576
1577 // Disallows copy and assignment.
1578 DoubleArrayBuilder(const DoubleArrayBuilder &);
1579 DoubleArrayBuilder &operator=(const DoubleArrayBuilder &);
1580
1581 std::size_t num_blocks() const {
1582 return units_.size() / BLOCK_SIZE;
1583 }
1584
1585 const extra_type &extras(id_type id) const {
1586 return extras_[id % NUM_EXTRAS];
1587 }
1588 extra_type &extras(id_type id) {
1589 return extras_[id % NUM_EXTRAS];
1590 }
1591
1592 template <typename T>
1593 void build_dawg(const Keyset<T> &keyset, DawgBuilder *dawg_builder);
1594 void build_from_dawg(const DawgBuilder &dawg);
1595 void build_from_dawg(const DawgBuilder &dawg,
1596 id_type dawg_id, id_type dic_id);
1597 id_type arrange_from_dawg(const DawgBuilder &dawg,
1598 id_type dawg_id, id_type dic_id);
1599
1600 template <typename T>
1601 void build_from_keyset(const Keyset<T> &keyset);
1602 template <typename T>
1603 void build_from_keyset(const Keyset<T> &keyset, std::size_t begin,
1604 std::size_t end, std::size_t depth, id_type dic_id);
1605 template <typename T>
1606 id_type arrange_from_keyset(const Keyset<T> &keyset, std::size_t begin,
1607 std::size_t end, std::size_t depth, id_type dic_id);
1608
1609 id_type find_valid_offset(id_type id) const;
1610 bool is_valid_offset(id_type id, id_type offset) const;
1611
1612 void reserve_id(id_type id);
1613 void expand_units();
1614
1615 void fix_all_blocks();
1616 void fix_block(id_type block_id);
1617 };
1618
1619 template <typename T>
1620 void DoubleArrayBuilder::build(const Keyset<T> &keyset) {
1621 if (keyset.has_values()) {
1622 Details::DawgBuilder dawg_builder;
1623 build_dawg(keyset, &dawg_builder);
1624 build_from_dawg(dawg_builder);
1625 dawg_builder.clear();
1626 } else {
1627 build_from_keyset(keyset);
1628 }
1629 }
1630
1631 inline void DoubleArrayBuilder::copy(std::size_t *size_ptr,
1632 DoubleArrayUnit **buf_ptr) const {
1633 if (size_ptr != NULL) {
1634 *size_ptr = units_.size();
1635 }
1636 if (buf_ptr != NULL) {
1637 *buf_ptr = new DoubleArrayUnit[units_.size()];
1638 unit_type *units = reinterpret_cast<unit_type *>(*buf_ptr);
1639 for (std::size_t i = 0; i < units_.size(); ++i) {
1640 units[i] = units_[i];
1641 }
1642 }
1643 }
1644
1645 inline void DoubleArrayBuilder::clear() {
1646 units_.clear();
1647 extras_.clear();
1648 labels_.clear();
1649 table_.clear();
1650 extras_head_ = 0;
1651 }
1652
1653 template <typename T>
1654 void DoubleArrayBuilder::build_dawg(const Keyset<T> &keyset,
1655 DawgBuilder *dawg_builder) {
1656 dawg_builder->init();
1657 for (std::size_t i = 0; i < keyset.num_keys(); ++i) {
1658 dawg_builder->insert(keyset.keys(i), keyset.lengths(i), keyset.values(i));
1659 if (progress_func_ != NULL) {
1660 progress_func_(i + 1, keyset.num_keys() + 1);
1661 }
1662 }
1663 dawg_builder->finish();
1664 }
1665
1666 inline void DoubleArrayBuilder::build_from_dawg(const DawgBuilder &dawg) {
1667 std::size_t num_units = 1;
1668 while (num_units < dawg.size()) {
1669 num_units <<= 1;
1670 }
1671 units_.reserve(num_units);
1672
1673 table_.reset(new id_type[dawg.num_intersections()]);
1674 for (std::size_t i = 0; i < dawg.num_intersections(); ++i) {
1675 table_[i] = 0;
1676 }
1677
1678 extras_.reset(new extra_type[NUM_EXTRAS]);
1679
1680 reserve_id(0);
1681 extras(0).set_is_used(true);
1682 units_[0].set_offset(1);
1683 units_[0].set_label('\0');
1684
1685 if (dawg.child(dawg.root()) != 0) {
1686 build_from_dawg(dawg, dawg.root(), 0);
1687 }
1688
1689 fix_all_blocks();
1690
1691 extras_.clear();
1692 labels_.clear();
1693 table_.clear();
1694 }
1695
1696 inline void DoubleArrayBuilder::build_from_dawg(const DawgBuilder &dawg,
1697 id_type dawg_id, id_type dic_id) {
1698 id_type dawg_child_id = dawg.child(dawg_id);
1699 if (dawg.is_intersection(dawg_child_id)) {
1700 id_type intersection_id = dawg.intersection_id(dawg_child_id);
1701 id_type offset = table_[intersection_id];
1702 if (offset != 0) {
1703 offset ^= dic_id;
1704 if (!(offset & UPPER_MASK) || !(offset & LOWER_MASK)) {
1705 if (dawg.is_leaf(dawg_child_id)) {
1706 units_[dic_id].set_has_leaf(true);
1707 }
1708 units_[dic_id].set_offset(offset);
1709 return;
1710 }
1711 }
1712 }
1713
1714 id_type offset = arrange_from_dawg(dawg, dawg_id, dic_id);
1715 if (dawg.is_intersection(dawg_child_id)) {
1716 table_[dawg.intersection_id(dawg_child_id)] = offset;
1717 }
1718
1719 do {
1720 uchar_type child_label = dawg.label(dawg_child_id);
1721 id_type dic_child_id = offset ^ child_label;
1722 if (child_label != '\0') {
1723 build_from_dawg(dawg, dawg_child_id, dic_child_id);
1724 }
1725 dawg_child_id = dawg.sibling(dawg_child_id);
1726 } while (dawg_child_id != 0);
1727 }
1728
1729 inline id_type DoubleArrayBuilder::arrange_from_dawg(const DawgBuilder &dawg,
1730 id_type dawg_id, id_type dic_id) {
1731 labels_.resize(0);
1732
1733 id_type dawg_child_id = dawg.child(dawg_id);
1734 while (dawg_child_id != 0) {
1735 labels_.append(dawg.label(dawg_child_id));
1736 dawg_child_id = dawg.sibling(dawg_child_id);
1737 }
1738
1739 id_type offset = find_valid_offset(dic_id);
1740 units_[dic_id].set_offset(dic_id ^ offset);
1741
1742 dawg_child_id = dawg.child(dawg_id);
1743 for (std::size_t i = 0; i < labels_.size(); ++i) {
1744 id_type dic_child_id = offset ^ labels_[i];
1745 reserve_id(dic_child_id);
1746
1747 if (dawg.is_leaf(dawg_child_id)) {
1748 units_[dic_id].set_has_leaf(true);
1749 units_[dic_child_id].set_value(dawg.value(dawg_child_id));
1750 } else {
1751 units_[dic_child_id].set_label(labels_[i]);
1752 }
1753
1754 dawg_child_id = dawg.sibling(dawg_child_id);
1755 }
1756 extras(offset).set_is_used(true);
1757
1758 return offset;
1759 }
1760
1761 template <typename T>
1762 void DoubleArrayBuilder::build_from_keyset(const Keyset<T> &keyset) {
1763 std::size_t num_units = 1;
1764 while (num_units < keyset.num_keys()) {
1765 num_units <<= 1;
1766 }
1767 units_.reserve(num_units);
1768
1769 extras_.reset(new extra_type[NUM_EXTRAS]);
1770
1771 reserve_id(0);
1772 extras(0).set_is_used(true);
1773 units_[0].set_offset(1);
1774 units_[0].set_label('\0');
1775
1776 if (keyset.num_keys() > 0) {
1777 build_from_keyset(keyset, 0, keyset.num_keys(), 0, 0);
1778 }
1779
1780 fix_all_blocks();
1781
1782 extras_.clear();
1783 labels_.clear();
1784 }
1785
1786 template <typename T>
1787 void DoubleArrayBuilder::build_from_keyset(const Keyset<T> &keyset,
1788 std::size_t begin, std::size_t end, std::size_t depth, id_type dic_id) {
1789 id_type offset = arrange_from_keyset(keyset, begin, end, depth, dic_id);
1790
1791 while (begin < end) {
1792 if (keyset.keys(begin, depth) != '\0') {
1793 break;
1794 }
1795 ++begin;
1796 }
1797 if (begin == end) {
1798 return;
1799 }
1800
1801 std::size_t last_begin = begin;
1802 uchar_type last_label = keyset.keys(begin, depth);
1803 while (++begin < end) {
1804 uchar_type label = keyset.keys(begin, depth);
1805 if (label != last_label) {
1806 build_from_keyset(keyset, last_begin, begin,
1807 depth + 1, offset ^ last_label);
1808 last_begin = begin;
1809 last_label = keyset.keys(begin, depth);
1810 }
1811 }
1812 build_from_keyset(keyset, last_begin, end, depth + 1, offset ^ last_label);
1813 }
1814
1815 template <typename T>
1816 id_type DoubleArrayBuilder::arrange_from_keyset(const Keyset<T> &keyset,
1817 std::size_t begin, std::size_t end, std::size_t depth, id_type dic_id) {
1818 labels_.resize(0);
1819
1820 value_type value = -1;
1821 for (std::size_t i = begin; i < end; ++i) {
1822 uchar_type label = keyset.keys(i, depth);
1823 if (label == '\0') {
1824 if (keyset.has_lengths() && depth < keyset.lengths(i)) {
1825 DARTS_THROW("failed to build double-array: "
1826 "invalid null character");
1827 } else if (keyset.values(i) < 0) {
1828 DARTS_THROW("failed to build double-array: negative value");
1829 }
1830
1831 if (value == -1) {
1832 value = keyset.values(i);
1833 }
1834 if (progress_func_ != NULL) {
1835 progress_func_(i + 1, keyset.num_keys() + 1);
1836 }
1837 }
1838
1839 if (labels_.empty()) {
1840 labels_.append(label);
1841 } else if (label != labels_[labels_.size() - 1]) {
1842 if (label < labels_[labels_.size() - 1]) {
1843 DARTS_THROW("failed to build double-array: wrong key order");
1844 }
1845 labels_.append(label);
1846 }
1847 }
1848
1849 id_type offset = find_valid_offset(dic_id);
1850 units_[dic_id].set_offset(dic_id ^ offset);
1851
1852 for (std::size_t i = 0; i < labels_.size(); ++i) {
1853 id_type dic_child_id = offset ^ labels_[i];
1854 reserve_id(dic_child_id);
1855 if (labels_[i] == '\0') {
1856 units_[dic_id].set_has_leaf(true);
1857 units_[dic_child_id].set_value(value);
1858 } else {
1859 units_[dic_child_id].set_label(labels_[i]);
1860 }
1861 }
1862 extras(offset).set_is_used(true);
1863
1864 return offset;
1865 }
1866
1867 inline id_type DoubleArrayBuilder::find_valid_offset(id_type id) const {
1868 if (extras_head_ >= units_.size()) {
1869 return static_cast<id_type>(units_.size()) | (id & LOWER_MASK);
1870 }
1871
1872 id_type unfixed_id = extras_head_;
1873 do {
1874 id_type offset = unfixed_id ^ labels_[0];
1875 if (is_valid_offset(id, offset)) {
1876 return offset;
1877 }
1878 unfixed_id = extras(unfixed_id).next();
1879 } while (unfixed_id != extras_head_);
1880
1881 return static_cast<id_type>(units_.size()) | (id & LOWER_MASK);
1882 }
1883
1884 inline bool DoubleArrayBuilder::is_valid_offset(id_type id,
1885 id_type offset) const {
1886 if (extras(offset).is_used()) {
1887 return false;
1888 }
1889
1890 id_type rel_offset = id ^ offset;
1891 if ((rel_offset & LOWER_MASK) && (rel_offset & UPPER_MASK)) {
1892 return false;
1893 }
1894
1895 for (std::size_t i = 1; i < labels_.size(); ++i) {
1896 if (extras(offset ^ labels_[i]).is_fixed()) {
1897 return false;
1898 }
1899 }
1900
1901 return true;
1902 }
1903
1904 inline void DoubleArrayBuilder::reserve_id(id_type id) {
1905 if (id >= units_.size()) {
1906 expand_units();
1907 }
1908
1909 if (id == extras_head_) {
1910 extras_head_ = extras(id).next();
1911 if (extras_head_ == id) {
1912 extras_head_ = static_cast<id_type>(units_.size());
1913 }
1914 }
1915 extras(extras(id).prev()).set_next(extras(id).next());
1916 extras(extras(id).next()).set_prev(extras(id).prev());
1917 extras(id).set_is_fixed(true);
1918 }
1919
1920 inline void DoubleArrayBuilder::expand_units() {
1921 id_type src_num_units = static_cast<id_type>(units_.size());
1922 id_type src_num_blocks = static_cast<id_type>(num_blocks());
1923
1924 id_type dest_num_units = src_num_units + BLOCK_SIZE;
1925 id_type dest_num_blocks = src_num_blocks + 1;
1926
1927 if (dest_num_blocks > NUM_EXTRA_BLOCKS) {
1928 fix_block(src_num_blocks - NUM_EXTRA_BLOCKS);
1929 }
1930
1931 units_.resize(dest_num_units);
1932
1933 if (dest_num_blocks > NUM_EXTRA_BLOCKS) {
1934 for (id_type id = src_num_units; id < dest_num_units; ++id) {
1935 extras(id).set_is_used(false);
1936 extras(id).set_is_fixed(false);
1937 }
1938 }
1939
1940 for (id_type i = src_num_units + 1; i < dest_num_units; ++i) {
1941 extras(i - 1).set_next(i);
1942 extras(i).set_prev(i - 1);
1943 }
1944
1945 extras(src_num_units).set_prev(dest_num_units - 1);
1946 extras(dest_num_units - 1).set_next(src_num_units);
1947
1948 extras(src_num_units).set_prev(extras(extras_head_).prev());
1949 extras(dest_num_units - 1).set_next(extras_head_);
1950
1951 extras(extras(extras_head_).prev()).set_next(src_num_units);
1952 extras(extras_head_).set_prev(dest_num_units - 1);
1953 }
1954
1955 inline void DoubleArrayBuilder::fix_all_blocks() {
1956 id_type begin = 0;
1957 if (num_blocks() > NUM_EXTRA_BLOCKS) {
1958 begin = static_cast<id_type>(num_blocks()) - NUM_EXTRA_BLOCKS;
1959 }
1960 id_type end = static_cast<id_type>(num_blocks());
1961
1962 for (id_type block_id = begin; block_id != end; ++block_id) {
1963 fix_block(block_id);
1964 }
1965 }
1966
1967 inline void DoubleArrayBuilder::fix_block(id_type block_id) {
1968 id_type begin = block_id * BLOCK_SIZE;
1969 id_type end = begin + BLOCK_SIZE;
1970
1971 id_type unused_offset = 0;
1972 for (id_type offset = begin; offset != end; ++offset) {
1973 if (!extras(offset).is_used()) {
1974 unused_offset = offset;
1975 break;
1976 }
1977 }
1978
1979 for (id_type id = begin; id != end; ++id) {
1980 if (!extras(id).is_fixed()) {
1981 reserve_id(id);
1982 units_[id].set_label(static_cast<uchar_type>(id ^ unused_offset));
1983 }
1984 }
1985 }
1986
1987 } // namespace Details
1988
1989 //
1990 // Member function build() of DoubleArrayImpl.
1991 //
1992
1993 template <typename A, typename B, typename T, typename C>
1994 int DoubleArrayImpl<A, B, T, C>::build(std::size_t num_keys,
1995 const key_type * const *keys, const std::size_t *lengths,
1996 const value_type *values, Details::progress_func_type progress_func) {
1997 Details::Keyset<value_type> keyset(num_keys, keys, lengths, values);
1998
1999 Details::DoubleArrayBuilder builder(progress_func);
2000 builder.build(keyset);
2001
2002 std::size_t size = 0;
2003 unit_type *buf = NULL;
2004 builder.copy(&size, &buf);
2005
2006 clear();
2007
2008 size_ = size;
2009 array_ = buf;
2010 buf_ = buf;
2011
2012 if (progress_func != NULL) {
2013 progress_func(num_keys + 1, num_keys + 1);
2014 }
2015
2016 return 0;
2017 }
2018
2019 } // namespace Darts
2020
2021 #undef DARTS_INT_TO_STR
2022 #undef DARTS_LINE_TO_STR
2023 #undef DARTS_LINE_STR
2024 #undef DARTS_THROW
2025
2026 #endif // DARTS_H_