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"
21 #if U_SHOW_CPLUSPLUS_API
25 * \brief C++ API: Rule Based Break Iterator
28 #if !UCONFIG_NO_BREAK_ITERATION
30 #include "unicode/brkiter.h"
31 #include "unicode/udata.h"
32 #include "unicode/parseerr.h"
33 #include "unicode/schriter.h"
34 // for Apple addition:
35 #include "unicode/urbtok.h"
40 class LanguageBreakEngine
;
41 struct RBBIDataHeader
;
42 class RBBIDataWrapper
;
43 class UnhandledEngine
;
48 * A subclass of BreakIterator whose behavior is specified using a list of rules.
49 * <p>Instances of this class are most commonly created by the factory methods of
50 * BreakIterator::createWordInstance(), BreakIterator::createLineInstance(), etc.,
51 * and then used via the abstract API in class BreakIterator</p>
53 * <p>See the ICU User Guide for information on Break Iterator Rules.</p>
55 * <p>This class is not intended to be subclassed.</p>
57 class U_COMMON_API RuleBasedBreakIterator
/*U_FINAL*/ : public BreakIterator
{
61 * The UText through which this BreakIterator accesses the text
66 #ifndef U_HIDE_INTERNAL_API
68 #endif /* U_HIDE_INTERNAL_API */
70 * The rule data for this BreakIterator instance.
71 * Not for general use; Public only for testing purposes.
74 RBBIDataWrapper
*fData
;
78 * Character categories for the Latin1 subset of Unicode
79 * @internal Apple-only
84 * Character category overrides
85 * @internal Apple-only <rdar://problem/51193810>
91 CategoryOverride
*fCatOverrides
;
92 int32_t fCatOverrideCount
;
95 * The current position of the iterator. Pinned, 0 < fPosition <= text.length.
96 * Never has the value UBRK_DONE (-1).
103 int32_t fRuleStatusIndex
;
106 * Cache of previously determined boundary positions.
109 BreakCache
*fBreakCache
;
112 * Cache of boundary positions within a region of text that has been
113 * sub-divided by dictionary based breaking.
115 class DictionaryCache
;
116 DictionaryCache
*fDictionaryCache
;
120 * If present, UStack of LanguageBreakEngine objects that might handle
121 * dictionary characters. Searched from top to bottom to find an object to
122 * handle a given character.
123 * @internal (private)
125 UStack
*fLanguageBreakEngines
;
129 * If present, the special LanguageBreakEngine used for handling
130 * characters that are in the dictionary set, but not handled by any
131 * LanguageBreakEngine.
132 * @internal (private)
134 UnhandledEngine
*fUnhandledBreakEngine
;
137 * Counter for the number of characters encountered with the "dictionary"
139 * @internal (private)
141 uint32_t fDictionaryCharCount
;
144 * A character iterator that refers to the same text as the UText, above.
145 * Only included for compatibility with old API, which was based on CharacterIterators.
146 * Value may be adopted from outside, or one of fSCharIter or fDCharIter, below.
148 CharacterIterator
*fCharIter
;
151 * When the input text is provided by a UnicodeString, this will point to
152 * a characterIterator that wraps that data. Needed only for the
153 * implementation of getText(), a backwards compatibility issue.
155 StringCharacterIterator fSCharIter
;
158 * True when iteration has run off the end, and iterator functions should return UBRK_DONE.
162 //=======================================================================
164 //=======================================================================
166 // The following is intended to be private in open-source.
167 // However Apple needs it to be public for urbtok.cpp
170 * Constructor from a flattened set of RBBI data in malloced memory.
171 * RulesBasedBreakIterators built from a custom set of rules
172 * are created via this constructor; the rules are compiled
173 * into memory, then the break iterator is constructed here.
175 * The break iterator adopts the memory, and will
177 * @internal (private)
179 RuleBasedBreakIterator(RBBIDataHeader
* data
, UErrorCode
&status
);
183 friend class RBBIRuleBuilder
;
185 friend class BreakIterator
;
189 /** Default constructor. Creates an empty shell of an iterator, with no
190 * rules or text to iterate over. Object can subsequently be assigned to.
193 RuleBasedBreakIterator();
196 * Copy constructor. Will produce a break iterator with the same behavior,
197 * and which iterates over the same text, as the one passed in.
198 * @param that The RuleBasedBreakIterator passed to be copied
201 RuleBasedBreakIterator(const RuleBasedBreakIterator
& that
);
204 * Construct a RuleBasedBreakIterator from a set of rules supplied as a string.
205 * @param rules The break rules to be used.
206 * @param parseError In the event of a syntax error in the rules, provides the location
207 * within the rules of the problem.
208 * @param status Information on any errors encountered.
211 RuleBasedBreakIterator( const UnicodeString
&rules
,
212 UParseError
&parseError
,
216 * Construct a RuleBasedBreakIterator from a set of precompiled binary rules.
217 * Binary rules are obtained from RulesBasedBreakIterator::getBinaryRules().
218 * Construction of a break iterator in this way is substantially faster than
219 * construction from source rules.
221 * Ownership of the storage containing the compiled rules remains with the
222 * caller of this function. The compiled rules must not be modified or
223 * deleted during the life of the break iterator.
225 * The compiled rules are not compatible across different major versions of ICU.
226 * The compiled rules are compatible only between machines with the same
227 * byte ordering (little or big endian) and the same base character set family
230 * @see #getBinaryRules
231 * @param compiledRules A pointer to the compiled break rules to be used.
232 * @param ruleLength The length of the compiled break rules, in bytes. This
233 * corresponds to the length value produced by getBinaryRules().
234 * @param status Information on any errors encountered, including invalid
238 RuleBasedBreakIterator(const uint8_t *compiledRules
,
243 * This constructor uses the udata interface to create a BreakIterator
244 * whose internal tables live in a memory-mapped file. "image" is an
245 * ICU UDataMemory handle for the pre-compiled break iterator tables.
246 * @param image handle to the memory image for the break iterator data.
247 * Ownership of the UDataMemory handle passes to the Break Iterator,
248 * which will be responsible for closing it when it is no longer needed.
249 * @param status Information on any errors encountered.
251 * @see #getBinaryRules
254 RuleBasedBreakIterator(UDataMemory
* image
, UErrorCode
&status
);
260 virtual ~RuleBasedBreakIterator();
263 * Assignment operator. Sets this iterator to have the same behavior,
264 * and iterate over the same text, as the one passed in.
265 * @param that The RuleBasedBreakItertor passed in
266 * @return the newly created RuleBasedBreakIterator
269 RuleBasedBreakIterator
& operator=(const RuleBasedBreakIterator
& that
);
272 * Equality operator. Returns TRUE if both BreakIterators are of the
273 * same class, have the same behavior, and iterate over the same text.
274 * @param that The BreakIterator to be compared for equality
275 * @return TRUE if both BreakIterators are of the
276 * same class, have the same behavior, and iterate over the same text.
279 virtual UBool
operator==(const BreakIterator
& that
) const;
282 * Not-equal operator. If operator== returns TRUE, this returns FALSE,
284 * @param that The BreakIterator to be compared for inequality
285 * @return TRUE if both BreakIterators are not same.
288 inline UBool
operator!=(const BreakIterator
& that
) const;
291 * Returns a newly-constructed RuleBasedBreakIterator with the same
292 * behavior, and iterating over the same text, as this one.
293 * Differs from the copy constructor in that it is polymorphic, and
294 * will correctly clone (copy) a derived class.
295 * clone() is thread safe. Multiple threads may simultaneously
296 * clone the same source break iterator.
297 * @return a newly-constructed RuleBasedBreakIterator
300 virtual RuleBasedBreakIterator
* clone() const;
303 * Compute a hash code for this BreakIterator
304 * @return A hash code
307 virtual int32_t hashCode(void) const;
310 * Returns the description used to create this iterator
311 * @return the description used to create this iterator
314 virtual const UnicodeString
& getRules(void) const;
316 //=======================================================================
317 // BreakIterator overrides
318 //=======================================================================
322 * Return a CharacterIterator over the text being analyzed.
323 * The returned character iterator is owned by the break iterator, and must
324 * not be deleted by the caller. Repeated calls to this function may
325 * return the same CharacterIterator.
328 * The returned character iterator must not be used concurrently with
329 * the break iterator. If concurrent operation is needed, clone the
330 * returned character iterator first and operate on the clone.
333 * When the break iterator is operating on text supplied via a UText,
334 * this function will fail. Lacking any way to signal failures, it
335 * returns an CharacterIterator containing no text.
336 * The function getUText() provides similar functionality,
337 * is reliable, and is more efficient.
340 * TODO: deprecate this function?
342 * @return An iterator over the text being analyzed.
345 virtual CharacterIterator
& getText(void) const;
349 * Get a UText for the text being analyzed.
350 * The returned UText is a shallow clone of the UText used internally
351 * by the break iterator implementation. It can safely be used to
352 * access the text without impacting any break iterator operations,
353 * but the underlying text itself must not be altered.
355 * @param fillIn A UText to be filled in. If NULL, a new UText will be
356 * allocated to hold the result.
357 * @param status receives any error codes.
358 * @return The current UText for this break iterator. If an input
359 * UText was provided, it will always be returned.
362 virtual UText
*getUText(UText
*fillIn
, UErrorCode
&status
) const;
365 * Set the iterator to analyze a new piece of text. This function resets
366 * the current iteration position to the beginning of the text.
367 * @param newText An iterator over the text to analyze. The BreakIterator
368 * takes ownership of the character iterator. The caller MUST NOT delete it!
371 virtual void adoptText(CharacterIterator
* newText
);
374 * Set the iterator to analyze a new piece of text. This function resets
375 * the current iteration position to the beginning of the text.
377 * The BreakIterator will retain a reference to the supplied string.
378 * The caller must not modify or delete the text while the BreakIterator
379 * retains the reference.
381 * @param newText The text to analyze.
384 virtual void setText(const UnicodeString
& newText
);
387 * Reset the break iterator to operate over the text represented by
388 * the UText. The iterator position is reset to the start.
390 * This function makes a shallow clone of the supplied UText. This means
391 * that the caller is free to immediately close or otherwise reuse the
392 * Utext that was passed as a parameter, but that the underlying text itself
393 * must not be altered while being referenced by the break iterator.
395 * @param text The UText used to change the text.
396 * @param status Receives any error codes.
399 virtual void setText(UText
*text
, UErrorCode
&status
);
402 * Sets the current iteration position to the beginning of the text, position zero.
403 * @return The offset of the beginning of the text, zero.
406 virtual int32_t first(void);
409 * Sets the current iteration position to the end of the text.
410 * @return The text's past-the-end offset.
413 virtual int32_t last(void);
416 * Advances the iterator either forward or backward the specified number of steps.
417 * Negative values move backward, and positive values move forward. This is
418 * equivalent to repeatedly calling next() or previous().
419 * @param n The number of steps to move. The sign indicates the direction
420 * (negative is backwards, and positive is forwards).
421 * @return The character offset of the boundary position n boundaries away from
425 virtual int32_t next(int32_t n
);
428 * Advances the iterator to the next boundary position.
429 * @return The position of the first boundary after this one.
432 virtual int32_t next(void);
435 * Moves the iterator backwards, to the last boundary preceding this one.
436 * @return The position of the last boundary position preceding this one.
439 virtual int32_t previous(void);
442 * Sets the iterator to refer to the first boundary position following
443 * the specified position.
444 * @param offset The position from which to begin searching for a break position.
445 * @return The position of the first break after the current position.
448 virtual int32_t following(int32_t offset
);
451 * Sets the iterator to refer to the last boundary position before the
452 * specified position.
453 * @param offset The position to begin searching for a break from.
454 * @return The position of the last boundary before the starting position.
457 virtual int32_t preceding(int32_t offset
);
460 * Returns true if the specified position is a boundary position. As a side
461 * effect, leaves the iterator pointing to the first boundary position at
463 * @param offset the offset to check.
464 * @return True if "offset" is a boundary position.
467 virtual UBool
isBoundary(int32_t offset
);
470 * Returns the current iteration position. Note that UBRK_DONE is never
471 * returned from this function; if iteration has run to the end of a
472 * string, current() will return the length of the string while
473 * next() will return UBRK_DONE).
474 * @return The current iteration position.
477 virtual int32_t current(void) const;
481 * Return the status tag from the break rule that determined the boundary at
482 * the current iteration position. For break rules that do not specify a
483 * status, a default value of 0 is returned. If more than one break rule
484 * would cause a boundary to be located at some position in the text,
485 * the numerically largest of the applicable status values is returned.
487 * Of the standard types of ICU break iterators, only word break and
488 * line break provide status values. The values are defined in
489 * the header file ubrk.h. For Word breaks, the status allows distinguishing between words
490 * that contain alphabetic letters, "words" that appear to be numbers,
491 * punctuation and spaces, words containing ideographic characters, and
492 * more. For Line Break, the status distinguishes between hard (mandatory) breaks
493 * and soft (potential) break positions.
495 * <code>getRuleStatus()</code> can be called after obtaining a boundary
496 * position from <code>next()</code>, <code>previous()</code>, or
497 * any other break iterator functions that returns a boundary position.
499 * Note that <code>getRuleStatus()</code> returns the value corresponding to
500 * <code>current()</code> index even after <code>next()</code> has returned DONE.
502 * When creating custom break rules, one is free to define whatever
503 * status values may be convenient for the application.
505 * @return the status from the break rule that determined the boundary
506 * at the current iteration position.
511 virtual int32_t getRuleStatus() const;
514 * Get the status (tag) values from the break rule(s) that determined the boundary
515 * at the current iteration position.
517 * The returned status value(s) are stored into an array provided by the caller.
518 * The values are stored in sorted (ascending) order.
519 * If the capacity of the output array is insufficient to hold the data,
520 * the output will be truncated to the available length, and a
521 * U_BUFFER_OVERFLOW_ERROR will be signaled.
523 * @param fillInVec an array to be filled in with the status values.
524 * @param capacity the length of the supplied vector. A length of zero causes
525 * the function to return the number of status values, in the
526 * normal way, without attempting to store any values.
527 * @param status receives error codes.
528 * @return The number of rule status values from the rules that determined
529 * the boundary at the current iteration position.
530 * In the event of a U_BUFFER_OVERFLOW_ERROR, the return value
531 * is the total number of status values that were available,
532 * not the reduced number that were actually returned.
536 virtual int32_t getRuleStatusVec(int32_t *fillInVec
, int32_t capacity
, UErrorCode
&status
);
539 * Apple custom extension
540 * Initializes Latin1 category
543 void initLatin1Cat(void);
546 * Apple custom extension
547 * Fetch the next set of tokens.
548 * @param maxTokens The maximum number of tokens to return.
549 * @param outTokenRanges Pointer to output array of token ranges.
550 * @param outTokenFlags (optional) pointer to output array of token flags.
553 int32_t tokenize(int32_t maxTokens
, RuleBasedTokenRange
*outTokenRanges
, unsigned long *outTokenFlags
);
556 * Returns a unique class ID POLYMORPHICALLY. Pure virtual override.
557 * This method is to implement a simple version of RTTI, since not all
558 * C++ compilers support genuine RTTI. Polymorphic operator==() and
559 * clone() methods call this method.
561 * @return The class ID for this object. All objects of a
562 * given class have the same class ID. Objects of
563 * other classes have different class IDs.
566 virtual UClassID
getDynamicClassID(void) const;
569 * Returns the class ID for this class. This is useful only for
570 * comparing to a return value from getDynamicClassID(). For example:
572 * Base* polymorphic_pointer = createPolymorphicObject();
573 * if (polymorphic_pointer->getDynamicClassID() ==
574 * Derived::getStaticClassID()) ...
576 * @return The class ID for all objects of this class.
579 static UClassID U_EXPORT2
getStaticClassID(void);
581 #ifndef U_FORCE_HIDE_DEPRECATED_API
583 * Deprecated functionality. Use clone() instead.
585 * Create a clone (copy) of this break iterator in memory provided
586 * by the caller. The idea is to increase performance by avoiding
587 * a storage allocation. Use of this function is NOT RECOMMENDED.
588 * Performance gains are minimal, and correct buffer management is
589 * tricky. Use clone() instead.
591 * @param stackBuffer The pointer to the memory into which the cloned object
592 * should be placed. If NULL, allocate heap memory
593 * for the cloned object.
594 * @param BufferSize The size of the buffer. If zero, return the required
595 * buffer size, but do not clone the object. If the
596 * size was too small (but not zero), allocate heap
597 * storage for the cloned object.
599 * @param status Error status. U_SAFECLONE_ALLOCATED_WARNING will be
600 * returned if the provided buffer was too small, and
601 * the clone was therefore put on the heap.
603 * @return Pointer to the clone object. This may differ from the stackBuffer
604 * address if the byte alignment of the stack buffer was not suitable
605 * or if the stackBuffer was too small to hold the clone.
606 * @deprecated ICU 52. Use clone() instead.
608 virtual RuleBasedBreakIterator
*createBufferClone(void *stackBuffer
,
611 #endif // U_FORCE_HIDE_DEPRECATED_API
614 * Return the binary form of compiled break rules,
615 * which can then be used to create a new break iterator at some
616 * time in the future. Creating a break iterator from pre-compiled rules
617 * is much faster than building one from the source form of the
620 * The binary data can only be used with the same version of ICU
621 * and on the same platform type (processor endian-ness)
623 * @param length Returns the length of the binary data. (Out parameter.)
625 * @return A pointer to the binary (compiled) rule data. The storage
626 * belongs to the RulesBasedBreakIterator object, not the
627 * caller, and must not be modified or deleted.
630 virtual const uint8_t *getBinaryRules(uint32_t &length
);
633 * Set the subject text string upon which the break iterator is operating
634 * without changing any other aspect of the matching state.
635 * The new and previous text strings must have the same content.
637 * This function is intended for use in environments where ICU is operating on
638 * strings that may move around in memory. It provides a mechanism for notifying
639 * ICU that the string has been relocated, and providing a new UText to access the
640 * string in its new position.
642 * Note that the break iterator implementation never copies the underlying text
643 * of a string being processed, but always operates directly on the original text
644 * provided by the user. Refreshing simply drops the references to the old text
645 * and replaces them with references to the new.
647 * Caution: this function is normally used only by very specialized,
648 * system-level code. One example use case is with garbage collection that moves
649 * the text in memory.
651 * @param input The new (moved) text string.
652 * @param status Receives errors detected by this function.
657 virtual RuleBasedBreakIterator
&refreshInputText(UText
*input
, UErrorCode
&status
);
659 #ifndef U_HIDE_INTERNAL_API
661 * Set the break category overrides for this break iterator, based on delimiter data.
662 * @param locale The locale whose delimiters to use.
663 * @internal Apple only <rdar://problem/51193810>
665 virtual void setCategoryOverrides(Locale locale
);
666 #endif /* U_HIDE_INTERNAL_API */
669 //=======================================================================
671 //=======================================================================
673 * Dumps caches and performs other actions associated with a complete change
674 * in text or iteration position.
675 * @internal (private)
680 * Common initialization function, used by constructors and bufferClone.
681 * @internal (private)
683 void init(UErrorCode
&status
);
686 * Iterate backwards from an arbitrary position in the input text using the
687 * synthesized Safe Reverse rules.
688 * This locates a "Safe Position" from which the forward break rules
689 * will operate correctly. A Safe Position is not necessarily a boundary itself.
691 * @param fromPosition the position in the input text to begin the iteration.
692 * @internal (private)
694 int32_t handleSafePrevious(int32_t fromPosition
);
697 * Find a rule-based boundary by running the state machine.
699 * fPosition, the position in the text to begin from.
701 * fPosition: the boundary following the starting position.
702 * fDictionaryCharCount the number of dictionary characters encountered.
703 * If > 0, the segment will be further subdivided
704 * fRuleStatusIndex Info from the state table indicating which rules caused the boundary.
706 * @internal (private)
708 int32_t handleNext();
709 int32_t handleNextInternal();
713 * This function returns the appropriate LanguageBreakEngine for a
715 * @param c A character in the dictionary set
716 * @internal (private)
718 const LanguageBreakEngine
*getLanguageBreakEngine(UChar32 c
);
721 #ifndef U_HIDE_INTERNAL_API
723 * Debugging function only.
729 * Debugging function only.
734 #endif /* U_HIDE_INTERNAL_API */
737 //------------------------------------------------------------------------------
739 // Inline Functions Definitions ...
741 //------------------------------------------------------------------------------
743 inline UBool
RuleBasedBreakIterator::operator!=(const BreakIterator
& that
) const {
744 return !operator==(that
);
749 #endif /* #if !UCONFIG_NO_BREAK_ITERATION */
751 #endif /* U_SHOW_CPLUSPLUS_API */