Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/native/common/unicode/bytestrie.h
38827 views
/*1*******************************************************************************2* Copyright (C) 2010-2012, International Business Machines3* Corporation and others. All Rights Reserved.4*******************************************************************************5* file name: bytestrie.h6* encoding: US-ASCII7* tab size: 8 (not used)8* indentation:49*10* created on: 2010sep2511* created by: Markus W. Scherer12*/1314#ifndef __BYTESTRIE_H__15#define __BYTESTRIE_H__1617/**18* \file19* \brief C++ API: Trie for mapping byte sequences to integer values.20*/2122#include "unicode/utypes.h"23#include "unicode/stringpiece.h"24#include "unicode/uobject.h"25#include "unicode/ustringtrie.h"2627U_NAMESPACE_BEGIN2829class ByteSink;30class BytesTrieBuilder;31class CharString;32class UVector32;3334/**35* Light-weight, non-const reader class for a BytesTrie.36* Traverses a byte-serialized data structure with minimal state,37* for mapping byte sequences to non-negative integer values.38*39* This class owns the serialized trie data only if it was constructed by40* the builder's build() method.41* The public constructor and the copy constructor only alias the data (only copy the pointer).42* There is no assignment operator.43*44* This class is not intended for public subclassing.45* @stable ICU 4.846*/47class U_COMMON_API BytesTrie : public UMemory {48public:49/**50* Constructs a BytesTrie reader instance.51*52* The trieBytes must contain a copy of a byte sequence from the BytesTrieBuilder,53* starting with the first byte of that sequence.54* The BytesTrie object will not read more bytes than55* the BytesTrieBuilder generated in the corresponding build() call.56*57* The array is not copied/cloned and must not be modified while58* the BytesTrie object is in use.59*60* @param trieBytes The byte array that contains the serialized trie.61* @stable ICU 4.862*/63BytesTrie(const void *trieBytes)64: ownedArray_(NULL), bytes_(static_cast<const uint8_t *>(trieBytes)),65pos_(bytes_), remainingMatchLength_(-1) {}6667/**68* Destructor.69* @stable ICU 4.870*/71~BytesTrie();7273/**74* Copy constructor, copies the other trie reader object and its state,75* but not the byte array which will be shared. (Shallow copy.)76* @param other Another BytesTrie object.77* @stable ICU 4.878*/79BytesTrie(const BytesTrie &other)80: ownedArray_(NULL), bytes_(other.bytes_),81pos_(other.pos_), remainingMatchLength_(other.remainingMatchLength_) {}8283/**84* Resets this trie to its initial state.85* @return *this86* @stable ICU 4.887*/88BytesTrie &reset() {89pos_=bytes_;90remainingMatchLength_=-1;91return *this;92}9394/**95* BytesTrie state object, for saving a trie's current state96* and resetting the trie back to this state later.97* @stable ICU 4.898*/99class State : public UMemory {100public:101/**102* Constructs an empty State.103* @stable ICU 4.8104*/105State() { bytes=NULL; }106private:107friend class BytesTrie;108109const uint8_t *bytes;110const uint8_t *pos;111int32_t remainingMatchLength;112};113114/**115* Saves the state of this trie.116* @param state The State object to hold the trie's state.117* @return *this118* @see resetToState119* @stable ICU 4.8120*/121const BytesTrie &saveState(State &state) const {122state.bytes=bytes_;123state.pos=pos_;124state.remainingMatchLength=remainingMatchLength_;125return *this;126}127128/**129* Resets this trie to the saved state.130* If the state object contains no state, or the state of a different trie,131* then this trie remains unchanged.132* @param state The State object which holds a saved trie state.133* @return *this134* @see saveState135* @see reset136* @stable ICU 4.8137*/138BytesTrie &resetToState(const State &state) {139if(bytes_==state.bytes && bytes_!=NULL) {140pos_=state.pos;141remainingMatchLength_=state.remainingMatchLength;142}143return *this;144}145146/**147* Determines whether the byte sequence so far matches, whether it has a value,148* and whether another input byte can continue a matching byte sequence.149* @return The match/value Result.150* @stable ICU 4.8151*/152UStringTrieResult current() const;153154/**155* Traverses the trie from the initial state for this input byte.156* Equivalent to reset().next(inByte).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.8161*/162inline UStringTrieResult first(int32_t inByte) {163remainingMatchLength_=-1;164if(inByte<0) {165inByte+=0x100;166}167return nextImpl(bytes_, inByte);168}169170/**171* Traverses the trie from the current state for this input byte.172* @param inByte Input byte value. Values -0x100..-1 are treated like 0..0xff.173* Values below -0x100 and above 0xff will never match.174* @return The match/value Result.175* @stable ICU 4.8176*/177UStringTrieResult next(int32_t inByte);178179/**180* Traverses the trie from the current state for this byte sequence.181* Equivalent to182* \code183* Result result=current();184* for(each c in s)185* if(!USTRINGTRIE_HAS_NEXT(result)) return USTRINGTRIE_NO_MATCH;186* result=next(c);187* return result;188* \endcode189* @param s A string or byte sequence. Can be NULL if length is 0.190* @param length The length of the byte sequence. Can be -1 if NUL-terminated.191* @return The match/value Result.192* @stable ICU 4.8193*/194UStringTrieResult next(const char *s, int32_t length);195196/**197* Returns a matching byte sequence's value if called immediately after198* current()/first()/next() returned USTRINGTRIE_INTERMEDIATE_VALUE or USTRINGTRIE_FINAL_VALUE.199* getValue() can be called multiple times.200*201* Do not call getValue() after USTRINGTRIE_NO_MATCH or USTRINGTRIE_NO_VALUE!202* @return The value for the byte sequence so far.203* @stable ICU 4.8204*/205inline int32_t getValue() const {206const uint8_t *pos=pos_;207int32_t leadByte=*pos++;208// U_ASSERT(leadByte>=kMinValueLead);209return readValue(pos, leadByte>>1);210}211212/**213* Determines whether all byte sequences reachable from the current state214* map to the same value.215* @param uniqueValue Receives the unique value, if this function returns TRUE.216* (output-only)217* @return TRUE if all byte sequences reachable from the current state218* map to the same value.219* @stable ICU 4.8220*/221inline UBool hasUniqueValue(int32_t &uniqueValue) const {222const uint8_t *pos=pos_;223// Skip the rest of a pending linear-match node.224return pos!=NULL && findUniqueValue(pos+remainingMatchLength_+1, FALSE, uniqueValue);225}226227/**228* Finds each byte which continues the byte sequence from the current state.229* That is, each byte b for which it would be next(b)!=USTRINGTRIE_NO_MATCH now.230* @param out Each next byte is appended to this object.231* (Only uses the out.Append(s, length) method.)232* @return the number of bytes which continue the byte sequence from here233* @stable ICU 4.8234*/235int32_t getNextBytes(ByteSink &out) const;236237/**238* Iterator for all of the (byte sequence, value) pairs in a BytesTrie.239* @stable ICU 4.8240*/241class U_COMMON_API Iterator : public UMemory {242public:243/**244* Iterates from the root of a byte-serialized BytesTrie.245* @param trieBytes The trie bytes.246* @param maxStringLength If 0, the iterator returns full strings/byte sequences.247* Otherwise, the iterator returns strings with this maximum length.248* @param errorCode Standard ICU error code. Its input value must249* pass the U_SUCCESS() test, or else the function returns250* immediately. Check for U_FAILURE() on output or use with251* function chaining. (See User Guide for details.)252* @stable ICU 4.8253*/254Iterator(const void *trieBytes, int32_t maxStringLength, UErrorCode &errorCode);255256/**257* Iterates from the current state of the specified BytesTrie.258* @param trie The trie whose state will be copied for iteration.259* @param maxStringLength If 0, the iterator returns full strings/byte sequences.260* Otherwise, the iterator returns strings with this maximum length.261* @param errorCode Standard ICU error code. Its input value must262* pass the U_SUCCESS() test, or else the function returns263* immediately. Check for U_FAILURE() on output or use with264* function chaining. (See User Guide for details.)265* @stable ICU 4.8266*/267Iterator(const BytesTrie &trie, int32_t maxStringLength, UErrorCode &errorCode);268269/**270* Destructor.271* @stable ICU 4.8272*/273~Iterator();274275/**276* Resets this iterator to its initial state.277* @return *this278* @stable ICU 4.8279*/280Iterator &reset();281282/**283* @return TRUE if there are more elements.284* @stable ICU 4.8285*/286UBool hasNext() const;287288/**289* Finds the next (byte sequence, value) pair if there is one.290*291* If the byte sequence is truncated to the maximum length and does not292* have a real value, then the value is set to -1.293* In this case, this "not a real value" is indistinguishable from294* a real value of -1.295* @param errorCode Standard ICU error code. Its input value must296* pass the U_SUCCESS() test, or else the function returns297* immediately. Check for U_FAILURE() on output or use with298* function chaining. (See User Guide for details.)299* @return TRUE if there is another element.300* @stable ICU 4.8301*/302UBool next(UErrorCode &errorCode);303304/**305* @return The NUL-terminated byte sequence for the last successful next().306* @stable ICU 4.8307*/308const StringPiece &getString() const { return sp_; }309/**310* @return The value for the last successful next().311* @stable ICU 4.8312*/313int32_t getValue() const { return value_; }314315private:316UBool truncateAndStop();317318const uint8_t *branchNext(const uint8_t *pos, int32_t length, UErrorCode &errorCode);319320const uint8_t *bytes_;321const uint8_t *pos_;322const uint8_t *initialPos_;323int32_t remainingMatchLength_;324int32_t initialRemainingMatchLength_;325326CharString *str_;327StringPiece sp_;328int32_t maxLength_;329int32_t value_;330331// The stack stores pairs of integers for backtracking to another332// outbound edge of a branch node.333// The first integer is an offset from bytes_.334// The second integer has the str_->length() from before the node in bits 15..0,335// and the remaining branch length in bits 24..16. (Bits 31..25 are unused.)336// (We could store the remaining branch length minus 1 in bits 23..16 and not use bits 31..24,337// but the code looks more confusing that way.)338UVector32 *stack_;339};340341private:342friend class BytesTrieBuilder;343344/**345* Constructs a BytesTrie reader instance.346* Unlike the public constructor which just aliases an array,347* this constructor adopts the builder's array.348* This constructor is only called by the builder.349*/350BytesTrie(void *adoptBytes, const void *trieBytes)351: ownedArray_(static_cast<uint8_t *>(adoptBytes)),352bytes_(static_cast<const uint8_t *>(trieBytes)),353pos_(bytes_), remainingMatchLength_(-1) {}354355// No assignment operator.356BytesTrie &operator=(const BytesTrie &other);357358inline void stop() {359pos_=NULL;360}361362// Reads a compact 32-bit integer.363// pos is already after the leadByte, and the lead byte is already shifted right by 1.364static int32_t readValue(const uint8_t *pos, int32_t leadByte);365static inline const uint8_t *skipValue(const uint8_t *pos, int32_t leadByte) {366// U_ASSERT(leadByte>=kMinValueLead);367if(leadByte>=(kMinTwoByteValueLead<<1)) {368if(leadByte<(kMinThreeByteValueLead<<1)) {369++pos;370} else if(leadByte<(kFourByteValueLead<<1)) {371pos+=2;372} else {373pos+=3+((leadByte>>1)&1);374}375}376return pos;377}378static inline const uint8_t *skipValue(const uint8_t *pos) {379int32_t leadByte=*pos++;380return skipValue(pos, leadByte);381}382383// Reads a jump delta and jumps.384static const uint8_t *jumpByDelta(const uint8_t *pos);385386static inline const uint8_t *skipDelta(const uint8_t *pos) {387int32_t delta=*pos++;388if(delta>=kMinTwoByteDeltaLead) {389if(delta<kMinThreeByteDeltaLead) {390++pos;391} else if(delta<kFourByteDeltaLead) {392pos+=2;393} else {394pos+=3+(delta&1);395}396}397return pos;398}399400static inline UStringTrieResult valueResult(int32_t node) {401return (UStringTrieResult)(USTRINGTRIE_INTERMEDIATE_VALUE-(node&kValueIsFinal));402}403404// Handles a branch node for both next(byte) and next(string).405UStringTrieResult branchNext(const uint8_t *pos, int32_t length, int32_t inByte);406407// Requires remainingLength_<0.408UStringTrieResult nextImpl(const uint8_t *pos, int32_t inByte);409410// Helper functions for hasUniqueValue().411// Recursively finds a unique value (or whether there is not a unique one)412// from a branch.413static const uint8_t *findUniqueValueFromBranch(const uint8_t *pos, int32_t length,414UBool haveUniqueValue, int32_t &uniqueValue);415// Recursively finds a unique value (or whether there is not a unique one)416// starting from a position on a node lead byte.417static UBool findUniqueValue(const uint8_t *pos, UBool haveUniqueValue, int32_t &uniqueValue);418419// Helper functions for getNextBytes().420// getNextBytes() when pos is on a branch node.421static void getNextBranchBytes(const uint8_t *pos, int32_t length, ByteSink &out);422static void append(ByteSink &out, int c);423424// BytesTrie data structure425//426// The trie consists of a series of byte-serialized nodes for incremental427// string/byte sequence matching. The root node is at the beginning of the trie data.428//429// Types of nodes are distinguished by their node lead byte ranges.430// After each node, except a final-value node, another node follows to431// encode match values or continue matching further bytes.432//433// Node types:434// - Value node: Stores a 32-bit integer in a compact, variable-length format.435// The value is for the string/byte sequence so far.436// One node bit indicates whether the value is final or whether437// matching continues with the next node.438// - Linear-match node: Matches a number of bytes.439// - Branch node: Branches to other nodes according to the current input byte.440// The node byte is the length of the branch (number of bytes to select from)441// minus 1. It is followed by a sub-node:442// - If the length is at most kMaxBranchLinearSubNodeLength, then443// there are length-1 (key, value) pairs and then one more comparison byte.444// If one of the key bytes matches, then the value is either a final value for445// the string/byte sequence so far, or a "jump" delta to the next node.446// If the last byte matches, then matching continues with the next node.447// (Values have the same encoding as value nodes.)448// - If the length is greater than kMaxBranchLinearSubNodeLength, then449// there is one byte and one "jump" delta.450// If the input byte is less than the sub-node byte, then "jump" by delta to451// the next sub-node which will have a length of length/2.452// (The delta has its own compact encoding.)453// Otherwise, skip the "jump" delta to the next sub-node454// which will have a length of length-length/2.455456// Node lead byte values.457458// 00..0f: Branch node. If node!=0 then the length is node+1, otherwise459// the length is one more than the next byte.460461// For a branch sub-node with at most this many entries, we drop down462// to a linear search.463static const int32_t kMaxBranchLinearSubNodeLength=5;464465// 10..1f: Linear-match node, match 1..16 bytes and continue reading the next node.466static const int32_t kMinLinearMatch=0x10;467static const int32_t kMaxLinearMatchLength=0x10;468469// 20..ff: Variable-length value node.470// If odd, the value is final. (Otherwise, intermediate value or jump delta.)471// Then shift-right by 1 bit.472// The remaining lead byte value indicates the number of following bytes (0..4)473// and contains the value's top bits.474static const int32_t kMinValueLead=kMinLinearMatch+kMaxLinearMatchLength; // 0x20475// It is a final value if bit 0 is set.476static const int32_t kValueIsFinal=1;477478// Compact value: After testing bit 0, shift right by 1 and then use the following thresholds.479static const int32_t kMinOneByteValueLead=kMinValueLead/2; // 0x10480static const int32_t kMaxOneByteValue=0x40; // At least 6 bits in the first byte.481482static const int32_t kMinTwoByteValueLead=kMinOneByteValueLead+kMaxOneByteValue+1; // 0x51483static const int32_t kMaxTwoByteValue=0x1aff;484485static const int32_t kMinThreeByteValueLead=kMinTwoByteValueLead+(kMaxTwoByteValue>>8)+1; // 0x6c486static const int32_t kFourByteValueLead=0x7e;487488// A little more than Unicode code points. (0x11ffff)489static const int32_t kMaxThreeByteValue=((kFourByteValueLead-kMinThreeByteValueLead)<<16)-1;490491static const int32_t kFiveByteValueLead=0x7f;492493// Compact delta integers.494static const int32_t kMaxOneByteDelta=0xbf;495static const int32_t kMinTwoByteDeltaLead=kMaxOneByteDelta+1; // 0xc0496static const int32_t kMinThreeByteDeltaLead=0xf0;497static const int32_t kFourByteDeltaLead=0xfe;498static const int32_t kFiveByteDeltaLead=0xff;499500static const int32_t kMaxTwoByteDelta=((kMinThreeByteDeltaLead-kMinTwoByteDeltaLead)<<8)-1; // 0x2fff501static const int32_t kMaxThreeByteDelta=((kFourByteDeltaLead-kMinThreeByteDeltaLead)<<16)-1; // 0xdffff502503uint8_t *ownedArray_;504505// Fixed value referencing the BytesTrie bytes.506const uint8_t *bytes_;507508// Iterator variables.509510// Pointer to next trie byte to read. NULL if no more matches.511const uint8_t *pos_;512// Remaining length of a linear-match node, minus 1. Negative if not in such a node.513int32_t remainingMatchLength_;514};515516U_NAMESPACE_END517518#endif // __BYTESTRIE_H__519520521