Skip to content

Commit 3e982a8

Browse files
authored
standard: Remove redundant code in range() (#20432)
If we use signed integers (which fit the unsigned chars), then we can avoid the extra checks. Also move an exception check to the proper place.
1 parent e97c0dc commit 3e982a8

File tree

1 file changed

+8
-14
lines changed

1 file changed

+8
-14
lines changed

ext/standard/array.c

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -3040,18 +3040,18 @@ PHP_FUNCTION(range)
30403040
if (start_type == IS_STRING || end_type == IS_STRING) {
30413041
php_error_docref(NULL, E_WARNING, "Argument #3 ($step) must be of type int when generating an array"
30423042
" of characters, inputs converted to 0");
3043-
}
3044-
if (UNEXPECTED(EG(exception))) {
3045-
RETURN_THROWS();
3043+
if (UNEXPECTED(EG(exception))) {
3044+
RETURN_THROWS();
3045+
}
30463046
}
30473047
end_type = IS_LONG;
30483048
start_type = IS_LONG;
30493049
goto handle_numeric_inputs;
30503050
}
30513051

3052-
/* Generate array of characters */
3053-
unsigned char low = (unsigned char)Z_STRVAL_P(user_start)[0];
3054-
unsigned char high = (unsigned char)Z_STRVAL_P(user_end)[0];
3052+
/* Generate array of characters, as ints to make bounds checking possible in the loop condition */
3053+
int low = Z_STRVAL_P(user_start)[0];
3054+
int high = Z_STRVAL_P(user_end)[0];
30553055

30563056
/* Decreasing char range */
30573057
if (low > high) {
@@ -3062,12 +3062,9 @@ PHP_FUNCTION(range)
30623062
array_init_size(return_value, (uint32_t)(((low - high) / step) + 1));
30633063
zend_hash_real_init_packed(Z_ARRVAL_P(return_value));
30643064
ZEND_HASH_FILL_PACKED(Z_ARRVAL_P(return_value)) {
3065-
for (; low >= high; low -= (unsigned int)step) {
3065+
for (; low >= high; low -= step) {
30663066
ZEND_HASH_FILL_SET_INTERNED_STR(ZSTR_CHAR(low));
30673067
ZEND_HASH_FILL_NEXT();
3068-
if (((signed int)low - step) < 0) {
3069-
break;
3070-
}
30713068
}
30723069
} ZEND_HASH_FILL_END();
30733070
} else if (high > low) { /* Increasing char range */
@@ -3080,12 +3077,9 @@ PHP_FUNCTION(range)
30803077
array_init_size(return_value, (uint32_t)(((high - low) / step) + 1));
30813078
zend_hash_real_init_packed(Z_ARRVAL_P(return_value));
30823079
ZEND_HASH_FILL_PACKED(Z_ARRVAL_P(return_value)) {
3083-
for (; low <= high; low += (unsigned int)step) {
3080+
for (; low <= high; low += step) {
30843081
ZEND_HASH_FILL_SET_INTERNED_STR(ZSTR_CHAR(low));
30853082
ZEND_HASH_FILL_NEXT();
3086-
if (((signed int)low + step) > 255) {
3087-
break;
3088-
}
30893083
}
30903084
} ZEND_HASH_FILL_END();
30913085
} else {

0 commit comments

Comments
 (0)