Update contrib.
2 ***************************************************************************
3 * Copyright (C) 1999-2005 International Business Machines Corporation *
4 * and others. All rights reserved. *
5 ***************************************************************************
7 **********************************************************************
8 * Date Name Description
9 * 10/22/99 alan Creation.
10 * 11/11/99 rgillam Complete port from Java.
11 **********************************************************************
17 #include "unicode/utypes.h"
21 * \brief C++ API: Rule Based Break Iterator
24 #if !UCONFIG_NO_BREAK_ITERATION
26 #include "unicode/brkiter.h"
27 #include "unicode/udata.h"
28 #include "unicode/parseerr.h"
36 struct RBBIDataHeader;
37 class RuleBasedBreakIteratorTables;
39 class RBBIDataWrapper;
40 struct RBBIStateTable;
46 * A subclass of BreakIterator whose behavior is specified using a list of rules.
47 * <p>Instances of this class are most commonly created by the factory methods of
48 * BreakIterator::createWordInstance(), BreakIterator::createLineInstance(), etc.,
49 * and then used via the abstract API in class BreakIterator</p>
51 * <p>See the ICU User Guide for information on Break Iterator Rules.</p>
53 * <p>This class is not intended to be subclassed. (Class DictionaryBasedBreakIterator
54 * is a subclass, but that relationship is effectively internal to the ICU
55 * implementation. The subclassing interface to RulesBasedBreakIterator is
56 * not part of the ICU API, and may not remain stable.</p>
59 class U_COMMON_API RuleBasedBreakIterator : public BreakIterator {
63 * The character iterator through which this BreakIterator accesses the text
66 CharacterIterator* fText;
69 * The rule data for this BreakIterator instance
72 RBBIDataWrapper *fData;
74 /** Index of the Rule {tag} values for the most recent match.
77 int32_t fLastRuleStatusIndex;
80 * Rule tag value valid flag.
81 * Some iterator operations don't intrinsically set the correct tag value.
82 * This flag lets us lazily compute the value if we are ever asked for it.
85 UBool fLastStatusIndexValid;
88 * Counter for the number of characters encountered with the "dictionary"
89 * flag set. Normal RBBI iterators don't use it, although the code
90 * for updating it is live. Dictionary Based break iterators (a subclass
91 * of us) access this field directly.
94 uint32_t fDictionaryCharCount;
97 * Debugging flag. Trace operation of state machine when true.
104 //=======================================================================
106 //=======================================================================
109 * Constructor from a flattened set of RBBI data in malloced memory.
110 * RulesBasedBreakIterators built from a custom set of rules
111 * are created via this constructor; the rules are compiled
112 * into memory, then the break iterator is constructed here.
114 * The break iterator adopts the memory, and will
118 RuleBasedBreakIterator(RBBIDataHeader* data, UErrorCode &status);
121 friend class RBBIRuleBuilder;
123 friend class BreakIterator;
129 /** Default constructor. Creates an empty shell of an iterator, with no
130 * rules or text to iterate over. Object can subsequently be assigned to.
133 RuleBasedBreakIterator();
136 * Copy constructor. Will produce a break iterator with the same behavior,
137 * and which iterates over the same text, as the one passed in.
138 * @param that The RuleBasedBreakIterator passed to be copied
141 RuleBasedBreakIterator(const RuleBasedBreakIterator& that);
144 * Construct a RuleBasedBreakIterator from a set of rules supplied as a string.
145 * @param rules The break rules to be used.
146 * @param parseError In the event of a syntax error in the rules, provides the location
147 * within the rules of the problem.
148 * @param status Information on any errors encountered.
151 RuleBasedBreakIterator( const UnicodeString &rules,
152 UParseError &parseError,
157 * This constructor uses the udata interface to create a BreakIterator
158 * whose internal tables live in a memory-mapped file. "image" is an
159 * ICU UDataMemory handle for the pre-compiled break iterator tables.
160 * @param image handle to the memory image for the break iterator data.
161 * Ownership of the UDataMemory handle passes to the Break Iterator,
162 * which will be responsible for closing it when it is no longer needed.
163 * @param status Information on any errors encountered.
165 * @see #getBinaryRules
168 RuleBasedBreakIterator(UDataMemory* image, UErrorCode &status);
174 virtual ~RuleBasedBreakIterator();
177 * Assignment operator. Sets this iterator to have the same behavior,
178 * and iterate over the same text, as the one passed in.
179 * @param that The RuleBasedBreakItertor passed in
180 * @return the newly created RuleBasedBreakIterator
183 RuleBasedBreakIterator& operator=(const RuleBasedBreakIterator& that);
186 * Equality operator. Returns TRUE if both BreakIterators are of the
187 * same class, have the same behavior, and iterate over the same text.
188 * @param that The BreakIterator to be compared for equality
189 * @return TRUE if both BreakIterators are of the
190 * same class, have the same behavior, and iterate over the same text.
193 virtual UBool operator==(const BreakIterator& that) const;
196 * Not-equal operator. If operator== returns TRUE, this returns FALSE,
198 * @param that The BreakIterator to be compared for inequality
199 * @return TRUE if both BreakIterators are not same.
202 UBool operator!=(const BreakIterator& that) const;
205 * Returns a newly-constructed RuleBasedBreakIterator with the same
206 * behavior, and iterating over the same text, as this one.
207 * Differs from the copy constructor in that it is polymorphic, and
208 * will correctly clone (copy) a derived class.
209 * clone() is thread safe. Multiple threads may simultaeneously
210 * clone the same source break iterator.
211 * @return a newly-constructed RuleBasedBreakIterator
214 virtual BreakIterator* clone() const;
217 * Compute a hash code for this BreakIterator
218 * @return A hash code
221 virtual int32_t hashCode(void) const;
224 * Returns the description used to create this iterator
225 * @return the description used to create this iterator
228 virtual const UnicodeString& getRules(void) const;
230 //=======================================================================
231 // BreakIterator overrides
232 //=======================================================================
235 * Return a CharacterIterator over the text being analyzed. This version
236 * of this method returns the actual CharacterIterator we're using internally.
237 * Changing the state of this iterator can have undefined consequences. If
238 * you need to change it, clone it first.
239 * @return An iterator over the text being analyzed.
242 virtual const CharacterIterator& getText(void) const;
246 * Get a UText for the text being analyzed.
247 * The returned UText is a shallow clone of the UText used internally
248 * by the break iterator implementation. It can safely be used to
249 * access the text without impacting any break iterator operations,
250 * but the underlying text itself must not be altered.
252 * @param fillIn A UText to be filled in. If NULL, a new UText will be
253 * allocated to hold the result.
254 * @param status receives any error codes.
255 * @return The current UText for this break iterator. If an input
256 * UText was provided, it will always be returned.
259 virtual UText *getUText(UText *fillIn, UErrorCode &status) const;
262 * Set the iterator to analyze a new piece of text. This function resets
263 * the current iteration position to the beginning of the text.
264 * @param newText An iterator over the text to analyze. The BreakIterator
265 * takes ownership of the character iterator. The caller MUST NOT delete it!
268 virtual void adoptText(CharacterIterator* newText);
271 * Set the iterator to analyze a new piece of text. This function resets
272 * the current iteration position to the beginning of the text.
273 * @param newText The text to analyze.
276 virtual void setText(const UnicodeString& newText);
279 * Reset the break iterator to operate over the text represented by
280 * the UText. The iterator position is reset to the start.
282 * This function makes a shallow clone of the supplied UText. This means
283 * that the caller is free to immediately close or otherwise reuse the
284 * Utext that was passed as a parameter, but that the underlying text itself
285 * must not be altered while being referenced by the break iterator.
287 * @param text The UText used to change the text.
288 * @param status Receives any error codes.
291 virtual void setText(UText *text, UErrorCode &status);
294 * Sets the current iteration position to the beginning of the text.
295 * (i.e., the CharacterIterator's starting offset).
296 * @return The offset of the beginning of the text.
299 virtual int32_t first(void);
302 * Sets the current iteration position to the end of the text.
303 * (i.e., the CharacterIterator's ending offset).
304 * @return The text's past-the-end offset.
307 virtual int32_t last(void);
310 * Advances the iterator either forward or backward the specified number of steps.
311 * Negative values move backward, and positive values move forward. This is
312 * equivalent to repeatedly calling next() or previous().
313 * @param n The number of steps to move. The sign indicates the direction
314 * (negative is backwards, and positive is forwards).
315 * @return The character offset of the boundary position n boundaries away from
319 virtual int32_t next(int32_t n);
322 * Advances the iterator to the next boundary position.
323 * @return The position of the first boundary after this one.
326 virtual int32_t next(void);
329 * Moves the iterator backwards, to the last boundary preceding this one.
330 * @return The position of the last boundary position preceding this one.
333 virtual int32_t previous(void);
336 * Sets the iterator to refer to the first boundary position following
337 * the specified position.
338 * @param offset The position from which to begin searching for a break position.
339 * @return The position of the first break after the current position.
342 virtual int32_t following(int32_t offset);
345 * Sets the iterator to refer to the last boundary position before the
346 * specified position.
347 * @param offset The position to begin searching for a break from.
348 * @return The position of the last boundary before the starting position.
351 virtual int32_t preceding(int32_t offset);
354 * Returns true if the specfied position is a boundary position. As a side
355 * effect, leaves the iterator pointing to the first boundary position at
357 * @param offset the offset to check.
358 * @return True if "offset" is a boundary position.
361 virtual UBool isBoundary(int32_t offset);
364 * Returns the current iteration position.
365 * @return The current iteration position.
368 virtual int32_t current(void) const;
372 * Return the status tag from the break rule that determined the most recently
373 * returned break position. For break rules that do not specify a
374 * status, a default value of 0 is returned. If more than one break rule
375 * would cause a boundary to be located at some position in the text,
376 * the numerically largest of the applicable status values is returned.
378 * Of the standard types of ICU break iterators, only word break and
379 * line break provide status values. The values are defined in
380 * the header file ubrk.h. For Word breaks, the status allows distinguishing between words
381 * that contain alphabetic letters, "words" that appear to be numbers,
382 * punctuation and spaces, words containing ideographic characters, and
383 * more. For Line Break, the status distinguishes between hard (mandatory) breaks
384 * and soft (potential) break positions.
386 * <code>getRuleStatus()</code> can be called after obtaining a boundary
387 * position from <code>next()</code>, <code>previous()</code>, or
388 * any other break iterator functions that returns a boundary position.
390 * When creating custom break rules, one is free to define whatever
391 * status values may be convenient for the application.
393 * Note: this function is not thread safe. It should not have been
394 * declared const, and the const remains only for compatibility
395 * reasons. (The function is logically const, but not bit-wise const).
397 * @return the status from the break rule that determined the most recently
398 * returned break position.
403 virtual int32_t getRuleStatus() const;
406 * Get the status (tag) values from the break rule(s) that determined the most
407 * recently returned break position.
409 * The returned status value(s) are stored into an array provided by the caller.
410 * The values are stored in sorted (ascending) order.
411 * If the capacity of the output array is insufficient to hold the data,
412 * the output will be truncated to the available length, and a
413 * U_BUFFER_OVERFLOW_ERROR will be signaled.
415 * @param fillInVec an array to be filled in with the status values.
416 * @param capacity the length of the supplied vector. A length of zero causes
417 * the function to return the number of status values, in the
418 * normal way, without attemtping to store any values.
419 * @param status receives error codes.
420 * @return The number of rule status values from rules that determined
421 * the most recent boundary returned by the break iterator.
422 * In the event of a U_BUFFER_OVERFLOW_ERROR, the return value
423 * is the total number of status values that were available,
424 * not the reduced number that were actually returned.
428 virtual int32_t getRuleStatusVec(int32_t *fillInVec, int32_t capacity, UErrorCode &status);
431 * Returns a unique class ID POLYMORPHICALLY. Pure virtual override.
432 * This method is to implement a simple version of RTTI, since not all
433 * C++ compilers support genuine RTTI. Polymorphic operator==() and
434 * clone() methods call this method.
436 * @return The class ID for this object. All objects of a
437 * given class have the same class ID. Objects of
438 * other classes have different class IDs.
441 virtual UClassID getDynamicClassID(void) const;
444 * Returns the class ID for this class. This is useful only for
445 * comparing to a return value from getDynamicClassID(). For example:
447 * Base* polymorphic_pointer = createPolymorphicObject();
448 * if (polymorphic_pointer->getDynamicClassID() ==
449 * Derived::getStaticClassID()) ...
451 * @return The class ID for all objects of this class.
454 static UClassID U_EXPORT2 getStaticClassID(void);
457 * Create a clone (copy) of this break iterator in memory provided
458 * by the caller. The idea is to increase performance by avoiding
459 * a storage allocation. Use of this functoin is NOT RECOMMENDED.
460 * Performance gains are minimal, and correct buffer management is
461 * tricky. Use clone() instead.
463 * @param stackBuffer The pointer to the memory into which the cloned object
464 * should be placed. If NULL, allocate heap memory
465 * for the cloned object.
466 * @param BufferSize The size of the buffer. If zero, return the required
467 * buffer size, but do not clone the object. If the
468 * size was too small (but not zero), allocate heap
469 * storage for the cloned object.
471 * @param status Error status. U_SAFECLONE_ALLOCATED_WARNING will be
472 * returned if the the provided buffer was too small, and
473 * the clone was therefore put on the heap.
475 * @return Pointer to the clone object. This may differ from the stackBuffer
476 * address if the byte alignment of the stack buffer was not suitable
477 * or if the stackBuffer was too small to hold the clone.
480 virtual BreakIterator * createBufferClone(void *stackBuffer,
486 * Return the binary form of compiled break rules,
487 * which can then be used to create a new break iterator at some
488 * time in the future. Creating a break iterator from pre-compiled rules
489 * is much faster than building one from the source form of the
492 * The binary data can only be used with the same version of ICU
493 * and on the same platform type (processor endian-ness)
495 * @param length Returns the length of the binary data. (Out paramter.)
497 * @return A pointer to the binary (compiled) rule data. The storage
498 * belongs to the RulesBasedBreakIterator object, not the
499 * caller, and must not be modified or deleted.
502 virtual const uint8_t *getBinaryRules(uint32_t &length);
506 //=======================================================================
508 //=======================================================================
510 * This method is the actual implementation of the next() method. All iteration
511 * vectors through here. This method initializes the state machine to state 1
512 * and advances through the text character by character until we reach the end
513 * of the text or the state machine transitions to state 0. We update our return
514 * value every time the state machine passes through a possible end state.
517 virtual int32_t handleNext(void);
520 * This method backs the iterator back up to a "safe position" in the text.
521 * This is a position that we know, without any context, must be a break position.
522 * The various calling methods then iterate forward from this safe position to
523 * the appropriate position to return. (For more information, see the description
524 * of buildBackwardsStateTable() in RuleBasedBreakIterator.Builder.)
527 virtual int32_t handlePrevious(void);
530 * Dumps caches and performs other actions associated with a complete change
531 * in text or iteration position. This function is a no-op in RuleBasedBreakIterator,
532 * but subclasses can and do override it.
535 virtual void reset(void);
538 * Return true if the category lookup for this char
539 * indicates that it is in the set of dictionary lookup chars.
540 * This function is intended for use by dictionary based break iterators.
541 * @return true if the category lookup for this char
542 * indicates that it is in the set of dictionary lookup chars.
545 virtual UBool isDictionaryChar(UChar32);
548 * Common initialization function, used by constructors and bufferClone.
549 * (Also used by DictionaryBasedBreakIterator::createBufferClone().)
557 * This method backs the iterator back up to a "safe position" in the text.
558 * This is a position that we know, without any context, must be a break position.
559 * The various calling methods then iterate forward from this safe position to
560 * the appropriate position to return. (For more information, see the description
561 * of buildBackwardsStateTable() in RuleBasedBreakIterator.Builder.)
562 * @param statetable state table used of moving backwards
565 int32_t handlePrevious(const RBBIStateTable *statetable);
568 * This method is the actual implementation of the next() method. All iteration
569 * vectors through here. This method initializes the state machine to state 1
570 * and advances through the text character by character until we reach the end
571 * of the text or the state machine transitions to state 0. We update our return
572 * value every time the state machine passes through a possible end state.
573 * @param statetable state table used of moving forwards
576 int32_t handleNext(const RBBIStateTable *statetable);
581 void makeRuleStatusValid();
585 //------------------------------------------------------------------------------
587 // Inline Functions Definitions ...
589 //------------------------------------------------------------------------------
591 inline UBool RuleBasedBreakIterator::operator!=(const BreakIterator& that) const {
592 return !operator==(that);
597 #endif /* #if !UCONFIG_NO_BREAK_ITERATION */