rbbi_cache.cpp 26 KB

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