Skip to content

Commit b4c3f25

Browse files
committed
Save haystack length, and move out of bound offset check outside a specialized path
1 parent e1935e9 commit b4c3f25

File tree

1 file changed

+13
-10
lines changed

1 file changed

+13
-10
lines changed

ext/mbstring/libmbfl/mbfl/mbfilter.c

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -817,6 +817,7 @@ mbfl_strpos(
817817
int reverse)
818818
{
819819
size_t result;
820+
size_t haystack_length;
820821
mbfl_string _haystack_u8, _needle_u8;
821822
const mbfl_string *haystack_u8, *needle_u8 = NULL;
822823
const unsigned char *u8_tbl;
@@ -855,29 +856,31 @@ mbfl_strpos(
855856
needle_u8 = needle;
856857
}
857858

859+
/* Check if offset is out of bound */
860+
haystack_length = mbfl_strlen(haystack_u8);
861+
if (
862+
(offset > 0 && offset > haystack_length)
863+
|| (offset < 0 && -offset > haystack_length)
864+
) {
865+
result = -16;
866+
goto out;
867+
}
868+
858869
result = (size_t) -1;
859870
if (haystack_u8->len < needle_u8->len) {
860871
goto out;
861872
}
862873

863874
if (needle_u8->len == 0) {
864-
/* Out of bound offset */
865-
if (
866-
(offset > 0 && offset > mbfl_strlen(haystack_u8))
867-
|| (offset < 0 && -offset > mbfl_strlen(haystack_u8))
868-
) {
869-
return -16;
870-
}
871-
872875
if (reverse) {
873876
if (offset < 0) {
874877
result = (size_t) -offset;
875878
} else {
876-
result = mbfl_strlen(haystack_u8) - offset;;
879+
result = haystack_length - offset;;
877880
}
878881
} else {
879882
if (offset < 0) {
880-
result = mbfl_strlen(haystack_u8) + offset;
883+
result = haystack_length + offset;
881884
} else {
882885
result = (size_t) offset;
883886
}

0 commit comments

Comments
 (0)