bytestrie.h 19 KB

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