@@ -92,6 +92,26 @@ void grapheme_substr_ascii(char *str, size_t str_len, int32_t f, int32_t l, char
9292 goto finish; \
9393 }
9494
95+ /* Find the next match that starts at or after "from". When "from" falls inside
96+ * a contraction, such as a Thai prevowel and its consonant, ICU returns the match
97+ * that starts at the contraction, before "from". Search again from each following
98+ * grapheme boundary, so that a match overlapping the skipped one is not missed. */
99+ static int32_t grapheme_usearch_next_from (UStringSearch * src , UBreakIterator * bi , int32_t from , UErrorCode * status )
100+ {
101+ int32_t pos = usearch_next (src , status );
102+ int32_t boundary = from ;
103+
104+ while (U_SUCCESS (* status ) && pos != USEARCH_DONE && pos < from ) {
105+ boundary = ubrk_following (bi , boundary );
106+ if (boundary == UBRK_DONE ) {
107+ return USEARCH_DONE ;
108+ }
109+ usearch_setOffset (src , boundary , status );
110+ pos = usearch_next (src , status );
111+ }
112+
113+ return pos ;
114+ }
95115
96116/* {{{ grapheme_strpos_utf16 - strrpos using utf16*/
97117int32_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 )
@@ -177,14 +197,15 @@ int32_t grapheme_strpos_utf16(char *haystack, size_t haystack_len, char *needle,
177197 } else {
178198 /* searching backwards is broken, so we search forwards, albeit it's less efficient */
179199 int32_t prev_pos = USEARCH_DONE ;
200+ int32_t next_pos = 0 ;
180201 do {
181- char_pos = usearch_next (src , & status );
202+ char_pos = grapheme_usearch_next_from (src , bi , next_pos , & status );
182203 if (char_pos == USEARCH_DONE || char_pos > offset_pos ) {
183204 char_pos = prev_pos ;
184205 break ;
185206 }
186207 prev_pos = char_pos ;
187- int32_t next_pos = ubrk_following (bi , char_pos );
208+ next_pos = ubrk_following (bi , char_pos );
188209 if (next_pos == UBRK_DONE ) {
189210 break ;
190211 }
@@ -193,7 +214,7 @@ int32_t grapheme_strpos_utf16(char *haystack, size_t haystack_len, char *needle,
193214 } while (1 );
194215 }
195216 } else {
196- char_pos = usearch_next (src , & status );
217+ char_pos = grapheme_usearch_next_from (src , bi , offset_pos , & status );
197218 }
198219 STRPOS_CHECK_STATUS (status , "Error looking up string" );
199220 if (char_pos != USEARCH_DONE && ubrk_isBoundary (bi , char_pos )) {
0 commit comments