Skip to content

Commit 6c015ae

Browse files
authored
mbstring count_demerits in reverse order (#11493)
This way we can avoid moving candidates that would be eliminated after.
1 parent 21aaf33 commit 6c015ae

File tree

1 file changed

+5
-6
lines changed

1 file changed

+5
-6
lines changed

ext/mbstring/mbstring.c

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3068,8 +3068,8 @@ static size_t count_demerits(struct candidate *array, size_t length, bool strict
30683068
unsigned int finished = 0; /* For how many candidate encodings have we processed all the input? */
30693069

30703070
while ((strict || length > 1) && finished < length) {
3071-
for (size_t i = 0; i < length; i++) {
3072-
try_next_encoding:
3071+
/* Iterate in reverse order to avoid moving candidates that can be eliminated. */
3072+
for (size_t i = length - 1; i != (size_t)-1; i--) {
30733073
/* Do we still have more input to process for this candidate encoding? */
30743074
if (array[i].in_len) {
30753075
const mbfl_encoding *enc = array[i].enc;
@@ -3083,11 +3083,10 @@ static size_t count_demerits(struct candidate *array, size_t length, bool strict
30833083
if (strict) {
30843084
/* This candidate encoding is not valid, eliminate it from consideration */
30853085
length--;
3086-
if (i == length) {
3086+
if (i < length) {
30873087
/* The eliminated candidate was the last valid one in the list */
3088-
goto next_iteration;
3088+
memmove(&array[i], &array[i+1], (length - i) * sizeof(struct candidate));
30893089
}
3090-
memmove(&array[i], &array[i+1], (length - i) * sizeof(struct candidate));
30913090
goto try_next_encoding;
30923091
} else {
30933092
array[i].demerits += 1000;
@@ -3100,8 +3099,8 @@ static size_t count_demerits(struct candidate *array, size_t length, bool strict
31003099
finished++;
31013100
}
31023101
}
3102+
try_next_encoding:;
31033103
}
3104-
next_iteration: ;
31053104
}
31063105

31073106
for (size_t i = 0; i < length; i++) {

0 commit comments

Comments
 (0)