ICU 68.2  68.2
bytestrie.h
Go to the documentation of this file.
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 
17 #ifndef __BYTESTRIE_H__
18 #define __BYTESTRIE_H__
19 
25 #include "unicode/utypes.h"
26 
27 #if U_SHOW_CPLUSPLUS_API
28 
29 #include "unicode/stringpiece.h"
30 #include "unicode/uobject.h"
31 #include "unicode/ustringtrie.h"
32 
33 U_NAMESPACE_BEGIN
34 
35 class ByteSink;
36 class BytesTrieBuilder;
37 class CharString;
38 class UVector32;
39 
53 class U_COMMON_API BytesTrie : public UMemory {
54 public:
69  BytesTrie(const void *trieBytes)
70  : ownedArray_(NULL), bytes_(static_cast<const uint8_t *>(trieBytes)),
71  pos_(bytes_), remainingMatchLength_(-1) {}
72 
78 
85  BytesTrie(const BytesTrie &other)
86  : ownedArray_(NULL), bytes_(other.bytes_),
87  pos_(other.pos_), remainingMatchLength_(other.remainingMatchLength_) {}
88 
95  pos_=bytes_;
96  remainingMatchLength_=-1;
97  return *this;
98  }
99 
108  uint64_t getState64() const {
109  return (static_cast<uint64_t>(remainingMatchLength_ + 2) << kState64RemainingShift) |
110  (uint64_t)(pos_ - bytes_);
111  }
112 
127  BytesTrie &resetToState64(uint64_t state) {
128  remainingMatchLength_ = static_cast<int32_t>(state >> kState64RemainingShift) - 2;
129  pos_ = bytes_ + (state & kState64PosMask);
130  return *this;
131  }
132 
138  class State : public UMemory {
139  public:
144  State() { bytes=NULL; }
145  private:
146  friend class BytesTrie;
147 
148  const uint8_t *bytes;
149  const uint8_t *pos;
150  int32_t remainingMatchLength;
151  };
152 
160  const BytesTrie &saveState(State &state) const {
161  state.bytes=bytes_;
162  state.pos=pos_;
163  state.remainingMatchLength=remainingMatchLength_;
164  return *this;
165  }
166 
177  BytesTrie &resetToState(const State &state) {
178  if(bytes_==state.bytes && bytes_!=NULL) {
179  pos_=state.pos;
180  remainingMatchLength_=state.remainingMatchLength;
181  }
182  return *this;
183  }
184 
192 
201  inline UStringTrieResult first(int32_t inByte) {
202  remainingMatchLength_=-1;
203  if(inByte<0) {
204  inByte+=0x100;
205  }
206  return nextImpl(bytes_, inByte);
207  }
208 
216  UStringTrieResult next(int32_t inByte);
217 
233  UStringTrieResult next(const char *s, int32_t length);
234 
244  inline int32_t getValue() const {
245  const uint8_t *pos=pos_;
246  int32_t leadByte=*pos++;
247  // U_ASSERT(leadByte>=kMinValueLead);
248  return readValue(pos, leadByte>>1);
249  }
250 
260  inline UBool hasUniqueValue(int32_t &uniqueValue) const {
261  const uint8_t *pos=pos_;
262  // Skip the rest of a pending linear-match node.
263  return pos!=NULL && findUniqueValue(pos+remainingMatchLength_+1, false, uniqueValue);
264  }
265 
274  int32_t getNextBytes(ByteSink &out) const;
275 
280  class U_COMMON_API Iterator : public UMemory {
281  public:
293  Iterator(const void *trieBytes, int32_t maxStringLength, UErrorCode &errorCode);
294 
306  Iterator(const BytesTrie &trie, int32_t maxStringLength, UErrorCode &errorCode);
307 
313 
320 
325  UBool hasNext() const;
326 
341  UBool next(UErrorCode &errorCode);
342 
352  int32_t getValue() const { return value_; }
353 
354  private:
355  UBool truncateAndStop();
356 
357  const uint8_t *branchNext(const uint8_t *pos, int32_t length, UErrorCode &errorCode);
358 
359  const uint8_t *bytes_;
360  const uint8_t *pos_;
361  const uint8_t *initialPos_;
362  int32_t remainingMatchLength_;
363  int32_t initialRemainingMatchLength_;
364 
365  CharString *str_;
366  int32_t maxLength_;
367  int32_t value_;
368 
369  // The stack stores pairs of integers for backtracking to another
370  // outbound edge of a branch node.
371  // The first integer is an offset from bytes_.
372  // The second integer has the str_->length() from before the node in bits 15..0,
373  // and the remaining branch length in bits 24..16. (Bits 31..25 are unused.)
374  // (We could store the remaining branch length minus 1 in bits 23..16 and not use bits 31..24,
375  // but the code looks more confusing that way.)
376  UVector32 *stack_;
377  };
378 
379 private:
380  friend class BytesTrieBuilder;
381 
388  BytesTrie(void *adoptBytes, const void *trieBytes)
389  : ownedArray_(static_cast<uint8_t *>(adoptBytes)),
390  bytes_(static_cast<const uint8_t *>(trieBytes)),
391  pos_(bytes_), remainingMatchLength_(-1) {}
392 
393  // No assignment operator.
394  BytesTrie &operator=(const BytesTrie &other);
395 
396  inline void stop() {
397  pos_=NULL;
398  }
399 
400  // Reads a compact 32-bit integer.
401  // pos is already after the leadByte, and the lead byte is already shifted right by 1.
402  static int32_t readValue(const uint8_t *pos, int32_t leadByte);
403  static inline const uint8_t *skipValue(const uint8_t *pos, int32_t leadByte) {
404  // U_ASSERT(leadByte>=kMinValueLead);
405  if(leadByte>=(kMinTwoByteValueLead<<1)) {
406  if(leadByte<(kMinThreeByteValueLead<<1)) {
407  ++pos;
408  } else if(leadByte<(kFourByteValueLead<<1)) {
409  pos+=2;
410  } else {
411  pos+=3+((leadByte>>1)&1);
412  }
413  }
414  return pos;
415  }
416  static inline const uint8_t *skipValue(const uint8_t *pos) {
417  int32_t leadByte=*pos++;
418  return skipValue(pos, leadByte);
419  }
420 
421  // Reads a jump delta and jumps.
422  static const uint8_t *jumpByDelta(const uint8_t *pos);
423 
424  static inline const uint8_t *skipDelta(const uint8_t *pos) {
425  int32_t delta=*pos++;
426  if(delta>=kMinTwoByteDeltaLead) {
427  if(delta<kMinThreeByteDeltaLead) {
428  ++pos;
429  } else if(delta<kFourByteDeltaLead) {
430  pos+=2;
431  } else {
432  pos+=3+(delta&1);
433  }
434  }
435  return pos;
436  }
437 
438  static inline UStringTrieResult valueResult(int32_t node) {
439  return (UStringTrieResult)(USTRINGTRIE_INTERMEDIATE_VALUE-(node&kValueIsFinal));
440  }
441 
442  // Handles a branch node for both next(byte) and next(string).
443  UStringTrieResult branchNext(const uint8_t *pos, int32_t length, int32_t inByte);
444 
445  // Requires remainingLength_<0.
446  UStringTrieResult nextImpl(const uint8_t *pos, int32_t inByte);
447 
448  // Helper functions for hasUniqueValue().
449  // Recursively finds a unique value (or whether there is not a unique one)
450  // from a branch.
451  static const uint8_t *findUniqueValueFromBranch(const uint8_t *pos, int32_t length,
452  UBool haveUniqueValue, int32_t &uniqueValue);
453  // Recursively finds a unique value (or whether there is not a unique one)
454  // starting from a position on a node lead byte.
455  static UBool findUniqueValue(const uint8_t *pos, UBool haveUniqueValue, int32_t &uniqueValue);
456 
457  // Helper functions for getNextBytes().
458  // getNextBytes() when pos is on a branch node.
459  static void getNextBranchBytes(const uint8_t *pos, int32_t length, ByteSink &out);
460  static void append(ByteSink &out, int c);
461 
462  // BytesTrie data structure
463  //
464  // The trie consists of a series of byte-serialized nodes for incremental
465  // string/byte sequence matching. The root node is at the beginning of the trie data.
466  //
467  // Types of nodes are distinguished by their node lead byte ranges.
468  // After each node, except a final-value node, another node follows to
469  // encode match values or continue matching further bytes.
470  //
471  // Node types:
472  // - Value node: Stores a 32-bit integer in a compact, variable-length format.
473  // The value is for the string/byte sequence so far.
474  // One node bit indicates whether the value is final or whether
475  // matching continues with the next node.
476  // - Linear-match node: Matches a number of bytes.
477  // - Branch node: Branches to other nodes according to the current input byte.
478  // The node byte is the length of the branch (number of bytes to select from)
479  // minus 1. It is followed by a sub-node:
480  // - If the length is at most kMaxBranchLinearSubNodeLength, then
481  // there are length-1 (key, value) pairs and then one more comparison byte.
482  // If one of the key bytes matches, then the value is either a final value for
483  // the string/byte sequence so far, or a "jump" delta to the next node.
484  // If the last byte matches, then matching continues with the next node.
485  // (Values have the same encoding as value nodes.)
486  // - If the length is greater than kMaxBranchLinearSubNodeLength, then
487  // there is one byte and one "jump" delta.
488  // If the input byte is less than the sub-node byte, then "jump" by delta to
489  // the next sub-node which will have a length of length/2.
490  // (The delta has its own compact encoding.)
491  // Otherwise, skip the "jump" delta to the next sub-node
492  // which will have a length of length-length/2.
493 
494  // Node lead byte values.
495 
496  // 00..0f: Branch node. If node!=0 then the length is node+1, otherwise
497  // the length is one more than the next byte.
498 
499  // For a branch sub-node with at most this many entries, we drop down
500  // to a linear search.
501  static const int32_t kMaxBranchLinearSubNodeLength=5;
502 
503  // 10..1f: Linear-match node, match 1..16 bytes and continue reading the next node.
504  static const int32_t kMinLinearMatch=0x10;
505  static const int32_t kMaxLinearMatchLength=0x10;
506 
507  // 20..ff: Variable-length value node.
508  // If odd, the value is final. (Otherwise, intermediate value or jump delta.)
509  // Then shift-right by 1 bit.
510  // The remaining lead byte value indicates the number of following bytes (0..4)
511  // and contains the value's top bits.
512  static const int32_t kMinValueLead=kMinLinearMatch+kMaxLinearMatchLength; // 0x20
513  // It is a final value if bit 0 is set.
514  static const int32_t kValueIsFinal=1;
515 
516  // Compact value: After testing bit 0, shift right by 1 and then use the following thresholds.
517  static const int32_t kMinOneByteValueLead=kMinValueLead/2; // 0x10
518  static const int32_t kMaxOneByteValue=0x40; // At least 6 bits in the first byte.
519 
520  static const int32_t kMinTwoByteValueLead=kMinOneByteValueLead+kMaxOneByteValue+1; // 0x51
521  static const int32_t kMaxTwoByteValue=0x1aff;
522 
523  static const int32_t kMinThreeByteValueLead=kMinTwoByteValueLead+(kMaxTwoByteValue>>8)+1; // 0x6c
524  static const int32_t kFourByteValueLead=0x7e;
525 
526  // A little more than Unicode code points. (0x11ffff)
527  static const int32_t kMaxThreeByteValue=((kFourByteValueLead-kMinThreeByteValueLead)<<16)-1;
528 
529  static const int32_t kFiveByteValueLead=0x7f;
530 
531  // Compact delta integers.
532  static const int32_t kMaxOneByteDelta=0xbf;
533  static const int32_t kMinTwoByteDeltaLead=kMaxOneByteDelta+1; // 0xc0
534  static const int32_t kMinThreeByteDeltaLead=0xf0;
535  static const int32_t kFourByteDeltaLead=0xfe;
536  static const int32_t kFiveByteDeltaLead=0xff;
537 
538  static const int32_t kMaxTwoByteDelta=((kMinThreeByteDeltaLead-kMinTwoByteDeltaLead)<<8)-1; // 0x2fff
539  static const int32_t kMaxThreeByteDelta=((kFourByteDeltaLead-kMinThreeByteDeltaLead)<<16)-1; // 0xdffff
540 
541  // For getState64():
542  // The remainingMatchLength_ is -1..14=(kMaxLinearMatchLength=0x10)-2
543  // so we need at least 5 bits for that.
544  // We add 2 to store it as a positive value 1..16=kMaxLinearMatchLength.
545  static constexpr int32_t kState64RemainingShift = 59;
546  static constexpr uint64_t kState64PosMask = (UINT64_C(1) << kState64RemainingShift) - 1;
547 
548  uint8_t *ownedArray_;
549 
550  // Fixed value referencing the BytesTrie bytes.
551  const uint8_t *bytes_;
552 
553  // Iterator variables.
554 
555  // Pointer to next trie byte to read. NULL if no more matches.
556  const uint8_t *pos_;
557  // Remaining length of a linear-match node, minus 1. Negative if not in such a node.
558  int32_t remainingMatchLength_;
559 };
560 
561 U_NAMESPACE_END
562 
563 #endif /* U_SHOW_CPLUSPLUS_API */
564 
565 #endif // __BYTESTRIE_H__
icu::BytesTrie::next
UStringTrieResult next(int32_t inByte)
Traverses the trie from the current state for this input byte.
icu::BytesTrie::getState64
uint64_t getState64() const
Returns the state of this trie as a 64-bit integer.
Definition: bytestrie.h:108
icu::BytesTrie::Iterator::Iterator
Iterator(const void *trieBytes, int32_t maxStringLength, UErrorCode &errorCode)
Iterates from the root of a byte-serialized BytesTrie.
USTRINGTRIE_INTERMEDIATE_VALUE
@ USTRINGTRIE_INTERMEDIATE_VALUE
The input unit(s) continued a matching string and there is a value for the string so far.
Definition: ustringtrie.h:66
icu::BytesTrie::BytesTrie
BytesTrie(const BytesTrie &other)
Copy constructor, copies the other trie reader object and its state, but not the byte array which wil...
Definition: bytestrie.h:85
icu::BytesTrie::current
UStringTrieResult current() const
Determines whether the byte sequence so far matches, whether it has a value, and whether another inpu...
utypes.h
Basic definitions for ICU, for both C and C++ APIs.
UINT64_C
#define UINT64_C(c)
Provides a platform independent way to specify an unsigned 64-bit integer constant.
Definition: umachine.h:241
icu::BytesTrie::Iterator::next
UBool next(UErrorCode &errorCode)
Finds the next (byte sequence, value) pair if there is one.
UBool
int8_t UBool
The ICU boolean type, a signed-byte integer.
Definition: umachine.h:269
icu::BytesTrie::getNextBytes
int32_t getNextBytes(ByteSink &out) const
Finds each byte which continues the byte sequence from the current state.
icu::BytesTrie::Iterator::getValue
int32_t getValue() const
Definition: bytestrie.h:352
U_COMMON_API
#define U_COMMON_API
Set to export library symbols from inside the common library, and to import them from outside.
Definition: utypes.h:300
icu::BytesTrie::~BytesTrie
~BytesTrie()
Destructor.
NULL
#define NULL
Define NULL if necessary, to nullptr for C++ and to ((void *)0) for C.
Definition: utypes.h:188
icu::BytesTrie::Iterator::getString
StringPiece getString() const
stringpiece.h
C++ API: StringPiece: Read-only byte string wrapper class.
icu::BytesTrie::Iterator::Iterator
Iterator(const BytesTrie &trie, int32_t maxStringLength, UErrorCode &errorCode)
Iterates from the current state of the specified BytesTrie.
icu::BytesTrie::Iterator
Iterator for all of the (byte sequence, value) pairs in a BytesTrie.
Definition: bytestrie.h:280
UErrorCode
UErrorCode
Standard ICU4C error code type, a substitute for exceptions.
Definition: utypes.h:415
icu::BytesTrie::saveState
const BytesTrie & saveState(State &state) const
Saves the state of this trie.
Definition: bytestrie.h:160
icu::ByteSink
A ByteSink can be filled with bytes.
Definition: bytestream.h:53
icu::UMemory
UMemory is the common ICU base class.
Definition: uobject.h:115
icu::BytesTrie::resetToState
BytesTrie & resetToState(const State &state)
Resets this trie to the saved state.
Definition: bytestrie.h:177
icu::BytesTrie::State
BytesTrie state object, for saving a trie's current state and resetting the trie back to this state l...
Definition: bytestrie.h:138
icu::BytesTrie
Light-weight, non-const reader class for a BytesTrie.
Definition: bytestrie.h:53
icu::BytesTrie::resetToState64
BytesTrie & resetToState64(uint64_t state)
Resets this trie to the saved state.
Definition: bytestrie.h:127
ustringtrie.h
C API: Helper definitions for dictionary trie APIs.
icu::BytesTrieBuilder
Builder class for BytesTrie.
Definition: bytestriebuilder.h:43
icu::BytesTrie::Iterator::reset
Iterator & reset()
Resets this iterator to its initial state.
icu::BytesTrie::reset
BytesTrie & reset()
Resets this trie to its initial state.
Definition: bytestrie.h:94
icu::BytesTrie::State::State
State()
Constructs an empty State.
Definition: bytestrie.h:144
icu::BytesTrie::hasUniqueValue
UBool hasUniqueValue(int32_t &uniqueValue) const
Determines whether all byte sequences reachable from the current state map to the same value.
Definition: bytestrie.h:260
icu::BytesTrie::next
UStringTrieResult next(const char *s, int32_t length)
Traverses the trie from the current state for this byte sequence.
UStringTrieResult
UStringTrieResult
Return values for BytesTrie::next(), UCharsTrie::next() and similar methods.
Definition: ustringtrie.h:35
uobject.h
C++ API: Common ICU base class UObject.
icu::BytesTrie::getValue
int32_t getValue() const
Returns a matching byte sequence's value if called immediately after current()/first()/next() returne...
Definition: bytestrie.h:244
icu::StringPiece
A string-like object that points to a sized piece of memory.
Definition: stringpiece.h:60
icu::BytesTrie::first
UStringTrieResult first(int32_t inByte)
Traverses the trie from the initial state for this input byte.
Definition: bytestrie.h:201
icu::BytesTrie::BytesTrie
BytesTrie(const void *trieBytes)
Constructs a BytesTrie reader instance.
Definition: bytestrie.h:69
icu::BytesTrie::Iterator::~Iterator
~Iterator()
Destructor.
icu::BytesTrie::Iterator::hasNext
UBool hasNext() const