1/*
2*******************************************************************************
3*   Copyright (C) 2010-2011, International Business Machines
4*   Corporation and others.  All Rights Reserved.
5*******************************************************************************
6*   file name:  ucharstrie.h
7*   encoding:   US-ASCII
8*   tab size:   8 (not used)
9*   indentation:4
10*
11*   created on: 2010nov14
12*   created by: Markus W. Scherer
13*/
14
15#ifndef __UCHARSTRIE_H__
16#define __UCHARSTRIE_H__
17
18/**
19 * \file
20 * \brief C++ API: Trie for mapping Unicode strings (or 16-bit-unit sequences)
21 *                 to integer values.
22 */
23
24#include "unicode/utypes.h"
25#include "unicode/unistr.h"
26#include "unicode/uobject.h"
27#include "unicode/ustringtrie.h"
28
29U_NAMESPACE_BEGIN
30
31class Appendable;
32class UCharsTrieBuilder;
33class UVector32;
34
35/**
36 * Light-weight, non-const reader class for a UCharsTrie.
37 * Traverses a UChar-serialized data structure with minimal state,
38 * for mapping strings (16-bit-unit sequences) to non-negative integer values.
39 *
40 * This class owns the serialized trie data only if it was constructed by
41 * the builder's build() method.
42 * The public constructor and the copy constructor only alias the data (only copy the pointer).
43 * There is no assignment operator.
44 *
45 * This class is not intended for public subclassing.
46 * @draft ICU 4.8
47 */
48class U_COMMON_API UCharsTrie : public UMemory {
49public:
50    /**
51     * Constructs a UCharsTrie reader instance.
52     *
53     * The trieUChars must contain a copy of a UChar sequence from the UCharsTrieBuilder,
54     * starting with the first UChar of that sequence.
55     * The UCharsTrie object will not read more UChars than
56     * the UCharsTrieBuilder generated in the corresponding build() call.
57     *
58     * The array is not copied/cloned and must not be modified while
59     * the UCharsTrie object is in use.
60     *
61     * @param trieUChars The UChar array that contains the serialized trie.
62     * @draft ICU 4.8
63     */
64    UCharsTrie(const UChar *trieUChars)
65            : ownedArray_(NULL), uchars_(trieUChars),
66              pos_(uchars_), remainingMatchLength_(-1) {}
67
68    /**
69     * Destructor.
70     * @draft ICU 4.8
71     */
72    ~UCharsTrie();
73
74    /**
75     * Copy constructor, copies the other trie reader object and its state,
76     * but not the UChar array which will be shared. (Shallow copy.)
77     * @param other Another UCharsTrie object.
78     * @draft ICU 4.8
79     */
80    UCharsTrie(const UCharsTrie &other)
81            : ownedArray_(NULL), uchars_(other.uchars_),
82              pos_(other.pos_), remainingMatchLength_(other.remainingMatchLength_) {}
83
84    /**
85     * Resets this trie to its initial state.
86     * @return *this
87     * @draft ICU 4.8
88     */
89    UCharsTrie &reset() {
90        pos_=uchars_;
91        remainingMatchLength_=-1;
92        return *this;
93    }
94
95    /**
96     * UCharsTrie state object, for saving a trie's current state
97     * and resetting the trie back to this state later.
98     * @draft ICU 4.8
99     */
100    class State : public UMemory {
101    public:
102        /**
103         * Constructs an empty State.
104         * @draft ICU 4.8
105         */
106        State() { uchars=NULL; }
107    private:
108        friend class UCharsTrie;
109
110        const UChar *uchars;
111        const UChar *pos;
112        int32_t remainingMatchLength;
113    };
114
115    /**
116     * Saves the state of this trie.
117     * @param state The State object to hold the trie's state.
118     * @return *this
119     * @see resetToState
120     * @draft ICU 4.8
121     */
122    const UCharsTrie &saveState(State &state) const {
123        state.uchars=uchars_;
124        state.pos=pos_;
125        state.remainingMatchLength=remainingMatchLength_;
126        return *this;
127    }
128
129    /**
130     * Resets this trie to the saved state.
131     * If the state object contains no state, or the state of a different trie,
132     * then this trie remains unchanged.
133     * @param state The State object which holds a saved trie state.
134     * @return *this
135     * @see saveState
136     * @see reset
137     * @draft ICU 4.8
138     */
139    UCharsTrie &resetToState(const State &state) {
140        if(uchars_==state.uchars && uchars_!=NULL) {
141            pos_=state.pos;
142            remainingMatchLength_=state.remainingMatchLength;
143        }
144        return *this;
145    }
146
147    /**
148     * Determines whether the string so far matches, whether it has a value,
149     * and whether another input UChar can continue a matching string.
150     * @return The match/value Result.
151     * @draft ICU 4.8
152     */
153    UStringTrieResult current() const;
154
155    /**
156     * Traverses the trie from the initial state for this input UChar.
157     * Equivalent to reset().next(uchar).
158     * @param uchar Input char value. Values below 0 and above 0xffff will never match.
159     * @return The match/value Result.
160     * @draft ICU 4.8
161     */
162    inline UStringTrieResult first(int32_t uchar) {
163        remainingMatchLength_=-1;
164        return nextImpl(uchars_, uchar);
165    }
166
167    /**
168     * Traverses the trie from the initial state for the
169     * one or two UTF-16 code units for this input code point.
170     * Equivalent to reset().nextForCodePoint(cp).
171     * @param cp A Unicode code point 0..0x10ffff.
172     * @return The match/value Result.
173     * @draft ICU 4.8
174     */
175    inline UStringTrieResult firstForCodePoint(UChar32 cp) {
176        return cp<=0xffff ?
177            first(cp) :
178            (USTRINGTRIE_HAS_NEXT(first(U16_LEAD(cp))) ?
179                next(U16_TRAIL(cp)) :
180                USTRINGTRIE_NO_MATCH);
181    }
182
183    /**
184     * Traverses the trie from the current state for this input UChar.
185     * @param uchar Input char value. Values below 0 and above 0xffff will never match.
186     * @return The match/value Result.
187     * @draft ICU 4.8
188     */
189    UStringTrieResult next(int32_t uchar);
190
191    /**
192     * Traverses the trie from the current state for the
193     * one or two UTF-16 code units for this input code point.
194     * @param cp A Unicode code point 0..0x10ffff.
195     * @return The match/value Result.
196     * @draft ICU 4.8
197     */
198    inline UStringTrieResult nextForCodePoint(UChar32 cp) {
199        return cp<=0xffff ?
200            next(cp) :
201            (USTRINGTRIE_HAS_NEXT(next(U16_LEAD(cp))) ?
202                next(U16_TRAIL(cp)) :
203                USTRINGTRIE_NO_MATCH);
204    }
205
206    /**
207     * Traverses the trie from the current state for this string.
208     * Equivalent to
209     * \code
210     * Result result=current();
211     * for(each c in s)
212     *   if(!USTRINGTRIE_HAS_NEXT(result)) return USTRINGTRIE_NO_MATCH;
213     *   result=next(c);
214     * return result;
215     * \endcode
216     * @param s A string. Can be NULL if length is 0.
217     * @param length The length of the string. Can be -1 if NUL-terminated.
218     * @return The match/value Result.
219     * @draft ICU 4.8
220     */
221    UStringTrieResult next(const UChar *s, int32_t length);
222
223    /**
224     * Returns a matching string's value if called immediately after
225     * current()/first()/next() returned USTRINGTRIE_INTERMEDIATE_VALUE or USTRINGTRIE_FINAL_VALUE.
226     * getValue() can be called multiple times.
227     *
228     * Do not call getValue() after USTRINGTRIE_NO_MATCH or USTRINGTRIE_NO_VALUE!
229     * @return The value for the string so far.
230     * @draft ICU 4.8
231     */
232    inline int32_t getValue() const {
233        const UChar *pos=pos_;
234        int32_t leadUnit=*pos++;
235        // U_ASSERT(leadUnit>=kMinValueLead);
236        return leadUnit&kValueIsFinal ?
237            readValue(pos, leadUnit&0x7fff) : readNodeValue(pos, leadUnit);
238    }
239
240    /**
241     * Determines whether all strings reachable from the current state
242     * map to the same value.
243     * @param uniqueValue Receives the unique value, if this function returns TRUE.
244     *                    (output-only)
245     * @return TRUE if all strings reachable from the current state
246     *         map to the same value.
247     * @draft ICU 4.8
248     */
249    inline UBool hasUniqueValue(int32_t &uniqueValue) const {
250        const UChar *pos=pos_;
251        // Skip the rest of a pending linear-match node.
252        return pos!=NULL && findUniqueValue(pos+remainingMatchLength_+1, FALSE, uniqueValue);
253    }
254
255    /**
256     * Finds each UChar which continues the string from the current state.
257     * That is, each UChar c for which it would be next(c)!=USTRINGTRIE_NO_MATCH now.
258     * @param out Each next UChar is appended to this object.
259     * @return the number of UChars which continue the string from here
260     * @draft ICU 4.8
261     */
262    int32_t getNextUChars(Appendable &out) const;
263
264    /**
265     * Iterator for all of the (string, value) pairs in a UCharsTrie.
266     * @draft ICU 4.8
267     */
268    class U_COMMON_API Iterator : public UMemory {
269    public:
270        /**
271         * Iterates from the root of a UChar-serialized UCharsTrie.
272         * @param trieUChars The trie UChars.
273         * @param maxStringLength If 0, the iterator returns full strings.
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         * @draft ICU 4.8
280         */
281        Iterator(const UChar *trieUChars, int32_t maxStringLength, UErrorCode &errorCode);
282
283        /**
284         * Iterates from the current state of the specified UCharsTrie.
285         * @param trie The trie whose state will be copied for iteration.
286         * @param maxStringLength If 0, the iterator returns full strings.
287         *                        Otherwise, the iterator returns strings with this maximum length.
288         * @param errorCode Standard ICU error code. Its input value must
289         *                  pass the U_SUCCESS() test, or else the function returns
290         *                  immediately. Check for U_FAILURE() on output or use with
291         *                  function chaining. (See User Guide for details.)
292         * @draft ICU 4.8
293         */
294        Iterator(const UCharsTrie &trie, int32_t maxStringLength, UErrorCode &errorCode);
295
296        /**
297         * Destructor.
298         * @draft ICU 4.8
299         */
300        ~Iterator();
301
302        /**
303         * Resets this iterator to its initial state.
304         * @return *this
305         * @draft ICU 4.8
306         */
307        Iterator &reset();
308
309        /**
310         * @return TRUE if there are more elements.
311         * @draft ICU 4.8
312         */
313        UBool hasNext() const;
314
315        /**
316         * Finds the next (string, value) pair if there is one.
317         *
318         * If the string is truncated to the maximum length and does not
319         * have a real value, then the value is set to -1.
320         * In this case, this "not a real value" is indistinguishable from
321         * a real value of -1.
322         * @param errorCode Standard ICU error code. Its input value must
323         *                  pass the U_SUCCESS() test, or else the function returns
324         *                  immediately. Check for U_FAILURE() on output or use with
325         *                  function chaining. (See User Guide for details.)
326         * @return TRUE if there is another element.
327         * @draft ICU 4.8
328         */
329        UBool next(UErrorCode &errorCode);
330
331        /**
332         * @return The string for the last successful next().
333         * @draft ICU 4.8
334         */
335        const UnicodeString &getString() const { return str_; }
336        /**
337         * @return The value for the last successful next().
338         * @draft ICU 4.8
339         */
340        int32_t getValue() const { return value_; }
341
342    private:
343        UBool truncateAndStop() {
344            pos_=NULL;
345            value_=-1;  // no real value for str
346            return TRUE;
347        }
348
349        const UChar *branchNext(const UChar *pos, int32_t length, UErrorCode &errorCode);
350
351        const UChar *uchars_;
352        const UChar *pos_;
353        const UChar *initialPos_;
354        int32_t remainingMatchLength_;
355        int32_t initialRemainingMatchLength_;
356        UBool skipValue_;  // Skip intermediate value which was already delivered.
357
358        UnicodeString str_;
359        int32_t maxLength_;
360        int32_t value_;
361
362        // The stack stores pairs of integers for backtracking to another
363        // outbound edge of a branch node.
364        // The first integer is an offset from uchars_.
365        // The second integer has the str_.length() from before the node in bits 15..0,
366        // and the remaining branch length in bits 31..16.
367        // (We could store the remaining branch length minus 1 in bits 30..16 and not use the sign bit,
368        // but the code looks more confusing that way.)
369        UVector32 *stack_;
370    };
371
372private:
373    friend class UCharsTrieBuilder;
374
375    /**
376     * Constructs a UCharsTrie reader instance.
377     * Unlike the public constructor which just aliases an array,
378     * this constructor adopts the builder's array.
379     * This constructor is only called by the builder.
380     */
381    UCharsTrie(UChar *adoptUChars, const UChar *trieUChars)
382            : ownedArray_(adoptUChars), uchars_(trieUChars),
383              pos_(uchars_), remainingMatchLength_(-1) {}
384
385    // No assignment operator.
386    UCharsTrie &operator=(const UCharsTrie &other);
387
388    inline void stop() {
389        pos_=NULL;
390    }
391
392    // Reads a compact 32-bit integer.
393    // pos is already after the leadUnit, and the lead unit has bit 15 reset.
394    static inline int32_t readValue(const UChar *pos, int32_t leadUnit) {
395        int32_t value;
396        if(leadUnit<kMinTwoUnitValueLead) {
397            value=leadUnit;
398        } else if(leadUnit<kThreeUnitValueLead) {
399            value=((leadUnit-kMinTwoUnitValueLead)<<16)|*pos;
400        } else {
401            value=(pos[0]<<16)|pos[1];
402        }
403        return value;
404    }
405    static inline const UChar *skipValue(const UChar *pos, int32_t leadUnit) {
406        if(leadUnit>=kMinTwoUnitValueLead) {
407            if(leadUnit<kThreeUnitValueLead) {
408                ++pos;
409            } else {
410                pos+=2;
411            }
412        }
413        return pos;
414    }
415    static inline const UChar *skipValue(const UChar *pos) {
416        int32_t leadUnit=*pos++;
417        return skipValue(pos, leadUnit&0x7fff);
418    }
419
420    static inline int32_t readNodeValue(const UChar *pos, int32_t leadUnit) {
421        // U_ASSERT(kMinValueLead<=leadUnit && leadUnit<kValueIsFinal);
422        int32_t value;
423        if(leadUnit<kMinTwoUnitNodeValueLead) {
424            value=(leadUnit>>6)-1;
425        } else if(leadUnit<kThreeUnitNodeValueLead) {
426            value=(((leadUnit&0x7fc0)-kMinTwoUnitNodeValueLead)<<10)|*pos;
427        } else {
428            value=(pos[0]<<16)|pos[1];
429        }
430        return value;
431    }
432    static inline const UChar *skipNodeValue(const UChar *pos, int32_t leadUnit) {
433        // U_ASSERT(kMinValueLead<=leadUnit && leadUnit<kValueIsFinal);
434        if(leadUnit>=kMinTwoUnitNodeValueLead) {
435            if(leadUnit<kThreeUnitNodeValueLead) {
436                ++pos;
437            } else {
438                pos+=2;
439            }
440        }
441        return pos;
442    }
443
444    static inline const UChar *jumpByDelta(const UChar *pos) {
445        int32_t delta=*pos++;
446        if(delta>=kMinTwoUnitDeltaLead) {
447            if(delta==kThreeUnitDeltaLead) {
448                delta=(pos[0]<<16)|pos[1];
449                pos+=2;
450            } else {
451                delta=((delta-kMinTwoUnitDeltaLead)<<16)|*pos++;
452            }
453        }
454        return pos+delta;
455    }
456
457    static const UChar *skipDelta(const UChar *pos) {
458        int32_t delta=*pos++;
459        if(delta>=kMinTwoUnitDeltaLead) {
460            if(delta==kThreeUnitDeltaLead) {
461                pos+=2;
462            } else {
463                ++pos;
464            }
465        }
466        return pos;
467    }
468
469    static inline UStringTrieResult valueResult(int32_t node) {
470        return (UStringTrieResult)(USTRINGTRIE_INTERMEDIATE_VALUE-(node>>15));
471    }
472
473    // Handles a branch node for both next(uchar) and next(string).
474    UStringTrieResult branchNext(const UChar *pos, int32_t length, int32_t uchar);
475
476    // Requires remainingLength_<0.
477    UStringTrieResult nextImpl(const UChar *pos, int32_t uchar);
478
479    // Helper functions for hasUniqueValue().
480    // Recursively finds a unique value (or whether there is not a unique one)
481    // from a branch.
482    static const UChar *findUniqueValueFromBranch(const UChar *pos, int32_t length,
483                                                  UBool haveUniqueValue, int32_t &uniqueValue);
484    // Recursively finds a unique value (or whether there is not a unique one)
485    // starting from a position on a node lead unit.
486    static UBool findUniqueValue(const UChar *pos, UBool haveUniqueValue, int32_t &uniqueValue);
487
488    // Helper functions for getNextUChars().
489    // getNextUChars() when pos is on a branch node.
490    static void getNextBranchUChars(const UChar *pos, int32_t length, Appendable &out);
491
492    // UCharsTrie data structure
493    //
494    // The trie consists of a series of UChar-serialized nodes for incremental
495    // Unicode string/UChar sequence matching. (UChar=16-bit unsigned integer)
496    // The root node is at the beginning of the trie data.
497    //
498    // Types of nodes are distinguished by their node lead unit ranges.
499    // After each node, except a final-value node, another node follows to
500    // encode match values or continue matching further units.
501    //
502    // Node types:
503    //  - Final-value node: Stores a 32-bit integer in a compact, variable-length format.
504    //    The value is for the string/UChar sequence so far.
505    //  - Match node, optionally with an intermediate value in a different compact format.
506    //    The value, if present, is for the string/UChar sequence so far.
507    //
508    //  Aside from the value, which uses the node lead unit's high bits:
509    //
510    //  - Linear-match node: Matches a number of units.
511    //  - Branch node: Branches to other nodes according to the current input unit.
512    //    The node unit is the length of the branch (number of units to select from)
513    //    minus 1. It is followed by a sub-node:
514    //    - If the length is at most kMaxBranchLinearSubNodeLength, then
515    //      there are length-1 (key, value) pairs and then one more comparison unit.
516    //      If one of the key units matches, then the value is either a final value for
517    //      the string so far, or a "jump" delta to the next node.
518    //      If the last unit matches, then matching continues with the next node.
519    //      (Values have the same encoding as final-value nodes.)
520    //    - If the length is greater than kMaxBranchLinearSubNodeLength, then
521    //      there is one unit and one "jump" delta.
522    //      If the input unit is less than the sub-node unit, then "jump" by delta to
523    //      the next sub-node which will have a length of length/2.
524    //      (The delta has its own compact encoding.)
525    //      Otherwise, skip the "jump" delta to the next sub-node
526    //      which will have a length of length-length/2.
527
528    // Match-node lead unit values, after masking off intermediate-value bits:
529
530    // 0000..002f: Branch node. If node!=0 then the length is node+1, otherwise
531    // the length is one more than the next unit.
532
533    // For a branch sub-node with at most this many entries, we drop down
534    // to a linear search.
535    static const int32_t kMaxBranchLinearSubNodeLength=5;
536
537    // 0030..003f: Linear-match node, match 1..16 units and continue reading the next node.
538    static const int32_t kMinLinearMatch=0x30;
539    static const int32_t kMaxLinearMatchLength=0x10;
540
541    // Match-node lead unit bits 14..6 for the optional intermediate value.
542    // If these bits are 0, then there is no intermediate value.
543    // Otherwise, see the *NodeValue* constants below.
544    static const int32_t kMinValueLead=kMinLinearMatch+kMaxLinearMatchLength;  // 0x0040
545    static const int32_t kNodeTypeMask=kMinValueLead-1;  // 0x003f
546
547    // A final-value node has bit 15 set.
548    static const int32_t kValueIsFinal=0x8000;
549
550    // Compact value: After testing and masking off bit 15, use the following thresholds.
551    static const int32_t kMaxOneUnitValue=0x3fff;
552
553    static const int32_t kMinTwoUnitValueLead=kMaxOneUnitValue+1;  // 0x4000
554    static const int32_t kThreeUnitValueLead=0x7fff;
555
556    static const int32_t kMaxTwoUnitValue=((kThreeUnitValueLead-kMinTwoUnitValueLead)<<16)-1;  // 0x3ffeffff
557
558    // Compact intermediate-value integer, lead unit shared with a branch or linear-match node.
559    static const int32_t kMaxOneUnitNodeValue=0xff;
560    static const int32_t kMinTwoUnitNodeValueLead=kMinValueLead+((kMaxOneUnitNodeValue+1)<<6);  // 0x4040
561    static const int32_t kThreeUnitNodeValueLead=0x7fc0;
562
563    static const int32_t kMaxTwoUnitNodeValue=
564        ((kThreeUnitNodeValueLead-kMinTwoUnitNodeValueLead)<<10)-1;  // 0xfdffff
565
566    // Compact delta integers.
567    static const int32_t kMaxOneUnitDelta=0xfbff;
568    static const int32_t kMinTwoUnitDeltaLead=kMaxOneUnitDelta+1;  // 0xfc00
569    static const int32_t kThreeUnitDeltaLead=0xffff;
570
571    static const int32_t kMaxTwoUnitDelta=((kThreeUnitDeltaLead-kMinTwoUnitDeltaLead)<<16)-1;  // 0x03feffff
572
573    UChar *ownedArray_;
574
575    // Fixed value referencing the UCharsTrie words.
576    const UChar *uchars_;
577
578    // Iterator variables.
579
580    // Pointer to next trie unit to read. NULL if no more matches.
581    const UChar *pos_;
582    // Remaining length of a linear-match node, minus 1. Negative if not in such a node.
583    int32_t remainingMatchLength_;
584};
585
586U_NAMESPACE_END
587
588#endif  // __UCHARSTRIE_H__
589