ucharstrie.h 21 KB

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