@@ -98,6 +98,26 @@ void grapheme_substr_ascii(char *str, size_t str_len, int32_t f, int32_t l, char
9898 goto finish; \
9999 }
100100
101+ /* Find the next match that starts at or after "from". When "from" falls inside
102+ * a contraction, such as a Thai prevowel and its consonant, ICU returns the match
103+ * that starts at the contraction, before "from". Search again from each following
104+ * grapheme boundary, so that a match overlapping the skipped one is not missed. */
105+ static int32_t grapheme_usearch_next_from (UStringSearch *src, UBreakIterator *bi, int32_t from, UErrorCode *status)
106+ {
107+ int32_t pos = usearch_next (src, status);
108+ int32_t boundary = from;
109+
110+ while (U_SUCCESS (*status) && pos != USEARCH_DONE && pos < from) {
111+ boundary = ubrk_following (bi, boundary);
112+ if (boundary == UBRK_DONE ) {
113+ return USEARCH_DONE ;
114+ }
115+ usearch_setOffset (src, boundary, status);
116+ pos = usearch_next (src, status);
117+ }
118+
119+ return pos;
120+ }
101121
102122/* {{{ grapheme_strpos_utf16 - strrpos using utf16*/
103123int32_t grapheme_strpos_utf16 (char *haystack, size_t haystack_len, char *needle, size_t needle_len, int32_t offset, int32_t *puchar_pos, int f_ignore_case, int last, const char * locale)
@@ -182,14 +202,15 @@ int32_t grapheme_strpos_utf16(char *haystack, size_t haystack_len, char *needle,
182202 } else {
183203 /* searching backwards is broken, so we search forwards, albeit it's less efficient */
184204 int32_t prev_pos = USEARCH_DONE ;
205+ int32_t next_pos = 0 ;
185206 do {
186- char_pos = usearch_next (src, &status);
207+ char_pos = grapheme_usearch_next_from (src, bi, next_pos , &status);
187208 if (char_pos == USEARCH_DONE || char_pos > offset_pos) {
188209 char_pos = prev_pos;
189210 break ;
190211 }
191212 prev_pos = char_pos;
192- int32_t next_pos = ubrk_following (bi, char_pos);
213+ next_pos = ubrk_following (bi, char_pos);
193214 if (next_pos == UBRK_DONE ) {
194215 break ;
195216 }
@@ -198,7 +219,7 @@ int32_t grapheme_strpos_utf16(char *haystack, size_t haystack_len, char *needle,
198219 } while (1 );
199220 }
200221 } else {
201- char_pos = usearch_next (src, &status);
222+ char_pos = grapheme_usearch_next_from (src, bi, offset_pos , &status);
202223 }
203224 STRPOS_CHECK_STATUS (status, " Error looking up string" );
204225 if (char_pos != USEARCH_DONE && ubrk_isBoundary (bi, char_pos)) {
0 commit comments