1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
4 *******************************************************************************
5 * Copyright (C) 2010-2012, International Business Machines
6 * Corporation and others. All Rights Reserved.
7 *******************************************************************************
8 * file name: ucharstrie.h
10 * tab size: 8 (not used)
13 * created on: 2010nov14
14 * created by: Markus W. Scherer
17 #ifndef __UCHARSTRIE_H__
18 #define __UCHARSTRIE_H__
22 * \brief C++ API: Trie for mapping Unicode strings (or 16-bit-unit sequences)
26 #include "unicode/utypes.h"
27 #include "unicode/unistr.h"
28 #include "unicode/uobject.h"
29 #include "unicode/ustringtrie.h"
31 #if U_SHOW_CPLUSPLUS_API
35 class UCharsTrieBuilder
;
39 * Light-weight, non-const reader class for a UCharsTrie.
40 * Traverses a char16_t-serialized data structure with minimal state,
41 * for mapping strings (16-bit-unit sequences) to non-negative integer values.
43 * This class owns the serialized trie data only if it was constructed by
44 * the builder's build() method.
45 * The public constructor and the copy constructor only alias the data (only copy the pointer).
46 * There is no assignment operator.
48 * This class is not intended for public subclassing.
51 class U_COMMON_API UCharsTrie
: public UMemory
{
54 * Constructs a UCharsTrie reader instance.
56 * The trieUChars must contain a copy of a char16_t sequence from the UCharsTrieBuilder,
57 * starting with the first char16_t of that sequence.
58 * The UCharsTrie object will not read more char16_ts than
59 * the UCharsTrieBuilder generated in the corresponding build() call.
61 * The array is not copied/cloned and must not be modified while
62 * the UCharsTrie object is in use.
64 * @param trieUChars The char16_t array that contains the serialized trie.
67 UCharsTrie(ConstChar16Ptr trieUChars
)
68 : ownedArray_(NULL
), uchars_(trieUChars
),
69 pos_(uchars_
), remainingMatchLength_(-1) {}
78 * Copy constructor, copies the other trie reader object and its state,
79 * but not the char16_t array which will be shared. (Shallow copy.)
80 * @param other Another UCharsTrie object.
83 UCharsTrie(const UCharsTrie
&other
)
84 : ownedArray_(NULL
), uchars_(other
.uchars_
),
85 pos_(other
.pos_
), remainingMatchLength_(other
.remainingMatchLength_
) {}
88 * Resets this trie to its initial state.
94 remainingMatchLength_
=-1;
99 * UCharsTrie state object, for saving a trie's current state
100 * and resetting the trie back to this state later.
103 class State
: public UMemory
{
106 * Constructs an empty State.
109 State() { uchars
=NULL
; }
111 friend class UCharsTrie
;
113 const char16_t *uchars
;
115 int32_t remainingMatchLength
;
119 * Saves the state of this trie.
120 * @param state The State object to hold the trie's state.
125 const UCharsTrie
&saveState(State
&state
) const {
126 state
.uchars
=uchars_
;
128 state
.remainingMatchLength
=remainingMatchLength_
;
133 * Resets this trie to the saved state.
134 * If the state object contains no state, or the state of a different trie,
135 * then this trie remains unchanged.
136 * @param state The State object which holds a saved trie state.
142 UCharsTrie
&resetToState(const State
&state
) {
143 if(uchars_
==state
.uchars
&& uchars_
!=NULL
) {
145 remainingMatchLength_
=state
.remainingMatchLength
;
151 * Determines whether the string so far matches, whether it has a value,
152 * and whether another input char16_t can continue a matching string.
153 * @return The match/value Result.
156 UStringTrieResult
current() const;
159 * Traverses the trie from the initial state for this input char16_t.
160 * Equivalent to reset().next(uchar).
161 * @param uchar Input char value. Values below 0 and above 0xffff will never match.
162 * @return The match/value Result.
165 inline UStringTrieResult
first(int32_t uchar
) {
166 remainingMatchLength_
=-1;
167 return nextImpl(uchars_
, uchar
);
171 * Traverses the trie from the initial state for the
172 * one or two UTF-16 code units for this input code point.
173 * Equivalent to reset().nextForCodePoint(cp).
174 * @param cp A Unicode code point 0..0x10ffff.
175 * @return The match/value Result.
178 UStringTrieResult
firstForCodePoint(UChar32 cp
);
181 * Traverses the trie from the current state for this input char16_t.
182 * @param uchar Input char value. Values below 0 and above 0xffff will never match.
183 * @return The match/value Result.
186 UStringTrieResult
next(int32_t uchar
);
189 * Traverses the trie from the current state for the
190 * one or two UTF-16 code units for this input code point.
191 * @param cp A Unicode code point 0..0x10ffff.
192 * @return The match/value Result.
195 UStringTrieResult
nextForCodePoint(UChar32 cp
);
198 * Traverses the trie from the current state for this string.
201 * Result result=current();
203 * if(!USTRINGTRIE_HAS_NEXT(result)) return USTRINGTRIE_NO_MATCH;
207 * @param s A string. Can be NULL if length is 0.
208 * @param length The length of the string. Can be -1 if NUL-terminated.
209 * @return The match/value Result.
212 UStringTrieResult
next(ConstChar16Ptr s
, int32_t length
);
215 * Returns a matching string's value if called immediately after
216 * current()/first()/next() returned USTRINGTRIE_INTERMEDIATE_VALUE or USTRINGTRIE_FINAL_VALUE.
217 * getValue() can be called multiple times.
219 * Do not call getValue() after USTRINGTRIE_NO_MATCH or USTRINGTRIE_NO_VALUE!
220 * @return The value for the string so far.
223 inline int32_t getValue() const {
224 const char16_t *pos
=pos_
;
225 int32_t leadUnit
=*pos
++;
226 // U_ASSERT(leadUnit>=kMinValueLead);
227 return leadUnit
&kValueIsFinal
?
228 readValue(pos
, leadUnit
&0x7fff) : readNodeValue(pos
, leadUnit
);
232 * Determines whether all strings reachable from the current state
233 * map to the same value.
234 * @param uniqueValue Receives the unique value, if this function returns TRUE.
236 * @return TRUE if all strings reachable from the current state
237 * map to the same value.
240 inline UBool
hasUniqueValue(int32_t &uniqueValue
) const {
241 const char16_t *pos
=pos_
;
242 // Skip the rest of a pending linear-match node.
243 return pos
!=NULL
&& findUniqueValue(pos
+remainingMatchLength_
+1, FALSE
, uniqueValue
);
247 * Finds each char16_t which continues the string from the current state.
248 * That is, each char16_t c for which it would be next(c)!=USTRINGTRIE_NO_MATCH now.
249 * @param out Each next char16_t is appended to this object.
250 * @return the number of char16_ts which continue the string from here
253 int32_t getNextUChars(Appendable
&out
) const;
256 * Iterator for all of the (string, value) pairs in a UCharsTrie.
259 class U_COMMON_API Iterator
: public UMemory
{
262 * Iterates from the root of a char16_t-serialized UCharsTrie.
263 * @param trieUChars The trie char16_ts.
264 * @param maxStringLength If 0, the iterator returns full strings.
265 * Otherwise, the iterator returns strings with this maximum length.
266 * @param errorCode Standard ICU error code. Its input value must
267 * pass the U_SUCCESS() test, or else the function returns
268 * immediately. Check for U_FAILURE() on output or use with
269 * function chaining. (See User Guide for details.)
272 Iterator(ConstChar16Ptr trieUChars
, int32_t maxStringLength
, UErrorCode
&errorCode
);
275 * Iterates from the current state of the specified UCharsTrie.
276 * @param trie The trie whose state will be copied for iteration.
277 * @param maxStringLength If 0, the iterator returns full strings.
278 * Otherwise, the iterator returns strings with this maximum length.
279 * @param errorCode Standard ICU error code. Its input value must
280 * pass the U_SUCCESS() test, or else the function returns
281 * immediately. Check for U_FAILURE() on output or use with
282 * function chaining. (See User Guide for details.)
285 Iterator(const UCharsTrie
&trie
, int32_t maxStringLength
, UErrorCode
&errorCode
);
294 * Resets this iterator to its initial state.
301 * @return TRUE if there are more elements.
304 UBool
hasNext() const;
307 * Finds the next (string, value) pair if there is one.
309 * If the string is truncated to the maximum length and does not
310 * have a real value, then the value is set to -1.
311 * In this case, this "not a real value" is indistinguishable from
312 * a real value of -1.
313 * @param errorCode Standard ICU error code. Its input value must
314 * pass the U_SUCCESS() test, or else the function returns
315 * immediately. Check for U_FAILURE() on output or use with
316 * function chaining. (See User Guide for details.)
317 * @return TRUE if there is another element.
320 UBool
next(UErrorCode
&errorCode
);
323 * @return The string for the last successful next().
326 const UnicodeString
&getString() const { return str_
; }
328 * @return The value for the last successful next().
331 int32_t getValue() const { return value_
; }
334 UBool
truncateAndStop() {
336 value_
=-1; // no real value for str
340 const char16_t *branchNext(const char16_t *pos
, int32_t length
, UErrorCode
&errorCode
);
342 const char16_t *uchars_
;
343 const char16_t *pos_
;
344 const char16_t *initialPos_
;
345 int32_t remainingMatchLength_
;
346 int32_t initialRemainingMatchLength_
;
347 UBool skipValue_
; // Skip intermediate value which was already delivered.
353 // The stack stores pairs of integers for backtracking to another
354 // outbound edge of a branch node.
355 // The first integer is an offset from uchars_.
356 // The second integer has the str_.length() from before the node in bits 15..0,
357 // and the remaining branch length in bits 31..16.
358 // (We could store the remaining branch length minus 1 in bits 30..16 and not use the sign bit,
359 // but the code looks more confusing that way.)
364 friend class UCharsTrieBuilder
;
367 * Constructs a UCharsTrie reader instance.
368 * Unlike the public constructor which just aliases an array,
369 * this constructor adopts the builder's array.
370 * This constructor is only called by the builder.
372 UCharsTrie(char16_t *adoptUChars
, const char16_t *trieUChars
)
373 : ownedArray_(adoptUChars
), uchars_(trieUChars
),
374 pos_(uchars_
), remainingMatchLength_(-1) {}
376 // No assignment operator.
377 UCharsTrie
&operator=(const UCharsTrie
&other
);
383 // Reads a compact 32-bit integer.
384 // pos is already after the leadUnit, and the lead unit has bit 15 reset.
385 static inline int32_t readValue(const char16_t *pos
, int32_t leadUnit
) {
387 if(leadUnit
<kMinTwoUnitValueLead
) {
389 } else if(leadUnit
<kThreeUnitValueLead
) {
390 value
=((leadUnit
-kMinTwoUnitValueLead
)<<16)|*pos
;
392 value
=(pos
[0]<<16)|pos
[1];
396 static inline const char16_t *skipValue(const char16_t *pos
, int32_t leadUnit
) {
397 if(leadUnit
>=kMinTwoUnitValueLead
) {
398 if(leadUnit
<kThreeUnitValueLead
) {
406 static inline const char16_t *skipValue(const char16_t *pos
) {
407 int32_t leadUnit
=*pos
++;
408 return skipValue(pos
, leadUnit
&0x7fff);
411 static inline int32_t readNodeValue(const char16_t *pos
, int32_t leadUnit
) {
412 // U_ASSERT(kMinValueLead<=leadUnit && leadUnit<kValueIsFinal);
414 if(leadUnit
<kMinTwoUnitNodeValueLead
) {
415 value
=(leadUnit
>>6)-1;
416 } else if(leadUnit
<kThreeUnitNodeValueLead
) {
417 value
=(((leadUnit
&0x7fc0)-kMinTwoUnitNodeValueLead
)<<10)|*pos
;
419 value
=(pos
[0]<<16)|pos
[1];
423 static inline const char16_t *skipNodeValue(const char16_t *pos
, int32_t leadUnit
) {
424 // U_ASSERT(kMinValueLead<=leadUnit && leadUnit<kValueIsFinal);
425 if(leadUnit
>=kMinTwoUnitNodeValueLead
) {
426 if(leadUnit
<kThreeUnitNodeValueLead
) {
435 static inline const char16_t *jumpByDelta(const char16_t *pos
) {
436 int32_t delta
=*pos
++;
437 if(delta
>=kMinTwoUnitDeltaLead
) {
438 if(delta
==kThreeUnitDeltaLead
) {
439 delta
=(pos
[0]<<16)|pos
[1];
442 delta
=((delta
-kMinTwoUnitDeltaLead
)<<16)|*pos
++;
448 static const char16_t *skipDelta(const char16_t *pos
) {
449 int32_t delta
=*pos
++;
450 if(delta
>=kMinTwoUnitDeltaLead
) {
451 if(delta
==kThreeUnitDeltaLead
) {
460 static inline UStringTrieResult
valueResult(int32_t node
) {
461 return (UStringTrieResult
)(USTRINGTRIE_INTERMEDIATE_VALUE
-(node
>>15));
464 // Handles a branch node for both next(uchar) and next(string).
465 UStringTrieResult
branchNext(const char16_t *pos
, int32_t length
, int32_t uchar
);
467 // Requires remainingLength_<0.
468 UStringTrieResult
nextImpl(const char16_t *pos
, int32_t uchar
);
470 // Helper functions for hasUniqueValue().
471 // Recursively finds a unique value (or whether there is not a unique one)
473 static const char16_t *findUniqueValueFromBranch(const char16_t *pos
, int32_t length
,
474 UBool haveUniqueValue
, int32_t &uniqueValue
);
475 // Recursively finds a unique value (or whether there is not a unique one)
476 // starting from a position on a node lead unit.
477 static UBool
findUniqueValue(const char16_t *pos
, UBool haveUniqueValue
, int32_t &uniqueValue
);
479 // Helper functions for getNextUChars().
480 // getNextUChars() when pos is on a branch node.
481 static void getNextBranchUChars(const char16_t *pos
, int32_t length
, Appendable
&out
);
483 // UCharsTrie data structure
485 // The trie consists of a series of char16_t-serialized nodes for incremental
486 // Unicode string/char16_t sequence matching. (char16_t=16-bit unsigned integer)
487 // The root node is at the beginning of the trie data.
489 // Types of nodes are distinguished by their node lead unit ranges.
490 // After each node, except a final-value node, another node follows to
491 // encode match values or continue matching further units.
494 // - Final-value node: Stores a 32-bit integer in a compact, variable-length format.
495 // The value is for the string/char16_t sequence so far.
496 // - Match node, optionally with an intermediate value in a different compact format.
497 // The value, if present, is for the string/char16_t sequence so far.
499 // Aside from the value, which uses the node lead unit's high bits:
501 // - Linear-match node: Matches a number of units.
502 // - Branch node: Branches to other nodes according to the current input unit.
503 // The node unit is the length of the branch (number of units to select from)
504 // minus 1. It is followed by a sub-node:
505 // - If the length is at most kMaxBranchLinearSubNodeLength, then
506 // there are length-1 (key, value) pairs and then one more comparison unit.
507 // If one of the key units matches, then the value is either a final value for
508 // the string so far, or a "jump" delta to the next node.
509 // If the last unit matches, then matching continues with the next node.
510 // (Values have the same encoding as final-value nodes.)
511 // - If the length is greater than kMaxBranchLinearSubNodeLength, then
512 // there is one unit and one "jump" delta.
513 // If the input unit is less than the sub-node unit, then "jump" by delta to
514 // the next sub-node which will have a length of length/2.
515 // (The delta has its own compact encoding.)
516 // Otherwise, skip the "jump" delta to the next sub-node
517 // which will have a length of length-length/2.
519 // Match-node lead unit values, after masking off intermediate-value bits:
521 // 0000..002f: Branch node. If node!=0 then the length is node+1, otherwise
522 // the length is one more than the next unit.
524 // For a branch sub-node with at most this many entries, we drop down
525 // to a linear search.
526 static const int32_t kMaxBranchLinearSubNodeLength
=5;
528 // 0030..003f: Linear-match node, match 1..16 units and continue reading the next node.
529 static const int32_t kMinLinearMatch
=0x30;
530 static const int32_t kMaxLinearMatchLength
=0x10;
532 // Match-node lead unit bits 14..6 for the optional intermediate value.
533 // If these bits are 0, then there is no intermediate value.
534 // Otherwise, see the *NodeValue* constants below.
535 static const int32_t kMinValueLead
=kMinLinearMatch
+kMaxLinearMatchLength
; // 0x0040
536 static const int32_t kNodeTypeMask
=kMinValueLead
-1; // 0x003f
538 // A final-value node has bit 15 set.
539 static const int32_t kValueIsFinal
=0x8000;
541 // Compact value: After testing and masking off bit 15, use the following thresholds.
542 static const int32_t kMaxOneUnitValue
=0x3fff;
544 static const int32_t kMinTwoUnitValueLead
=kMaxOneUnitValue
+1; // 0x4000
545 static const int32_t kThreeUnitValueLead
=0x7fff;
547 static const int32_t kMaxTwoUnitValue
=((kThreeUnitValueLead
-kMinTwoUnitValueLead
)<<16)-1; // 0x3ffeffff
549 // Compact intermediate-value integer, lead unit shared with a branch or linear-match node.
550 static const int32_t kMaxOneUnitNodeValue
=0xff;
551 static const int32_t kMinTwoUnitNodeValueLead
=kMinValueLead
+((kMaxOneUnitNodeValue
+1)<<6); // 0x4040
552 static const int32_t kThreeUnitNodeValueLead
=0x7fc0;
554 static const int32_t kMaxTwoUnitNodeValue
=
555 ((kThreeUnitNodeValueLead
-kMinTwoUnitNodeValueLead
)<<10)-1; // 0xfdffff
557 // Compact delta integers.
558 static const int32_t kMaxOneUnitDelta
=0xfbff;
559 static const int32_t kMinTwoUnitDeltaLead
=kMaxOneUnitDelta
+1; // 0xfc00
560 static const int32_t kThreeUnitDeltaLead
=0xffff;
562 static const int32_t kMaxTwoUnitDelta
=((kThreeUnitDeltaLead
-kMinTwoUnitDeltaLead
)<<16)-1; // 0x03feffff
564 char16_t *ownedArray_
;
566 // Fixed value referencing the UCharsTrie words.
567 const char16_t *uchars_
;
569 // Iterator variables.
571 // Pointer to next trie unit to read. NULL if no more matches.
572 const char16_t *pos_
;
573 // Remaining length of a linear-match node, minus 1. Negative if not in such a node.
574 int32_t remainingMatchLength_
;
578 #endif // U_SHOW_CPLUSPLUS_API
580 #endif // __UCHARSTRIE_H__