1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
4 ***************************************************************************
5 * Copyright (C) 1999-2016 International Business Machines Corporation *
6 * and others. All rights reserved. *
7 ***************************************************************************
9 **********************************************************************
10 * Date Name Description
11 * 10/22/99 alan Creation.
12 * 11/11/99 rgillam Complete port from Java.
13 **********************************************************************
19 #include "unicode/utypes.h"
23 * \brief C++ API: Rule Based Break Iterator
26 #if !UCONFIG_NO_BREAK_ITERATION
28 #include "unicode/brkiter.h"
29 #include "unicode/udata.h"
30 #include "unicode/parseerr.h"
31 #include "unicode/schriter.h"
32 // for Apple addition:
33 #include "unicode/urbtok.h"
35 #if U_SHOW_CPLUSPLUS_API
39 class LanguageBreakEngine
;
40 struct RBBIDataHeader
;
41 class RBBIDataWrapper
;
42 class UnhandledEngine
;
47 * A subclass of BreakIterator whose behavior is specified using a list of rules.
48 * <p>Instances of this class are most commonly created by the factory methods of
49 * BreakIterator::createWordInstance(), BreakIterator::createLineInstance(), etc.,
50 * and then used via the abstract API in class BreakIterator</p>
52 * <p>See the ICU User Guide for information on Break Iterator Rules.</p>
54 * <p>This class is not intended to be subclassed.</p>
56 class U_COMMON_API RuleBasedBreakIterator
/*U_FINAL*/ : public BreakIterator
{
60 * The UText through which this BreakIterator accesses the text
65 #ifndef U_HIDE_INTERNAL_API
67 #endif /* U_HIDE_INTERNAL_API */
69 * The rule data for this BreakIterator instance.
70 * Not for general use; Public only for testing purposes.
73 RBBIDataWrapper
*fData
;
77 * Character categories for the Latin1 subset of Unicode
78 * @internal Apple-only
83 * The current position of the iterator. Pinned, 0 < fPosition <= text.length.
84 * Never has the value UBRK_DONE (-1).
91 int32_t fRuleStatusIndex
;
94 * Cache of previously determined boundary positions.
97 BreakCache
*fBreakCache
;
100 * Cache of boundary positions within a region of text that has been
101 * sub-divided by dictionary based breaking.
103 class DictionaryCache
;
104 DictionaryCache
*fDictionaryCache
;
108 * If present, UStack of LanguageBreakEngine objects that might handle
109 * dictionary characters. Searched from top to bottom to find an object to
110 * handle a given character.
113 UStack
*fLanguageBreakEngines
;
117 * If present, the special LanguageBreakEngine used for handling
118 * characters that are in the dictionary set, but not handled by any
119 * LangugageBreakEngine.
122 UnhandledEngine
*fUnhandledBreakEngine
;
125 * Counter for the number of characters encountered with the "dictionary"
129 uint32_t fDictionaryCharCount
;
132 * A character iterator that refers to the same text as the UText, above.
133 * Only included for compatibility with old API, which was based on CharacterIterators.
134 * Value may be adopted from outside, or one of fSCharIter or fDCharIter, below.
136 CharacterIterator
*fCharIter
;
139 * When the input text is provided by a UnicodeString, this will point to
140 * a characterIterator that wraps that data. Needed only for the
141 * implementation of getText(), a backwards compatibility issue.
143 StringCharacterIterator fSCharIter
;
146 * True when iteration has run off the end, and iterator functions should return UBRK_DONE.
150 //=======================================================================
152 //=======================================================================
154 // The following is intended to be private in open-source.
155 // However Apple needs it to be public for urbtok.cpp
158 * Constructor from a flattened set of RBBI data in malloced memory.
159 * RulesBasedBreakIterators built from a custom set of rules
160 * are created via this constructor; the rules are compiled
161 * into memory, then the break iterator is constructed here.
163 * The break iterator adopts the memory, and will
167 RuleBasedBreakIterator(RBBIDataHeader
* data
, UErrorCode
&status
);
171 friend class RBBIRuleBuilder
;
173 friend class BreakIterator
;
177 /** Default constructor. Creates an empty shell of an iterator, with no
178 * rules or text to iterate over. Object can subsequently be assigned to.
181 RuleBasedBreakIterator();
184 * Copy constructor. Will produce a break iterator with the same behavior,
185 * and which iterates over the same text, as the one passed in.
186 * @param that The RuleBasedBreakIterator passed to be copied
189 RuleBasedBreakIterator(const RuleBasedBreakIterator
& that
);
192 * Construct a RuleBasedBreakIterator from a set of rules supplied as a string.
193 * @param rules The break rules to be used.
194 * @param parseError In the event of a syntax error in the rules, provides the location
195 * within the rules of the problem.
196 * @param status Information on any errors encountered.
199 RuleBasedBreakIterator( const UnicodeString
&rules
,
200 UParseError
&parseError
,
204 * Construct a RuleBasedBreakIterator from a set of precompiled binary rules.
205 * Binary rules are obtained from RulesBasedBreakIterator::getBinaryRules().
206 * Construction of a break iterator in this way is substantially faster than
207 * construction from source rules.
209 * Ownership of the storage containing the compiled rules remains with the
210 * caller of this function. The compiled rules must not be modified or
211 * deleted during the life of the break iterator.
213 * The compiled rules are not compatible across different major versions of ICU.
214 * The compiled rules are compatible only between machines with the same
215 * byte ordering (little or big endian) and the same base character set family
218 * @see #getBinaryRules
219 * @param compiledRules A pointer to the compiled break rules to be used.
220 * @param ruleLength The length of the compiled break rules, in bytes. This
221 * corresponds to the length value produced by getBinaryRules().
222 * @param status Information on any errors encountered, including invalid
226 RuleBasedBreakIterator(const uint8_t *compiledRules
,
231 * This constructor uses the udata interface to create a BreakIterator
232 * whose internal tables live in a memory-mapped file. "image" is an
233 * ICU UDataMemory handle for the pre-compiled break iterator tables.
234 * @param image handle to the memory image for the break iterator data.
235 * Ownership of the UDataMemory handle passes to the Break Iterator,
236 * which will be responsible for closing it when it is no longer needed.
237 * @param status Information on any errors encountered.
239 * @see #getBinaryRules
242 RuleBasedBreakIterator(UDataMemory
* image
, UErrorCode
&status
);
248 virtual ~RuleBasedBreakIterator();
251 * Assignment operator. Sets this iterator to have the same behavior,
252 * and iterate over the same text, as the one passed in.
253 * @param that The RuleBasedBreakItertor passed in
254 * @return the newly created RuleBasedBreakIterator
257 RuleBasedBreakIterator
& operator=(const RuleBasedBreakIterator
& that
);
260 * Equality operator. Returns TRUE if both BreakIterators are of the
261 * same class, have the same behavior, and iterate over the same text.
262 * @param that The BreakIterator to be compared for equality
263 * @return TRUE if both BreakIterators are of the
264 * same class, have the same behavior, and iterate over the same text.
267 virtual UBool
operator==(const BreakIterator
& that
) const;
270 * Not-equal operator. If operator== returns TRUE, this returns FALSE,
272 * @param that The BreakIterator to be compared for inequality
273 * @return TRUE if both BreakIterators are not same.
276 UBool
operator!=(const BreakIterator
& that
) const;
279 * Returns a newly-constructed RuleBasedBreakIterator with the same
280 * behavior, and iterating over the same text, as this one.
281 * Differs from the copy constructor in that it is polymorphic, and
282 * will correctly clone (copy) a derived class.
283 * clone() is thread safe. Multiple threads may simultaneously
284 * clone the same source break iterator.
285 * @return a newly-constructed RuleBasedBreakIterator
288 virtual BreakIterator
* clone() const;
291 * Compute a hash code for this BreakIterator
292 * @return A hash code
295 virtual int32_t hashCode(void) const;
298 * Returns the description used to create this iterator
299 * @return the description used to create this iterator
302 virtual const UnicodeString
& getRules(void) const;
304 //=======================================================================
305 // BreakIterator overrides
306 //=======================================================================
310 * Return a CharacterIterator over the text being analyzed.
311 * The returned character iterator is owned by the break iterator, and must
312 * not be deleted by the caller. Repeated calls to this function may
313 * return the same CharacterIterator.
316 * The returned character iterator must not be used concurrently with
317 * the break iterator. If concurrent operation is needed, clone the
318 * returned character iterator first and operate on the clone.
321 * When the break iterator is operating on text supplied via a UText,
322 * this function will fail. Lacking any way to signal failures, it
323 * returns an CharacterIterator containing no text.
324 * The function getUText() provides similar functionality,
325 * is reliable, and is more efficient.
328 * TODO: deprecate this function?
330 * @return An iterator over the text being analyzed.
333 virtual CharacterIterator
& getText(void) const;
337 * Get a UText for the text being analyzed.
338 * The returned UText is a shallow clone of the UText used internally
339 * by the break iterator implementation. It can safely be used to
340 * access the text without impacting any break iterator operations,
341 * but the underlying text itself must not be altered.
343 * @param fillIn A UText to be filled in. If NULL, a new UText will be
344 * allocated to hold the result.
345 * @param status receives any error codes.
346 * @return The current UText for this break iterator. If an input
347 * UText was provided, it will always be returned.
350 virtual UText
*getUText(UText
*fillIn
, UErrorCode
&status
) const;
353 * Set the iterator to analyze a new piece of text. This function resets
354 * the current iteration position to the beginning of the text.
355 * @param newText An iterator over the text to analyze. The BreakIterator
356 * takes ownership of the character iterator. The caller MUST NOT delete it!
359 virtual void adoptText(CharacterIterator
* newText
);
362 * Set the iterator to analyze a new piece of text. This function resets
363 * the current iteration position to the beginning of the text.
365 * The BreakIterator will retain a reference to the supplied string.
366 * The caller must not modify or delete the text while the BreakIterator
367 * retains the reference.
369 * @param newText The text to analyze.
372 virtual void setText(const UnicodeString
& newText
);
375 * Reset the break iterator to operate over the text represented by
376 * the UText. The iterator position is reset to the start.
378 * This function makes a shallow clone of the supplied UText. This means
379 * that the caller is free to immediately close or otherwise reuse the
380 * Utext that was passed as a parameter, but that the underlying text itself
381 * must not be altered while being referenced by the break iterator.
383 * @param text The UText used to change the text.
384 * @param status Receives any error codes.
387 virtual void setText(UText
*text
, UErrorCode
&status
);
390 * Sets the current iteration position to the beginning of the text, position zero.
391 * @return The offset of the beginning of the text, zero.
394 virtual int32_t first(void);
397 * Sets the current iteration position to the end of the text.
398 * @return The text's past-the-end offset.
401 virtual int32_t last(void);
404 * Advances the iterator either forward or backward the specified number of steps.
405 * Negative values move backward, and positive values move forward. This is
406 * equivalent to repeatedly calling next() or previous().
407 * @param n The number of steps to move. The sign indicates the direction
408 * (negative is backwards, and positive is forwards).
409 * @return The character offset of the boundary position n boundaries away from
413 virtual int32_t next(int32_t n
);
416 * Advances the iterator to the next boundary position.
417 * @return The position of the first boundary after this one.
420 virtual int32_t next(void);
423 * Moves the iterator backwards, to the last boundary preceding this one.
424 * @return The position of the last boundary position preceding this one.
427 virtual int32_t previous(void);
430 * Sets the iterator to refer to the first boundary position following
431 * the specified position.
432 * @param offset The position from which to begin searching for a break position.
433 * @return The position of the first break after the current position.
436 virtual int32_t following(int32_t offset
);
439 * Sets the iterator to refer to the last boundary position before the
440 * specified position.
441 * @param offset The position to begin searching for a break from.
442 * @return The position of the last boundary before the starting position.
445 virtual int32_t preceding(int32_t offset
);
448 * Returns true if the specified position is a boundary position. As a side
449 * effect, leaves the iterator pointing to the first boundary position at
451 * @param offset the offset to check.
452 * @return True if "offset" is a boundary position.
455 virtual UBool
isBoundary(int32_t offset
);
458 * Returns the current iteration position. Note that UBRK_DONE is never
459 * returned from this function; if iteration has run to the end of a
460 * string, current() will return the length of the string while
461 * next() will return UBRK_DONE).
462 * @return The current iteration position.
465 virtual int32_t current(void) const;
469 * Return the status tag from the break rule that determined the boundary at
470 * the current iteration position. For break rules that do not specify a
471 * status, a default value of 0 is returned. If more than one break rule
472 * would cause a boundary to be located at some position in the text,
473 * the numerically largest of the applicable status values is returned.
475 * Of the standard types of ICU break iterators, only word break and
476 * line break provide status values. The values are defined in
477 * the header file ubrk.h. For Word breaks, the status allows distinguishing between words
478 * that contain alphabetic letters, "words" that appear to be numbers,
479 * punctuation and spaces, words containing ideographic characters, and
480 * more. For Line Break, the status distinguishes between hard (mandatory) breaks
481 * and soft (potential) break positions.
483 * <code>getRuleStatus()</code> can be called after obtaining a boundary
484 * position from <code>next()</code>, <code>previous()</code>, or
485 * any other break iterator functions that returns a boundary position.
487 * Note that <code>getRuleStatus()</code> returns the value corresponding to
488 * <code>current()</code> index even after <code>next()</code> has returned DONE.
490 * When creating custom break rules, one is free to define whatever
491 * status values may be convenient for the application.
493 * @return the status from the break rule that determined the boundary
494 * at the current iteration position.
499 virtual int32_t getRuleStatus() const;
502 * Get the status (tag) values from the break rule(s) that determined the boundary
503 * at the current iteration position.
505 * The returned status value(s) are stored into an array provided by the caller.
506 * The values are stored in sorted (ascending) order.
507 * If the capacity of the output array is insufficient to hold the data,
508 * the output will be truncated to the available length, and a
509 * U_BUFFER_OVERFLOW_ERROR will be signaled.
511 * @param fillInVec an array to be filled in with the status values.
512 * @param capacity the length of the supplied vector. A length of zero causes
513 * the function to return the number of status values, in the
514 * normal way, without attempting to store any values.
515 * @param status receives error codes.
516 * @return The number of rule status values from the rules that determined
517 * the boundary at the current iteration position.
518 * In the event of a U_BUFFER_OVERFLOW_ERROR, the return value
519 * is the total number of status values that were available,
520 * not the reduced number that were actually returned.
524 virtual int32_t getRuleStatusVec(int32_t *fillInVec
, int32_t capacity
, UErrorCode
&status
);
527 * Apple custom extension
528 * Initializes Latin1 category
531 void initLatin1Cat(void);
534 * Apple custom extension
535 * Fetch the next set of tokens.
536 * @param maxTokens The maximum number of tokens to return.
537 * @param outTokenRanges Pointer to output array of token ranges.
538 * @param outTokenFlags (optional) pointer to output array of token flags.
541 int32_t tokenize(int32_t maxTokens
, RuleBasedTokenRange
*outTokenRanges
, unsigned long *outTokenFlags
);
544 * Returns a unique class ID POLYMORPHICALLY. Pure virtual override.
545 * This method is to implement a simple version of RTTI, since not all
546 * C++ compilers support genuine RTTI. Polymorphic operator==() and
547 * clone() methods call this method.
549 * @return The class ID for this object. All objects of a
550 * given class have the same class ID. Objects of
551 * other classes have different class IDs.
554 virtual UClassID
getDynamicClassID(void) const;
557 * Returns the class ID for this class. This is useful only for
558 * comparing to a return value from getDynamicClassID(). For example:
560 * Base* polymorphic_pointer = createPolymorphicObject();
561 * if (polymorphic_pointer->getDynamicClassID() ==
562 * Derived::getStaticClassID()) ...
564 * @return The class ID for all objects of this class.
567 static UClassID U_EXPORT2
getStaticClassID(void);
570 * Deprecated functionality. Use clone() instead.
572 * Create a clone (copy) of this break iterator in memory provided
573 * by the caller. The idea is to increase performance by avoiding
574 * a storage allocation. Use of this function is NOT RECOMMENDED.
575 * Performance gains are minimal, and correct buffer management is
576 * tricky. Use clone() instead.
578 * @param stackBuffer The pointer to the memory into which the cloned object
579 * should be placed. If NULL, allocate heap memory
580 * for the cloned object.
581 * @param BufferSize The size of the buffer. If zero, return the required
582 * buffer size, but do not clone the object. If the
583 * size was too small (but not zero), allocate heap
584 * storage for the cloned object.
586 * @param status Error status. U_SAFECLONE_ALLOCATED_WARNING will be
587 * returned if the provided buffer was too small, and
588 * the clone was therefore put on the heap.
590 * @return Pointer to the clone object. This may differ from the stackBuffer
591 * address if the byte alignment of the stack buffer was not suitable
592 * or if the stackBuffer was too small to hold the clone.
593 * @deprecated ICU 52. Use clone() instead.
595 virtual BreakIterator
* createBufferClone(void *stackBuffer
,
601 * Return the binary form of compiled break rules,
602 * which can then be used to create a new break iterator at some
603 * time in the future. Creating a break iterator from pre-compiled rules
604 * is much faster than building one from the source form of the
607 * The binary data can only be used with the same version of ICU
608 * and on the same platform type (processor endian-ness)
610 * @param length Returns the length of the binary data. (Out parameter.)
612 * @return A pointer to the binary (compiled) rule data. The storage
613 * belongs to the RulesBasedBreakIterator object, not the
614 * caller, and must not be modified or deleted.
617 virtual const uint8_t *getBinaryRules(uint32_t &length
);
620 * Set the subject text string upon which the break iterator is operating
621 * without changing any other aspect of the matching state.
622 * The new and previous text strings must have the same content.
624 * This function is intended for use in environments where ICU is operating on
625 * strings that may move around in memory. It provides a mechanism for notifying
626 * ICU that the string has been relocated, and providing a new UText to access the
627 * string in its new position.
629 * Note that the break iterator implementation never copies the underlying text
630 * of a string being processed, but always operates directly on the original text
631 * provided by the user. Refreshing simply drops the references to the old text
632 * and replaces them with references to the new.
634 * Caution: this function is normally used only by very specialized,
635 * system-level code. One example use case is with garbage collection that moves
636 * the text in memory.
638 * @param input The new (moved) text string.
639 * @param status Receives errors detected by this function.
644 virtual RuleBasedBreakIterator
&refreshInputText(UText
*input
, UErrorCode
&status
);
648 //=======================================================================
650 //=======================================================================
652 * Dumps caches and performs other actions associated with a complete change
653 * in text or iteration position.
654 * @internal (private)
659 * Common initialization function, used by constructors and bufferClone.
660 * @internal (private)
662 void init(UErrorCode
&status
);
665 * Iterate backwards from an arbitrary position in the input text using the
666 * synthesized Safe Reverse rules.
667 * This locates a "Safe Position" from which the forward break rules
668 * will operate correctly. A Safe Position is not necessarily a boundary itself.
670 * @param fromPosition the position in the input text to begin the iteration.
671 * @internal (private)
673 int32_t handleSafePrevious(int32_t fromPosition
);
676 * Find a rule-based boundary by running the state machine.
678 * fPosition, the position in the text to begin from.
680 * fPosition: the boundary following the starting position.
681 * fDictionaryCharCount the number of dictionary characters encountered.
682 * If > 0, the segment will be further subdivided
683 * fRuleStatusIndex Info from the state table indicating which rules caused the boundary.
685 * @internal (private)
687 int32_t handleNext();
688 int32_t handleNextInternal();
692 * This function returns the appropriate LanguageBreakEngine for a
694 * @param c A character in the dictionary set
695 * @internal (private)
697 const LanguageBreakEngine
*getLanguageBreakEngine(UChar32 c
);
700 #ifndef U_HIDE_INTERNAL_API
702 * Debugging function only.
708 * Debugging function only.
713 #endif /* U_HIDE_INTERNAL_API */
716 //------------------------------------------------------------------------------
718 // Inline Functions Definitions ...
720 //------------------------------------------------------------------------------
722 inline UBool
RuleBasedBreakIterator::operator!=(const BreakIterator
& that
) const {
723 return !operator==(that
);
727 #endif // U_SHOW_CPLUSPLUS_API
729 #endif /* #if !UCONFIG_NO_BREAK_ITERATION */