bytestrie.h 19 KB

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