bytestrie.h 21 KB

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