1 // Copyright (C) 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 
4 // file: rbbi_cache.cpp
5 
6 #include "unicode/utypes.h"
7 
8 #if !UCONFIG_NO_BREAK_ITERATION
9 
10 #include "unicode/ubrk.h"
11 #include "unicode/rbbi.h"
12 
13 #include "rbbi_cache.h"
14 
15 #include "brkeng.h"
16 #include "cmemory.h"
17 #include "rbbidata.h"
18 #include "rbbirb.h"
19 #include "uassert.h"
20 #include "uvectr32.h"
21 
22 U_NAMESPACE_BEGIN
23 
24 /*
25  * DictionaryCache implementation
26  */
27 
DictionaryCache(RuleBasedBreakIterator * bi,UErrorCode & status)28 RuleBasedBreakIterator::DictionaryCache::DictionaryCache(RuleBasedBreakIterator *bi, UErrorCode &status) :
29         fBI(bi), fBreaks(status), fPositionInCache(-1),
30         fStart(0), fLimit(0), fFirstRuleStatusIndex(0), fOtherRuleStatusIndex(0) {
31 }
32 
~DictionaryCache()33 RuleBasedBreakIterator::DictionaryCache::~DictionaryCache() {
34 }
35 
reset()36 void RuleBasedBreakIterator::DictionaryCache::reset() {
37     fPositionInCache = -1;
38     fStart = 0;
39     fLimit = 0;
40     fFirstRuleStatusIndex = 0;
41     fOtherRuleStatusIndex = 0;
42     fBreaks.removeAllElements();
43 }
44 
following(int32_t fromPos,int32_t * result,int32_t * statusIndex)45 UBool RuleBasedBreakIterator::DictionaryCache::following(int32_t fromPos, int32_t *result, int32_t *statusIndex) {
46     if (fromPos >= fLimit || fromPos < fStart) {
47         fPositionInCache = -1;
48         return FALSE;
49     }
50 
51     // Sequential iteration, move from previous boundary to the following
52 
53     int32_t r = 0;
54     if (fPositionInCache >= 0 && fPositionInCache < fBreaks.size() && fBreaks.elementAti(fPositionInCache) == fromPos) {
55         ++fPositionInCache;
56         if (fPositionInCache >= fBreaks.size()) {
57             fPositionInCache = -1;
58             return FALSE;
59         }
60         r = fBreaks.elementAti(fPositionInCache);
61         U_ASSERT(r > fromPos);
62         *result = r;
63         *statusIndex = fOtherRuleStatusIndex;
64         return TRUE;
65     }
66 
67     // Random indexing. Linear search for the boundary following the given position.
68 
69     for (fPositionInCache = 0; fPositionInCache < fBreaks.size(); ++fPositionInCache) {
70         r= fBreaks.elementAti(fPositionInCache);
71         if (r > fromPos) {
72             *result = r;
73             *statusIndex = fOtherRuleStatusIndex;
74             return TRUE;
75         }
76     }
77     UPRV_UNREACHABLE_EXIT;
78 }
79 
80 
preceding(int32_t fromPos,int32_t * result,int32_t * statusIndex)81 UBool RuleBasedBreakIterator::DictionaryCache::preceding(int32_t fromPos, int32_t *result, int32_t *statusIndex) {
82     if (fromPos <= fStart || fromPos > fLimit) {
83         fPositionInCache = -1;
84         return FALSE;
85     }
86 
87     if (fromPos == fLimit) {
88         fPositionInCache = fBreaks.size() - 1;
89         if (fPositionInCache >= 0) {
90             U_ASSERT(fBreaks.elementAti(fPositionInCache) == fromPos);
91         }
92     }
93 
94     int32_t r;
95     if (fPositionInCache > 0 && fPositionInCache < fBreaks.size() && fBreaks.elementAti(fPositionInCache) == fromPos) {
96         --fPositionInCache;
97         r = fBreaks.elementAti(fPositionInCache);
98         U_ASSERT(r < fromPos);
99         *result = r;
100         *statusIndex = ( r== fStart) ? fFirstRuleStatusIndex : fOtherRuleStatusIndex;
101         return TRUE;
102     }
103 
104     if (fPositionInCache == 0) {
105         fPositionInCache = -1;
106         return FALSE;
107     }
108 
109     for (fPositionInCache = fBreaks.size()-1; fPositionInCache >= 0; --fPositionInCache) {
110         r = fBreaks.elementAti(fPositionInCache);
111         if (r < fromPos) {
112             *result = r;
113             *statusIndex = ( r == fStart) ? fFirstRuleStatusIndex : fOtherRuleStatusIndex;
114             return TRUE;
115         }
116     }
117     UPRV_UNREACHABLE_EXIT;
118 }
119 
populateDictionary(int32_t startPos,int32_t endPos,int32_t firstRuleStatus,int32_t otherRuleStatus)120 void RuleBasedBreakIterator::DictionaryCache::populateDictionary(int32_t startPos, int32_t endPos,
121                                        int32_t firstRuleStatus, int32_t otherRuleStatus) {
122     if ((endPos - startPos) <= 1) {
123         return;
124     }
125 
126     reset();
127     fFirstRuleStatusIndex = firstRuleStatus;
128     fOtherRuleStatusIndex = otherRuleStatus;
129 
130     int32_t rangeStart = startPos;
131     int32_t rangeEnd = endPos;
132 
133     uint16_t    category;
134     int32_t     current;
135     UErrorCode  status = U_ZERO_ERROR;
136     int32_t     foundBreakCount = 0;
137     UText      *text = &fBI->fText;
138 
139     // Loop through the text, looking for ranges of dictionary characters.
140     // For each span, find the appropriate break engine, and ask it to find
141     // any breaks within the span.
142 
143     utext_setNativeIndex(text, rangeStart);
144     UChar32     c = utext_current32(text);
145     category = ucptrie_get(fBI->fData->fTrie, c);
146     uint32_t dictStart = fBI->fData->fForwardTable->fDictCategoriesStart;
147 
148     while(U_SUCCESS(status)) {
149         while((current = (int32_t)UTEXT_GETNATIVEINDEX(text)) < rangeEnd
150                 && (category < dictStart)) {
151             utext_next32(text);           // TODO: cleaner loop structure.
152             c = utext_current32(text);
153             category = ucptrie_get(fBI->fData->fTrie, c);
154         }
155         if (current >= rangeEnd) {
156             break;
157         }
158 
159         // We now have a dictionary character. Get the appropriate language object
160         // to deal with it.
161         const LanguageBreakEngine *lbe = fBI->getLanguageBreakEngine(c);
162 
163         // Ask the language object if there are any breaks. It will add them to the cache and
164         // leave the text pointer on the other side of its range, ready to search for the next one.
165         if (lbe != NULL) {
166             foundBreakCount += lbe->findBreaks(text, rangeStart, rangeEnd, fBreaks, status);
167         }
168 
169         // Reload the loop variables for the next go-round
170         c = utext_current32(text);
171         category = ucptrie_get(fBI->fData->fTrie, c);
172     }
173 
174     // If we found breaks, ensure that the first and last entries are
175     // the original starting and ending position. And initialize the
176     // cache iteration position to the first entry.
177 
178     // printf("foundBreakCount = %d\n", foundBreakCount);
179     if (foundBreakCount > 0) {
180         U_ASSERT(foundBreakCount == fBreaks.size());
181         if (startPos < fBreaks.elementAti(0)) {
182             // The dictionary did not place a boundary at the start of the segment of text.
183             // Add one now. This should not commonly happen, but it would be easy for interactions
184             // of the rules for dictionary segments and the break engine implementations to
185             // inadvertently cause it. Cover it here, just in case.
186             fBreaks.insertElementAt(startPos, 0, status);
187         }
188         if (endPos > fBreaks.peeki()) {
189             fBreaks.push(endPos, status);
190         }
191         fPositionInCache = 0;
192         // Note: Dictionary matching may extend beyond the original limit.
193         fStart = fBreaks.elementAti(0);
194         fLimit = fBreaks.peeki();
195     } else {
196         // there were no language-based breaks, even though the segment contained
197         // dictionary characters. Subsequent attempts to fetch boundaries from the dictionary cache
198         // for this range will fail, and the calling code will fall back to the rule based boundaries.
199     }
200 }
201 
202 
203 /*
204  *   BreakCache implementation
205  */
206 
BreakCache(RuleBasedBreakIterator * bi,UErrorCode & status)207 RuleBasedBreakIterator::BreakCache::BreakCache(RuleBasedBreakIterator *bi, UErrorCode &status) :
208         fBI(bi), fSideBuffer(status) {
209     reset();
210 }
211 
212 
~BreakCache()213 RuleBasedBreakIterator::BreakCache::~BreakCache() {
214 }
215 
216 
reset(int32_t pos,int32_t ruleStatus)217 void RuleBasedBreakIterator::BreakCache::reset(int32_t pos, int32_t ruleStatus) {
218     fStartBufIdx = 0;
219     fEndBufIdx = 0;
220     fTextIdx = pos;
221     fBufIdx = 0;
222     fBoundaries[0] = pos;
223     fStatuses[0] = (uint16_t)ruleStatus;
224 }
225 
226 
current()227 int32_t  RuleBasedBreakIterator::BreakCache::current() {
228     fBI->fPosition = fTextIdx;
229     fBI->fRuleStatusIndex = fStatuses[fBufIdx];
230     fBI->fDone = FALSE;
231     return fTextIdx;
232 }
233 
234 
following(int32_t startPos,UErrorCode & status)235 void RuleBasedBreakIterator::BreakCache::following(int32_t startPos, UErrorCode &status) {
236     if (U_FAILURE(status)) {
237         return;
238     }
239     if (startPos == fTextIdx || seek(startPos) || populateNear(startPos, status)) {
240         // startPos is in the cache. Do a next() from that position.
241         // TODO: an awkward set of interactions with bi->fDone
242         //       seek() does not clear it; it can't because of interactions with populateNear().
243         //       next() does not clear it in the fast-path case, where everything matters. Maybe it should.
244         //       So clear it here, for the case where seek() succeeded on an iterator that had previously run off the end.
245         fBI->fDone = false;
246         next();
247     }
248     return;
249 }
250 
251 
preceding(int32_t startPos,UErrorCode & status)252 void RuleBasedBreakIterator::BreakCache::preceding(int32_t startPos, UErrorCode &status) {
253     if (U_FAILURE(status)) {
254         return;
255     }
256     if (startPos == fTextIdx || seek(startPos) || populateNear(startPos, status)) {
257         if (startPos == fTextIdx) {
258             previous(status);
259         } else {
260             // seek() leaves the BreakCache positioned at the preceding boundary
261             //        if the requested position is between two boundaries.
262             // current() pushes the BreakCache position out to the BreakIterator itself.
263             U_ASSERT(startPos > fTextIdx);
264             current();
265         }
266     }
267     return;
268 }
269 
270 
271 /*
272  * Out-of-line code for BreakCache::next().
273  * Cache does not already contain the boundary
274  */
nextOL()275 void RuleBasedBreakIterator::BreakCache::nextOL() {
276     fBI->fDone = !populateFollowing();
277     fBI->fPosition = fTextIdx;
278     fBI->fRuleStatusIndex = fStatuses[fBufIdx];
279     return;
280 }
281 
282 
previous(UErrorCode & status)283 void RuleBasedBreakIterator::BreakCache::previous(UErrorCode &status) {
284     if (U_FAILURE(status)) {
285         return;
286     }
287     int32_t initialBufIdx = fBufIdx;
288     if (fBufIdx == fStartBufIdx) {
289         // At start of cache. Prepend to it.
290         populatePreceding(status);
291     } else {
292         // Cache already holds the next boundary
293         fBufIdx = modChunkSize(fBufIdx - 1);
294         fTextIdx = fBoundaries[fBufIdx];
295     }
296     fBI->fDone = (fBufIdx == initialBufIdx);
297     fBI->fPosition = fTextIdx;
298     fBI->fRuleStatusIndex = fStatuses[fBufIdx];
299     return;
300 }
301 
302 
seek(int32_t pos)303 UBool RuleBasedBreakIterator::BreakCache::seek(int32_t pos) {
304     if (pos < fBoundaries[fStartBufIdx] || pos > fBoundaries[fEndBufIdx]) {
305         return FALSE;
306     }
307     if (pos == fBoundaries[fStartBufIdx]) {
308         // Common case: seek(0), from BreakIterator::first()
309         fBufIdx = fStartBufIdx;
310         fTextIdx = fBoundaries[fBufIdx];
311         return TRUE;
312     }
313     if (pos == fBoundaries[fEndBufIdx]) {
314         fBufIdx = fEndBufIdx;
315         fTextIdx = fBoundaries[fBufIdx];
316         return TRUE;
317     }
318 
319     int32_t min = fStartBufIdx;
320     int32_t max = fEndBufIdx;
321     while (min != max) {
322         int32_t probe = (min + max + (min>max ? CACHE_SIZE : 0)) / 2;
323         probe = modChunkSize(probe);
324         if (fBoundaries[probe] > pos) {
325             max = probe;
326         } else {
327             min = modChunkSize(probe + 1);
328         }
329     }
330     U_ASSERT(fBoundaries[max] > pos);
331     fBufIdx = modChunkSize(max - 1);
332     fTextIdx = fBoundaries[fBufIdx];
333     U_ASSERT(fTextIdx <= pos);
334     return TRUE;
335 }
336 
337 
populateNear(int32_t position,UErrorCode & status)338 UBool RuleBasedBreakIterator::BreakCache::populateNear(int32_t position, UErrorCode &status) {
339     if (U_FAILURE(status)) {
340         return FALSE;
341     }
342     U_ASSERT(position < fBoundaries[fStartBufIdx] || position > fBoundaries[fEndBufIdx]);
343 
344     // Find a boundary somewhere in the vicinity of the requested position.
345     // Depending on the safe rules and the text data, it could be either before, at, or after
346     // the requested position.
347 
348 
349     // If the requested position is not near already cached positions, clear the existing cache,
350     // find a near-by boundary and begin new cache contents there.
351 
352     if ((position < fBoundaries[fStartBufIdx] - 15) || position > (fBoundaries[fEndBufIdx] + 15)) {
353         int32_t aBoundary = 0;
354         int32_t ruleStatusIndex = 0;
355         if (position > 20) {
356             int32_t backupPos = fBI->handleSafePrevious(position);
357 
358             if (backupPos > 0) {
359                 // Advance to the boundary following the backup position.
360                 // There is a complication: the safe reverse rules identify pairs of code points
361                 // that are safe. If advancing from the safe point moves forwards by less than
362                 // two code points, we need to advance one more time to ensure that the boundary
363                 // is good, including a correct rules status value.
364                 //
365                 fBI->fPosition = backupPos;
366                 aBoundary = fBI->handleNext();
367                 if (aBoundary <= backupPos + 4) {
368                     // +4 is a quick test for possibly having advanced only one codepoint.
369                     // Four being the length of the longest potential code point, a supplementary in UTF-8
370                     utext_setNativeIndex(&fBI->fText, aBoundary);
371                     if (backupPos == utext_getPreviousNativeIndex(&fBI->fText)) {
372                         // The initial handleNext() only advanced by a single code point. Go again.
373                         aBoundary = fBI->handleNext();   // Safe rules identify safe pairs.
374                     }
375                 }
376                 ruleStatusIndex = fBI->fRuleStatusIndex;
377             }
378         }
379         reset(aBoundary, ruleStatusIndex);        // Reset cache to hold aBoundary as a single starting point.
380     }
381 
382     // Fill in boundaries between existing cache content and the new requested position.
383 
384     if (fBoundaries[fEndBufIdx] < position) {
385         // The last position in the cache precedes the requested position.
386         // Add following position(s) to the cache.
387         while (fBoundaries[fEndBufIdx] < position) {
388             if (!populateFollowing()) {
389                 UPRV_UNREACHABLE_EXIT;
390             }
391         }
392         fBufIdx = fEndBufIdx;                      // Set iterator position to the end of the buffer.
393         fTextIdx = fBoundaries[fBufIdx];           // Required because populateFollowing may add extra boundaries.
394         while (fTextIdx > position) {              // Move backwards to a position at or preceding the requested pos.
395             previous(status);
396         }
397         return true;
398     }
399 
400     if (fBoundaries[fStartBufIdx] > position) {
401         // The first position in the cache is beyond the requested position.
402         // back up more until we get a boundary <= the requested position.
403         while (fBoundaries[fStartBufIdx] > position) {
404             populatePreceding(status);
405         }
406         fBufIdx = fStartBufIdx;                    // Set iterator position to the start of the buffer.
407         fTextIdx = fBoundaries[fBufIdx];           // Required because populatePreceding may add extra boundaries.
408         while (fTextIdx < position) {              // Move forwards to a position at or following the requested pos.
409             next();
410         }
411         if (fTextIdx > position) {
412             // If position is not itself a boundary, the next() loop above will overshoot.
413             // Back up one, leaving cache position at the boundary preceding the requested position.
414             previous(status);
415         }
416         return true;
417     }
418 
419     U_ASSERT(fTextIdx == position);
420     return true;
421 }
422 
423 
424 
populateFollowing()425 UBool RuleBasedBreakIterator::BreakCache::populateFollowing() {
426     int32_t fromPosition = fBoundaries[fEndBufIdx];
427     int32_t fromRuleStatusIdx = fStatuses[fEndBufIdx];
428     int32_t pos = 0;
429     int32_t ruleStatusIdx = 0;
430 
431     if (fBI->fDictionaryCache->following(fromPosition, &pos, &ruleStatusIdx)) {
432         addFollowing(pos, ruleStatusIdx, UpdateCachePosition);
433         return TRUE;
434     }
435 
436     fBI->fPosition = fromPosition;
437     pos = fBI->handleNext();
438     if (pos == UBRK_DONE) {
439         return FALSE;
440     }
441 
442     ruleStatusIdx = fBI->fRuleStatusIndex;
443     if (fBI->fDictionaryCharCount > 0) {
444         // The text segment obtained from the rules includes dictionary characters.
445         // Subdivide it, with subdivided results going into the dictionary cache.
446         fBI->fDictionaryCache->populateDictionary(fromPosition, pos, fromRuleStatusIdx, ruleStatusIdx);
447         if (fBI->fDictionaryCache->following(fromPosition, &pos, &ruleStatusIdx)) {
448             addFollowing(pos, ruleStatusIdx, UpdateCachePosition);
449             return TRUE;
450             // TODO: may want to move a sizable chunk of dictionary cache to break cache at this point.
451             //       But be careful with interactions with populateNear().
452         }
453     }
454 
455     // Rule based segment did not include dictionary characters.
456     // Or, it did contain dictionary chars, but the dictionary segmenter didn't handle them,
457     //    meaning that we didn't take the return, above.
458     // Add its end point to the cache.
459     addFollowing(pos, ruleStatusIdx, UpdateCachePosition);
460 
461     // Add several non-dictionary boundaries at this point, to optimize straight forward iteration.
462     //    (subsequent calls to BreakIterator::next() will take the fast path, getting cached results.
463     //
464     for (int count=0; count<6; ++count) {
465         pos = fBI->handleNext();
466         if (pos == UBRK_DONE || fBI->fDictionaryCharCount > 0) {
467             break;
468         }
469         addFollowing(pos, fBI->fRuleStatusIndex, RetainCachePosition);
470     }
471 
472     return TRUE;
473 }
474 
475 
populatePreceding(UErrorCode & status)476 UBool RuleBasedBreakIterator::BreakCache::populatePreceding(UErrorCode &status) {
477     if (U_FAILURE(status)) {
478         return FALSE;
479     }
480 
481     int32_t fromPosition = fBoundaries[fStartBufIdx];
482     if (fromPosition == 0) {
483         return FALSE;
484     }
485 
486     int32_t position = 0;
487     int32_t positionStatusIdx = 0;
488 
489     if (fBI->fDictionaryCache->preceding(fromPosition, &position, &positionStatusIdx)) {
490         addPreceding(position, positionStatusIdx, UpdateCachePosition);
491         return TRUE;
492     }
493 
494     int32_t backupPosition = fromPosition;
495 
496     // Find a boundary somewhere preceding the first already-cached boundary
497     do {
498         backupPosition = backupPosition - 30;
499         if (backupPosition <= 0) {
500             backupPosition = 0;
501         } else {
502             backupPosition = fBI->handleSafePrevious(backupPosition);
503         }
504         if (backupPosition == UBRK_DONE || backupPosition == 0) {
505             position = 0;
506             positionStatusIdx = 0;
507         } else {
508             // Advance to the boundary following the backup position.
509             // There is a complication: the safe reverse rules identify pairs of code points
510             // that are safe. If advancing from the safe point moves forwards by less than
511             // two code points, we need to advance one more time to ensure that the boundary
512             // is good, including a correct rules status value.
513             //
514             fBI->fPosition = backupPosition;
515             position = fBI->handleNext();
516             if (position <= backupPosition + 4) {
517                 // +4 is a quick test for possibly having advanced only one codepoint.
518                 // Four being the length of the longest potential code point, a supplementary in UTF-8
519                 utext_setNativeIndex(&fBI->fText, position);
520                 if (backupPosition == utext_getPreviousNativeIndex(&fBI->fText)) {
521                     // The initial handleNext() only advanced by a single code point. Go again.
522                     position = fBI->handleNext();   // Safe rules identify safe pairs.
523                 }
524             }
525             positionStatusIdx = fBI->fRuleStatusIndex;
526         }
527     } while (position >= fromPosition);
528 
529     // Find boundaries between the one we just located and the first already-cached boundary
530     // Put them in a side buffer, because we don't yet know where they will fall in the circular cache buffer..
531 
532     fSideBuffer.removeAllElements();
533     fSideBuffer.addElement(position, status);
534     fSideBuffer.addElement(positionStatusIdx, status);
535 
536     do {
537         int32_t prevPosition = fBI->fPosition = position;
538         int32_t prevStatusIdx = positionStatusIdx;
539         position = fBI->handleNext();
540         positionStatusIdx = fBI->fRuleStatusIndex;
541         if (position == UBRK_DONE) {
542             break;
543         }
544 
545         UBool segmentHandledByDictionary = FALSE;
546         if (fBI->fDictionaryCharCount != 0) {
547             // Segment from the rules includes dictionary characters.
548             // Subdivide it, with subdivided results going into the dictionary cache.
549             int32_t dictSegEndPosition = position;
550             fBI->fDictionaryCache->populateDictionary(prevPosition, dictSegEndPosition, prevStatusIdx, positionStatusIdx);
551             while (fBI->fDictionaryCache->following(prevPosition, &position, &positionStatusIdx)) {
552                 segmentHandledByDictionary = true;
553                 U_ASSERT(position > prevPosition);
554                 if (position >= fromPosition) {
555                     break;
556                 }
557                 U_ASSERT(position <= dictSegEndPosition);
558                 fSideBuffer.addElement(position, status);
559                 fSideBuffer.addElement(positionStatusIdx, status);
560                 prevPosition = position;
561             }
562             U_ASSERT(position==dictSegEndPosition || position>=fromPosition);
563         }
564 
565         if (!segmentHandledByDictionary && position < fromPosition) {
566             fSideBuffer.addElement(position, status);
567             fSideBuffer.addElement(positionStatusIdx, status);
568         }
569     } while (position < fromPosition);
570 
571     // Move boundaries from the side buffer to the main circular buffer.
572     UBool success = FALSE;
573     if (!fSideBuffer.isEmpty()) {
574         positionStatusIdx = fSideBuffer.popi();
575         position = fSideBuffer.popi();
576         addPreceding(position, positionStatusIdx, UpdateCachePosition);
577         success = TRUE;
578     }
579 
580     while (!fSideBuffer.isEmpty()) {
581         positionStatusIdx = fSideBuffer.popi();
582         position = fSideBuffer.popi();
583         if (!addPreceding(position, positionStatusIdx, RetainCachePosition)) {
584             // No space in circular buffer to hold a new preceding result while
585             // also retaining the current cache (iteration) position.
586             // Bailing out is safe; the cache will refill again if needed.
587             break;
588         }
589     }
590 
591     return success;
592 }
593 
594 
addFollowing(int32_t position,int32_t ruleStatusIdx,UpdatePositionValues update)595 void RuleBasedBreakIterator::BreakCache::addFollowing(int32_t position, int32_t ruleStatusIdx, UpdatePositionValues update) {
596     U_ASSERT(position > fBoundaries[fEndBufIdx]);
597     U_ASSERT(ruleStatusIdx <= UINT16_MAX);
598     int32_t nextIdx = modChunkSize(fEndBufIdx + 1);
599     if (nextIdx == fStartBufIdx) {
600         fStartBufIdx = modChunkSize(fStartBufIdx + 6);    // TODO: experiment. Probably revert to 1.
601     }
602     fBoundaries[nextIdx] = position;
603     fStatuses[nextIdx] = static_cast<uint16_t>(ruleStatusIdx);
604     fEndBufIdx = nextIdx;
605     if (update == UpdateCachePosition) {
606         // Set current position to the newly added boundary.
607         fBufIdx = nextIdx;
608         fTextIdx = position;
609     } else {
610         // Retaining the original cache position.
611         // Check if the added boundary wraps around the buffer, and would over-write the original position.
612         // It's the responsibility of callers of this function to not add too many.
613         U_ASSERT(nextIdx != fBufIdx);
614     }
615 }
616 
addPreceding(int32_t position,int32_t ruleStatusIdx,UpdatePositionValues update)617 bool RuleBasedBreakIterator::BreakCache::addPreceding(int32_t position, int32_t ruleStatusIdx, UpdatePositionValues update) {
618     U_ASSERT(position < fBoundaries[fStartBufIdx]);
619     U_ASSERT(ruleStatusIdx <= UINT16_MAX);
620     int32_t nextIdx = modChunkSize(fStartBufIdx - 1);
621     if (nextIdx == fEndBufIdx) {
622         if (fBufIdx == fEndBufIdx && update == RetainCachePosition) {
623             // Failure. The insertion of the new boundary would claim the buffer position that is the
624             // current iteration position. And we also want to retain the current iteration position.
625             // (The buffer is already completely full of entries that precede the iteration position.)
626             return false;
627         }
628         fEndBufIdx = modChunkSize(fEndBufIdx - 1);
629     }
630     fBoundaries[nextIdx] = position;
631     fStatuses[nextIdx] = static_cast<uint16_t>(ruleStatusIdx);
632     fStartBufIdx = nextIdx;
633     if (update == UpdateCachePosition) {
634         fBufIdx = nextIdx;
635         fTextIdx = position;
636     }
637     return true;
638 }
639 
640 
dumpCache()641 void RuleBasedBreakIterator::BreakCache::dumpCache() {
642 #ifdef RBBI_DEBUG
643     RBBIDebugPrintf("fTextIdx:%d   fBufIdx:%d\n", fTextIdx, fBufIdx);
644     for (int32_t i=fStartBufIdx; ; i=modChunkSize(i+1)) {
645         RBBIDebugPrintf("%d  %d\n", i, fBoundaries[i]);
646         if (i == fEndBufIdx) {
647             break;
648         }
649     }
650 #endif
651 }
652 
653 U_NAMESPACE_END
654 
655 #endif // #if !UCONFIG_NO_BREAK_ITERATION
656