Skip to content

Commit

Permalink
Optimize Redis\Server::format(), allowed to use number as key in a map
Browse files Browse the repository at this point in the history
  • Loading branch information
matyhtf committed Nov 18, 2024
1 parent 7ce419c commit 85d53fe
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 16 deletions.
29 changes: 15 additions & 14 deletions ext-src/swoole_redis_server.cc
Original file line number Diff line number Diff line change
Expand Up @@ -320,9 +320,10 @@ static bool redis_response_format(String *buf, zend_long type, zval *value) {
SW_STRING_FORMAT(buf, "*%d\r\n", zend_hash_num_elements(Z_ARRVAL_P(value)));

zval *item;
SW_HASHTABLE_FOREACH_START(Z_ARRVAL_P(value), item)
redis_response_format_array_item(buf, item);
SW_HASHTABLE_FOREACH_END();
ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(value), item) {
redis_response_format_array_item(buf, item);
}
ZEND_HASH_FOREACH_END();
} else if (type == Redis::REPLY_MAP) {
if (!value) {
goto _no_value;
Expand All @@ -332,19 +333,19 @@ static bool redis_response_format(String *buf, zend_long type, zval *value) {
}
SW_STRING_FORMAT(buf, "*%d\r\n", 2 * zend_hash_num_elements(Z_ARRVAL_P(value)));

char *key;
uint32_t keylen;
int keytype;
zend_string *key;
zend_ulong num_key;
zval *item;

SW_HASHTABLE_FOREACH_START2(Z_ARRVAL_P(value), key, keylen, keytype, item)
if (key == nullptr || keylen == 0) {
continue;
ZEND_HASH_FOREACH_KEY_VAL(Z_ARRVAL_P(value), num_key, key, item) {
if (key) {
SW_STRING_FORMAT(buf, "$%zu\r\n%.*s\r\n", ZSTR_LEN(key), (int) ZSTR_LEN(key), ZSTR_VAL(key));
} else {
std::string _key = std::to_string(num_key);
SW_STRING_FORMAT(buf, "$%zu\r\n%.*s\r\n", _key.length(), (int) _key.length(), _key.c_str());
}
redis_response_format_array_item(buf, item);
}
SW_STRING_FORMAT(buf, "$%d\r\n%.*s\r\n", keylen, keylen, key);
redis_response_format_array_item(buf, item);
(void) keytype;
SW_HASHTABLE_FOREACH_END();
ZEND_HASH_FOREACH_END();
} else {
php_swoole_error(E_WARNING, "Unknown type[%d]", (int) type);
return false;
Expand Down
8 changes: 6 additions & 2 deletions tests/swoole_redis_server/format.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ echo Server::format(Server::STATUS, "SUCCESS");
echo Server::format(Server::INT, 1000);
echo Server::format(Server::STRING, "hello swoole");
echo Server::format(Server::SET, ["php", "is", "best"]);
echo Server::format(Server::MAP, ["php" => '99', "java" => '88', "c++" => '666']);
echo Server::format(Server::MAP, ["php" => '99', "java" => '88', "c++" => '666', 9999 => 'hello']);
?>
--EXPECT--
-ERR
Expand All @@ -32,7 +32,7 @@ $2
is
$4
best
*6
*8
$3
php
$2
Expand All @@ -45,3 +45,7 @@ $3
c++
$3
666
$4
9999
$5
hello

0 comments on commit 85d53fe

Please sign in to comment.