ucharstrie.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. /*
  2. *******************************************************************************
  3. * Copyright (C) 2010-2012, International Business Machines
  4. * Corporation and others. All Rights Reserved.
  5. *******************************************************************************
  6. * file name: ucharstrie.h
  7. * encoding: US-ASCII
  8. * tab size: 8 (not used)
  9. * indentation:4
  10. *
  11. * created on: 2010nov14
  12. * created by: Markus W. Scherer
  13. */
  14. #ifndef __UCHARSTRIE_H__
  15. #define __UCHARSTRIE_H__
  16. /**
  17. * \file
  18. * \brief C++ API: Trie for mapping Unicode strings (or 16-bit-unit sequences)
  19. * to integer values.
  20. */
  21. #include "unicode/utypes.h"
  22. #include "unicode/unistr.h"
  23. #include "unicode/uobject.h"
  24. #include "unicode/ustringtrie.h"
  25. U_NAMESPACE_BEGIN
  26. class Appendable;
  27. class UCharsTrieBuilder;
  28. class UVector32;
  29. /**
  30. * Light-weight, non-const reader class for a UCharsTrie.
  31. * Traverses a UChar-serialized data structure with minimal state,
  32. * for mapping strings (16-bit-unit sequences) to non-negative integer values.
  33. *
  34. * This class owns the serialized trie data only if it was constructed by
  35. * the builder's build() method.
  36. * The public constructor and the copy constructor only alias the data (only copy the pointer).
  37. * There is no assignment operator.
  38. *
  39. * This class is not intended for public subclassing.
  40. * @stable ICU 4.8
  41. */
  42. class U_COMMON_API UCharsTrie : public UMemory {
  43. public:
  44. /**
  45. * Constructs a UCharsTrie reader instance.
  46. *
  47. * The trieUChars must contain a copy of a UChar sequence from the UCharsTrieBuilder,
  48. * starting with the first UChar of that sequence.
  49. * The UCharsTrie object will not read more UChars than
  50. * the UCharsTrieBuilder generated in the corresponding build() call.
  51. *
  52. * The array is not copied/cloned and must not be modified while
  53. * the UCharsTrie object is in use.
  54. *
  55. * @param trieUChars The UChar array that contains the serialized trie.
  56. * @stable ICU 4.8
  57. */
  58. UCharsTrie(const UChar *trieUChars)
  59. : ownedArray_(NULL), uchars_(trieUChars),
  60. pos_(uchars_), remainingMatchLength_(-1) {}
  61. /**
  62. * Destructor.
  63. * @stable ICU 4.8
  64. */
  65. ~UCharsTrie();
  66. /**
  67. * Copy constructor, copies the other trie reader object and its state,
  68. * but not the UChar array which will be shared. (Shallow copy.)
  69. * @param other Another UCharsTrie object.
  70. * @stable ICU 4.8
  71. */
  72. UCharsTrie(const UCharsTrie &other)
  73. : ownedArray_(NULL), uchars_(other.uchars_),
  74. pos_(other.pos_), remainingMatchLength_(other.remainingMatchLength_) {}
  75. /**
  76. * Resets this trie to its initial state.
  77. * @return *this
  78. * @stable ICU 4.8
  79. */
  80. UCharsTrie &reset() {
  81. pos_=uchars_;
  82. remainingMatchLength_=-1;
  83. return *this;
  84. }
  85. /**
  86. * UCharsTrie state object, for saving a trie's current state
  87. * and resetting the trie back to this state later.
  88. * @stable ICU 4.8
  89. */
  90. class State : public UMemory {
  91. public:
  92. /**
  93. * Constructs an empty State.
  94. * @stable ICU 4.8
  95. */
  96. State() { uchars=NULL; }
  97. private:
  98. friend class UCharsTrie;
  99. const UChar *uchars;
  100. const UChar *pos;
  101. int32_t remainingMatchLength;
  102. };
  103. /**
  104. * Saves the state of this trie.
  105. * @param state The State object to hold the trie's state.
  106. * @return *this
  107. * @see resetToState
  108. * @stable ICU 4.8
  109. */
  110. const UCharsTrie &saveState(State &state) const {
  111. state.uchars=uchars_;
  112. state.pos=pos_;
  113. state.remainingMatchLength=remainingMatchLength_;
  114. return *this;
  115. }
  116. /**
  117. * Resets this trie to the saved state.
  118. * If the state object contains no state, or the state of a different trie,
  119. * then this trie remains unchanged.
  120. * @param state The State object which holds a saved trie state.
  121. * @return *this
  122. * @see saveState
  123. * @see reset
  124. * @stable ICU 4.8
  125. */
  126. UCharsTrie &resetToState(const State &state) {
  127. if(uchars_==state.uchars && uchars_!=NULL) {
  128. pos_=state.pos;
  129. remainingMatchLength_=state.remainingMatchLength;
  130. }
  131. return *this;
  132. }
  133. /**
  134. * Determines whether the string so far matches, whether it has a value,
  135. * and whether another input UChar can continue a matching string.
  136. * @return The match/value Result.
  137. * @stable ICU 4.8
  138. */
  139. UStringTrieResult current() const;
  140. /**
  141. * Traverses the trie from the initial state for this input UChar.
  142. * Equivalent to reset().next(uchar).
  143. * @param uchar Input char value. Values below 0 and above 0xffff will never match.
  144. * @return The match/value Result.
  145. * @stable ICU 4.8
  146. */
  147. inline UStringTrieResult first(int32_t uchar) {
  148. remainingMatchLength_=-1;
  149. return nextImpl(uchars_, uchar);
  150. }
  151. /**
  152. * Traverses the trie from the initial state for the
  153. * one or two UTF-16 code units for this input code point.
  154. * Equivalent to reset().nextForCodePoint(cp).
  155. * @param cp A Unicode code point 0..0x10ffff.
  156. * @return The match/value Result.
  157. * @stable ICU 4.8
  158. */
  159. UStringTrieResult firstForCodePoint(UChar32 cp);
  160. /**
  161. * Traverses the trie from the current state for this input UChar.
  162. * @param uchar Input char value. Values below 0 and above 0xffff will never match.
  163. * @return The match/value Result.
  164. * @stable ICU 4.8
  165. */
  166. UStringTrieResult next(int32_t uchar);
  167. /**
  168. * Traverses the trie from the current state for the
  169. * one or two UTF-16 code units for this input code point.
  170. * @param cp A Unicode code point 0..0x10ffff.
  171. * @return The match/value Result.
  172. * @stable ICU 4.8
  173. */
  174. UStringTrieResult nextForCodePoint(UChar32 cp);
  175. /**
  176. * Traverses the trie from the current state for this string.
  177. * Equivalent to
  178. * \code
  179. * Result result=current();
  180. * for(each c in s)
  181. * if(!USTRINGTRIE_HAS_NEXT(result)) return USTRINGTRIE_NO_MATCH;
  182. * result=next(c);
  183. * return result;
  184. * \endcode
  185. * @param s A string. Can be NULL if length is 0.
  186. * @param length The length of the string. Can be -1 if NUL-terminated.
  187. * @return The match/value Result.
  188. * @stable ICU 4.8
  189. */
  190. UStringTrieResult next(const UChar *s, int32_t length);
  191. /**
  192. * Returns a matching string's value if called immediately after
  193. * current()/first()/next() returned USTRINGTRIE_INTERMEDIATE_VALUE or USTRINGTRIE_FINAL_VALUE.
  194. * getValue() can be called multiple times.
  195. *
  196. * Do not call getValue() after USTRINGTRIE_NO_MATCH or USTRINGTRIE_NO_VALUE!
  197. * @return The value for the string so far.
  198. * @stable ICU 4.8
  199. */
  200. inline int32_t getValue() const {
  201. const UChar *pos=pos_;
  202. int32_t leadUnit=*pos++;
  203. // U_ASSERT(leadUnit>=kMinValueLead);
  204. return leadUnit&kValueIsFinal ?
  205. readValue(pos, leadUnit&0x7fff) : readNodeValue(pos, leadUnit);
  206. }
  207. /**
  208. * Determines whether all strings reachable from the current state
  209. * map to the same value.
  210. * @param uniqueValue Receives the unique value, if this function returns TRUE.
  211. * (output-only)
  212. * @return TRUE if all strings reachable from the current state
  213. * map to the same value.
  214. * @stable ICU 4.8
  215. */
  216. inline UBool hasUniqueValue(int32_t &uniqueValue) const {
  217. const UChar *pos=pos_;
  218. // Skip the rest of a pending linear-match node.
  219. return pos!=NULL && findUniqueValue(pos+remainingMatchLength_+1, FALSE, uniqueValue);
  220. }
  221. /**
  222. * Finds each UChar which continues the string from the current state.
  223. * That is, each UChar c for which it would be next(c)!=USTRINGTRIE_NO_MATCH now.
  224. * @param out Each next UChar is appended to this object.
  225. * @return the number of UChars which continue the string from here
  226. * @stable ICU 4.8
  227. */
  228. int32_t getNextUChars(Appendable &out) const;
  229. /**
  230. * Iterator for all of the (string, value) pairs in a UCharsTrie.
  231. * @stable ICU 4.8
  232. */
  233. class U_COMMON_API Iterator : public UMemory {
  234. public:
  235. /**
  236. * Iterates from the root of a UChar-serialized UCharsTrie.
  237. * @param trieUChars The trie UChars.
  238. * @param maxStringLength If 0, the iterator returns full strings.
  239. * Otherwise, the iterator returns strings with this maximum length.
  240. * @param errorCode Standard ICU error code. Its input value must
  241. * pass the U_SUCCESS() test, or else the function returns
  242. * immediately. Check for U_FAILURE() on output or use with
  243. * function chaining. (See User Guide for details.)
  244. * @stable ICU 4.8
  245. */
  246. Iterator(const UChar *trieUChars, int32_t maxStringLength, UErrorCode &errorCode);
  247. /**
  248. * Iterates from the current state of the specified UCharsTrie.
  249. * @param trie The trie whose state will be copied for iteration.
  250. * @param maxStringLength If 0, the iterator returns full strings.
  251. * Otherwise, the iterator returns strings with this maximum length.
  252. * @param errorCode Standard ICU error code. Its input value must
  253. * pass the U_SUCCESS() test, or else the function returns
  254. * immediately. Check for U_FAILURE() on output or use with
  255. * function chaining. (See User Guide for details.)
  256. * @stable ICU 4.8
  257. */
  258. Iterator(const UCharsTrie &trie, int32_t maxStringLength, UErrorCode &errorCode);
  259. /**
  260. * Destructor.
  261. * @stable ICU 4.8
  262. */
  263. ~Iterator();
  264. /**
  265. * Resets this iterator to its initial state.
  266. * @return *this
  267. * @stable ICU 4.8
  268. */
  269. Iterator &reset();
  270. /**
  271. * @return TRUE if there are more elements.
  272. * @stable ICU 4.8
  273. */
  274. UBool hasNext() const;
  275. /**
  276. * Finds the next (string, value) pair if there is one.
  277. *
  278. * If the string is truncated to the maximum length and does not
  279. * have a real value, then the value is set to -1.
  280. * In this case, this "not a real value" is indistinguishable from
  281. * a real value of -1.
  282. * @param errorCode Standard ICU error code. Its input value must
  283. * pass the U_SUCCESS() test, or else the function returns
  284. * immediately. Check for U_FAILURE() on output or use with
  285. * function chaining. (See User Guide for details.)
  286. * @return TRUE if there is another element.
  287. * @stable ICU 4.8
  288. */
  289. UBool next(UErrorCode &errorCode);
  290. /**
  291. * @return The string for the last successful next().
  292. * @stable ICU 4.8
  293. */
  294. const UnicodeString &getString() const { return str_; }
  295. /**
  296. * @return The value for the last successful next().
  297. * @stable ICU 4.8
  298. */
  299. int32_t getValue() const { return value_; }
  300. private:
  301. UBool truncateAndStop() {
  302. pos_=NULL;
  303. value_=-1; // no real value for str
  304. return TRUE;
  305. }
  306. const UChar *branchNext(const UChar *pos, int32_t length, UErrorCode &errorCode);
  307. const UChar *uchars_;
  308. const UChar *pos_;
  309. const UChar *initialPos_;
  310. int32_t remainingMatchLength_;
  311. int32_t initialRemainingMatchLength_;
  312. UBool skipValue_; // Skip intermediate value which was already delivered.
  313. UnicodeString str_;
  314. int32_t maxLength_;
  315. int32_t value_;
  316. // The stack stores pairs of integers for backtracking to another
  317. // outbound edge of a branch node.
  318. // The first integer is an offset from uchars_.
  319. // The second integer has the str_.length() from before the node in bits 15..0,
  320. // and the remaining branch length in bits 31..16.
  321. // (We could store the remaining branch length minus 1 in bits 30..16 and not use the sign bit,
  322. // but the code looks more confusing that way.)
  323. UVector32 *stack_;
  324. };
  325. private:
  326. friend class UCharsTrieBuilder;
  327. /**
  328. * Constructs a UCharsTrie reader instance.
  329. * Unlike the public constructor which just aliases an array,
  330. * this constructor adopts the builder's array.
  331. * This constructor is only called by the builder.
  332. */
  333. UCharsTrie(UChar *adoptUChars, const UChar *trieUChars)
  334. : ownedArray_(adoptUChars), uchars_(trieUChars),
  335. pos_(uchars_), remainingMatchLength_(-1) {}
  336. // No assignment operator.
  337. UCharsTrie &operator=(const UCharsTrie &other);
  338. inline void stop() {
  339. pos_=NULL;
  340. }
  341. // Reads a compact 32-bit integer.
  342. // pos is already after the leadUnit, and the lead unit has bit 15 reset.
  343. static inline int32_t readValue(const UChar *pos, int32_t leadUnit) {
  344. int32_t value;
  345. if(leadUnit<kMinTwoUnitValueLead) {
  346. value=leadUnit;
  347. } else if(leadUnit<kThreeUnitValueLead) {
  348. value=((leadUnit-kMinTwoUnitValueLead)<<16)|*pos;
  349. } else {
  350. value=(pos[0]<<16)|pos[1];
  351. }
  352. return value;
  353. }
  354. static inline const UChar *skipValue(const UChar *pos, int32_t leadUnit) {
  355. if(leadUnit>=kMinTwoUnitValueLead) {
  356. if(leadUnit<kThreeUnitValueLead) {
  357. ++pos;
  358. } else {
  359. pos+=2;
  360. }
  361. }
  362. return pos;
  363. }
  364. static inline const UChar *skipValue(const UChar *pos) {
  365. int32_t leadUnit=*pos++;
  366. return skipValue(pos, leadUnit&0x7fff);
  367. }
  368. static inline int32_t readNodeValue(const UChar *pos, int32_t leadUnit) {
  369. // U_ASSERT(kMinValueLead<=leadUnit && leadUnit<kValueIsFinal);
  370. int32_t value;
  371. if(leadUnit<kMinTwoUnitNodeValueLead) {
  372. value=(leadUnit>>6)-1;
  373. } else if(leadUnit<kThreeUnitNodeValueLead) {
  374. value=(((leadUnit&0x7fc0)-kMinTwoUnitNodeValueLead)<<10)|*pos;
  375. } else {
  376. value=(pos[0]<<16)|pos[1];
  377. }
  378. return value;
  379. }
  380. static inline const UChar *skipNodeValue(const UChar *pos, int32_t leadUnit) {
  381. // U_ASSERT(kMinValueLead<=leadUnit && leadUnit<kValueIsFinal);
  382. if(leadUnit>=kMinTwoUnitNodeValueLead) {
  383. if(leadUnit<kThreeUnitNodeValueLead) {
  384. ++pos;
  385. } else {
  386. pos+=2;
  387. }
  388. }
  389. return pos;
  390. }
  391. static inline const UChar *jumpByDelta(const UChar *pos) {
  392. int32_t delta=*pos++;
  393. if(delta>=kMinTwoUnitDeltaLead) {
  394. if(delta==kThreeUnitDeltaLead) {
  395. delta=(pos[0]<<16)|pos[1];
  396. pos+=2;
  397. } else {
  398. delta=((delta-kMinTwoUnitDeltaLead)<<16)|*pos++;
  399. }
  400. }
  401. return pos+delta;
  402. }
  403. static const UChar *skipDelta(const UChar *pos) {
  404. int32_t delta=*pos++;
  405. if(delta>=kMinTwoUnitDeltaLead) {
  406. if(delta==kThreeUnitDeltaLead) {
  407. pos+=2;
  408. } else {
  409. ++pos;
  410. }
  411. }
  412. return pos;
  413. }
  414. static inline UStringTrieResult valueResult(int32_t node) {
  415. return (UStringTrieResult)(USTRINGTRIE_INTERMEDIATE_VALUE-(node>>15));
  416. }
  417. // Handles a branch node for both next(uchar) and next(string).
  418. UStringTrieResult branchNext(const UChar *pos, int32_t length, int32_t uchar);
  419. // Requires remainingLength_<0.
  420. UStringTrieResult nextImpl(const UChar *pos, int32_t uchar);
  421. // Helper functions for hasUniqueValue().
  422. // Recursively finds a unique value (or whether there is not a unique one)
  423. // from a branch.
  424. static const UChar *findUniqueValueFromBranch(const UChar *pos, int32_t length,
  425. UBool haveUniqueValue, int32_t &uniqueValue);
  426. // Recursively finds a unique value (or whether there is not a unique one)
  427. // starting from a position on a node lead unit.
  428. static UBool findUniqueValue(const UChar *pos, UBool haveUniqueValue, int32_t &uniqueValue);
  429. // Helper functions for getNextUChars().
  430. // getNextUChars() when pos is on a branch node.
  431. static void getNextBranchUChars(const UChar *pos, int32_t length, Appendable &out);
  432. // UCharsTrie data structure
  433. //
  434. // The trie consists of a series of UChar-serialized nodes for incremental
  435. // Unicode string/UChar sequence matching. (UChar=16-bit unsigned integer)
  436. // The root node is at the beginning of the trie data.
  437. //
  438. // Types of nodes are distinguished by their node lead unit ranges.
  439. // After each node, except a final-value node, another node follows to
  440. // encode match values or continue matching further units.
  441. //
  442. // Node types:
  443. // - Final-value node: Stores a 32-bit integer in a compact, variable-length format.
  444. // The value is for the string/UChar sequence so far.
  445. // - Match node, optionally with an intermediate value in a different compact format.
  446. // The value, if present, is for the string/UChar sequence so far.
  447. //
  448. // Aside from the value, which uses the node lead unit's high bits:
  449. //
  450. // - Linear-match node: Matches a number of units.
  451. // - Branch node: Branches to other nodes according to the current input unit.
  452. // The node unit is the length of the branch (number of units to select from)
  453. // minus 1. It is followed by a sub-node:
  454. // - If the length is at most kMaxBranchLinearSubNodeLength, then
  455. // there are length-1 (key, value) pairs and then one more comparison unit.
  456. // If one of the key units matches, then the value is either a final value for
  457. // the string so far, or a "jump" delta to the next node.
  458. // If the last unit matches, then matching continues with the next node.
  459. // (Values have the same encoding as final-value nodes.)
  460. // - If the length is greater than kMaxBranchLinearSubNodeLength, then
  461. // there is one unit and one "jump" delta.
  462. // If the input unit is less than the sub-node unit, then "jump" by delta to
  463. // the next sub-node which will have a length of length/2.
  464. // (The delta has its own compact encoding.)
  465. // Otherwise, skip the "jump" delta to the next sub-node
  466. // which will have a length of length-length/2.
  467. // Match-node lead unit values, after masking off intermediate-value bits:
  468. // 0000..002f: Branch node. If node!=0 then the length is node+1, otherwise
  469. // the length is one more than the next unit.
  470. // For a branch sub-node with at most this many entries, we drop down
  471. // to a linear search.
  472. static const int32_t kMaxBranchLinearSubNodeLength=5;
  473. // 0030..003f: Linear-match node, match 1..16 units and continue reading the next node.
  474. static const int32_t kMinLinearMatch=0x30;
  475. static const int32_t kMaxLinearMatchLength=0x10;
  476. // Match-node lead unit bits 14..6 for the optional intermediate value.
  477. // If these bits are 0, then there is no intermediate value.
  478. // Otherwise, see the *NodeValue* constants below.
  479. static const int32_t kMinValueLead=kMinLinearMatch+kMaxLinearMatchLength; // 0x0040
  480. static const int32_t kNodeTypeMask=kMinValueLead-1; // 0x003f
  481. // A final-value node has bit 15 set.
  482. static const int32_t kValueIsFinal=0x8000;
  483. // Compact value: After testing and masking off bit 15, use the following thresholds.
  484. static const int32_t kMaxOneUnitValue=0x3fff;
  485. static const int32_t kMinTwoUnitValueLead=kMaxOneUnitValue+1; // 0x4000
  486. static const int32_t kThreeUnitValueLead=0x7fff;
  487. static const int32_t kMaxTwoUnitValue=((kThreeUnitValueLead-kMinTwoUnitValueLead)<<16)-1; // 0x3ffeffff
  488. // Compact intermediate-value integer, lead unit shared with a branch or linear-match node.
  489. static const int32_t kMaxOneUnitNodeValue=0xff;
  490. static const int32_t kMinTwoUnitNodeValueLead=kMinValueLead+((kMaxOneUnitNodeValue+1)<<6); // 0x4040
  491. static const int32_t kThreeUnitNodeValueLead=0x7fc0;
  492. static const int32_t kMaxTwoUnitNodeValue=
  493. ((kThreeUnitNodeValueLead-kMinTwoUnitNodeValueLead)<<10)-1; // 0xfdffff
  494. // Compact delta integers.
  495. static const int32_t kMaxOneUnitDelta=0xfbff;
  496. static const int32_t kMinTwoUnitDeltaLead=kMaxOneUnitDelta+1; // 0xfc00
  497. static const int32_t kThreeUnitDeltaLead=0xffff;
  498. static const int32_t kMaxTwoUnitDelta=((kThreeUnitDeltaLead-kMinTwoUnitDeltaLead)<<16)-1; // 0x03feffff
  499. UChar *ownedArray_;
  500. // Fixed value referencing the UCharsTrie words.
  501. const UChar *uchars_;
  502. // Iterator variables.
  503. // Pointer to next trie unit to read. NULL if no more matches.
  504. const UChar *pos_;
  505. // Remaining length of a linear-match node, minus 1. Negative if not in such a node.
  506. int32_t remainingMatchLength_;
  507. };
  508. U_NAMESPACE_END
  509. #endif // __UCHARSTRIE_H__