bytestrie.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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. class BytesTrieTest;
  28. U_NAMESPACE_BEGIN
  29. class ByteSink;
  30. class BytesTrieBuilder;
  31. class CharString;
  32. class UVector32;
  33. /**
  34. * Light-weight, non-const reader class for a BytesTrie.
  35. * Traverses a byte-serialized data structure with minimal state,
  36. * for mapping byte sequences to non-negative integer values.
  37. *
  38. * This class owns the serialized trie data only if it was constructed by
  39. * the builder's build() method.
  40. * The public constructor and the copy constructor only alias the data (only copy the pointer).
  41. * There is no assignment operator.
  42. *
  43. * This class is not intended for public subclassing.
  44. * @stable ICU 4.8
  45. */
  46. class U_COMMON_API BytesTrie : public UMemory {
  47. public:
  48. /**
  49. * Constructs a BytesTrie reader instance.
  50. *
  51. * The trieBytes must contain a copy of a byte sequence from the BytesTrieBuilder,
  52. * starting with the first byte of that sequence.
  53. * The BytesTrie object will not read more bytes than
  54. * the BytesTrieBuilder generated in the corresponding build() call.
  55. *
  56. * The array is not copied/cloned and must not be modified while
  57. * the BytesTrie object is in use.
  58. *
  59. * @param trieBytes The byte array that contains the serialized trie.
  60. * @stable ICU 4.8
  61. */
  62. BytesTrie(const void *trieBytes)
  63. : ownedArray_(nullptr), bytes_(static_cast<const uint8_t *>(trieBytes)),
  64. pos_(bytes_), remainingMatchLength_(-1) {}
  65. /**
  66. * Destructor.
  67. * @stable ICU 4.8
  68. */
  69. ~BytesTrie();
  70. /**
  71. * Copy constructor, copies the other trie reader object and its state,
  72. * but not the byte array which will be shared. (Shallow copy.)
  73. * @param other Another BytesTrie object.
  74. * @stable ICU 4.8
  75. */
  76. BytesTrie(const BytesTrie &other)
  77. : ownedArray_(nullptr), bytes_(other.bytes_),
  78. pos_(other.pos_), remainingMatchLength_(other.remainingMatchLength_) {}
  79. /**
  80. * Resets this trie to its initial state.
  81. * @return *this
  82. * @stable ICU 4.8
  83. */
  84. BytesTrie &reset() {
  85. pos_=bytes_;
  86. remainingMatchLength_=-1;
  87. return *this;
  88. }
  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. * @stable 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. * @stable 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. /**
  121. * BytesTrie state object, for saving a trie's current state
  122. * and resetting the trie back to this state later.
  123. * @stable ICU 4.8
  124. */
  125. class State : public UMemory {
  126. public:
  127. /**
  128. * Constructs an empty State.
  129. * @stable ICU 4.8
  130. */
  131. State() { bytes=nullptr; }
  132. private:
  133. friend class BytesTrie;
  134. const uint8_t *bytes;
  135. const uint8_t *pos;
  136. int32_t remainingMatchLength;
  137. };
  138. /**
  139. * Saves the state of this trie.
  140. * @param state The State object to hold the trie's state.
  141. * @return *this
  142. * @see resetToState
  143. * @stable ICU 4.8
  144. */
  145. const BytesTrie &saveState(State &state) const {
  146. state.bytes=bytes_;
  147. state.pos=pos_;
  148. state.remainingMatchLength=remainingMatchLength_;
  149. return *this;
  150. }
  151. /**
  152. * Resets this trie to the saved state.
  153. * If the state object contains no state, or the state of a different trie,
  154. * then this trie remains unchanged.
  155. * @param state The State object which holds a saved trie state.
  156. * @return *this
  157. * @see saveState
  158. * @see reset
  159. * @stable ICU 4.8
  160. */
  161. BytesTrie &resetToState(const State &state) {
  162. if(bytes_==state.bytes && bytes_!=nullptr) {
  163. pos_=state.pos;
  164. remainingMatchLength_=state.remainingMatchLength;
  165. }
  166. return *this;
  167. }
  168. /**
  169. * Determines whether the byte sequence so far matches, whether it has a value,
  170. * and whether another input byte can continue a matching byte sequence.
  171. * @return The match/value Result.
  172. * @stable ICU 4.8
  173. */
  174. UStringTrieResult current() const;
  175. /**
  176. * Traverses the trie from the initial state for this input byte.
  177. * Equivalent to reset().next(inByte).
  178. * @param inByte Input byte value. Values -0x100..-1 are treated like 0..0xff.
  179. * Values below -0x100 and above 0xff will never match.
  180. * @return The match/value Result.
  181. * @stable ICU 4.8
  182. */
  183. inline UStringTrieResult first(int32_t inByte) {
  184. remainingMatchLength_=-1;
  185. if(inByte<0) {
  186. inByte+=0x100;
  187. }
  188. return nextImpl(bytes_, inByte);
  189. }
  190. /**
  191. * Traverses the trie from the current state for this input byte.
  192. * @param inByte Input byte value. Values -0x100..-1 are treated like 0..0xff.
  193. * Values below -0x100 and above 0xff will never match.
  194. * @return The match/value Result.
  195. * @stable ICU 4.8
  196. */
  197. UStringTrieResult next(int32_t inByte);
  198. /**
  199. * Traverses the trie from the current state for this byte sequence.
  200. * Equivalent to
  201. * \code
  202. * Result result=current();
  203. * for(each c in s)
  204. * if(!USTRINGTRIE_HAS_NEXT(result)) return USTRINGTRIE_NO_MATCH;
  205. * result=next(c);
  206. * return result;
  207. * \endcode
  208. * @param s A string or byte sequence. Can be nullptr if length is 0.
  209. * @param length The length of the byte sequence. Can be -1 if NUL-terminated.
  210. * @return The match/value Result.
  211. * @stable ICU 4.8
  212. */
  213. UStringTrieResult next(const char *s, int32_t length);
  214. /**
  215. * Returns a matching byte sequence'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.
  218. *
  219. * Do not call getValue() after USTRINGTRIE_NO_MATCH or USTRINGTRIE_NO_VALUE!
  220. * @return The value for the byte sequence so far.
  221. * @stable ICU 4.8
  222. */
  223. inline int32_t getValue() const {
  224. const uint8_t *pos=pos_;
  225. int32_t leadByte=*pos++;
  226. // U_ASSERT(leadByte>=kMinValueLead);
  227. return readValue(pos, leadByte>>1);
  228. }
  229. /**
  230. * Determines whether all byte sequences reachable from the current state
  231. * map to the same value.
  232. * @param uniqueValue Receives the unique value, if this function returns true.
  233. * (output-only)
  234. * @return true if all byte sequences reachable from the current state
  235. * map to the same value.
  236. * @stable ICU 4.8
  237. */
  238. inline UBool hasUniqueValue(int32_t &uniqueValue) const {
  239. const uint8_t *pos=pos_;
  240. // Skip the rest of a pending linear-match node.
  241. return pos!=nullptr && findUniqueValue(pos+remainingMatchLength_+1, false, uniqueValue);
  242. }
  243. /**
  244. * Finds each byte which continues the byte sequence from the current state.
  245. * That is, each byte b for which it would be next(b)!=USTRINGTRIE_NO_MATCH now.
  246. * @param out Each next byte is appended to this object.
  247. * (Only uses the out.Append(s, length) method.)
  248. * @return the number of bytes which continue the byte sequence from here
  249. * @stable ICU 4.8
  250. */
  251. int32_t getNextBytes(ByteSink &out) const;
  252. /**
  253. * Iterator for all of the (byte sequence, value) pairs in a BytesTrie.
  254. * @stable ICU 4.8
  255. */
  256. class U_COMMON_API Iterator : public UMemory {
  257. public:
  258. /**
  259. * Iterates from the root of a byte-serialized BytesTrie.
  260. * @param trieBytes The trie bytes.
  261. * @param maxStringLength If 0, the iterator returns full strings/byte sequences.
  262. * Otherwise, the iterator returns strings with this maximum length.
  263. * @param errorCode Standard ICU error code. Its input value must
  264. * pass the U_SUCCESS() test, or else the function returns
  265. * immediately. Check for U_FAILURE() on output or use with
  266. * function chaining. (See User Guide for details.)
  267. * @stable ICU 4.8
  268. */
  269. Iterator(const void *trieBytes, int32_t maxStringLength, UErrorCode &errorCode);
  270. /**
  271. * Iterates from the current state of the specified BytesTrie.
  272. * @param trie The trie whose state will be copied for iteration.
  273. * @param maxStringLength If 0, the iterator returns full strings/byte sequences.
  274. * Otherwise, the iterator returns strings with this maximum length.
  275. * @param errorCode Standard ICU error code. Its input value must
  276. * pass the U_SUCCESS() test, or else the function returns
  277. * immediately. Check for U_FAILURE() on output or use with
  278. * function chaining. (See User Guide for details.)
  279. * @stable ICU 4.8
  280. */
  281. Iterator(const BytesTrie &trie, int32_t maxStringLength, UErrorCode &errorCode);
  282. /**
  283. * Destructor.
  284. * @stable ICU 4.8
  285. */
  286. ~Iterator();
  287. /**
  288. * Resets this iterator to its initial state.
  289. * @return *this
  290. * @stable ICU 4.8
  291. */
  292. Iterator &reset();
  293. /**
  294. * @return true if there are more elements.
  295. * @stable ICU 4.8
  296. */
  297. UBool hasNext() const;
  298. /**
  299. * Finds the next (byte sequence, value) pair if there is one.
  300. *
  301. * If the byte sequence is truncated to the maximum length and does not
  302. * have a real value, then the value is set to -1.
  303. * In this case, this "not a real value" is indistinguishable from
  304. * a real value of -1.
  305. * @param errorCode Standard ICU error code. Its input value must
  306. * pass the U_SUCCESS() test, or else the function returns
  307. * immediately. Check for U_FAILURE() on output or use with
  308. * function chaining. (See User Guide for details.)
  309. * @return true if there is another element.
  310. * @stable ICU 4.8
  311. */
  312. UBool next(UErrorCode &errorCode);
  313. /**
  314. * @return The NUL-terminated byte sequence for the last successful next().
  315. * @stable ICU 4.8
  316. */
  317. StringPiece getString() const;
  318. /**
  319. * @return The value for the last successful next().
  320. * @stable ICU 4.8
  321. */
  322. int32_t getValue() const { return value_; }
  323. private:
  324. UBool truncateAndStop();
  325. const uint8_t *branchNext(const uint8_t *pos, int32_t length, UErrorCode &errorCode);
  326. const uint8_t *bytes_;
  327. const uint8_t *pos_;
  328. const uint8_t *initialPos_;
  329. int32_t remainingMatchLength_;
  330. int32_t initialRemainingMatchLength_;
  331. CharString *str_;
  332. int32_t maxLength_;
  333. int32_t value_;
  334. // The stack stores pairs of integers for backtracking to another
  335. // outbound edge of a branch node.
  336. // The first integer is an offset from bytes_.
  337. // The second integer has the str_->length() from before the node in bits 15..0,
  338. // and the remaining branch length in bits 24..16. (Bits 31..25 are unused.)
  339. // (We could store the remaining branch length minus 1 in bits 23..16 and not use bits 31..24,
  340. // but the code looks more confusing that way.)
  341. UVector32 *stack_;
  342. };
  343. private:
  344. friend class BytesTrieBuilder;
  345. friend class ::BytesTrieTest;
  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) = delete;
  358. inline void stop() {
  359. pos_=nullptr;
  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. nullptr 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__