[php-src] PR #21607: Zend: Introduce inline helpers for raw C-string concatenation
| From: | LamentXU123 | Date: | Thu, 02 Apr 2026 13:53:39 +0000 |
| Subject: | [php-src] PR #21607: Zend: Introduce inline helpers for raw C-string concatenation | ||
| Groups: | php.git-pulls | ||
| Request: | Send a blank email to git-pulls+get-35474@lists.php.net to get a copy of this message | ||
Pull Request: https://github.com/php/php-src/pull/21607
Author: LamentXU123
This PR introduces three new
zend_always_inline helpers to
Zend/zend_string.h for concatenating raw C strings (char *):
- zend_str_append_char_to_raw
- zend_str_concat_to_raw
- zend_str_concat3_to_raw
Now, several places in the codebase has manual emalloc + memcpy +
\0 boilerplate to generate temporary char *. This manual approach is
verbose, and harder to read. In some cases when we actually need a zend_string instead
of char *, we already has some refactors (https://github.com/php/php-src/pull/21564 and
https://github.com/php/php-src/pull/21567)
by using zend_string_concat* API, but when it comes to char *, the API
forces a 24-byte struct allocation, which is immediately discarded, and will unnecessarily lower
performance. In order to solve this, I think we can introduce three APIs focusing on dealing with
chars * refactoring.
Below are some examples:
**Appending a single character (e.g., in
[ext/pdo_pgsql/pgsql_driver.c](https://github.com/php/php-src/pull/21597#issuecomment-4176279902))**
Before:
```c
char *zquery = emalloc(ZSTR_LEN(tmp) + 2);
memcpy(zquery, ZSTR_VAL(tmp), ZSTR_LEN(tmp));
zquery[ZSTR_LEN(tmp)] = '\n';
zquery[ZSTR_LEN(tmp) + 1] = '\0';
```
After:
```
char *zquery = zend_str_append_char_to_raw(ZSTR_VAL(tmp), ZSTR_LEN(tmp), '\n');
```
**Concatenating 3 strings (e.g., [php_fsockopen_format_host_port in
ext/standard/fsock.c](https://github.com/php/php-src/blob/f4a2e339e331ca5758722b50c20140bd0bc943f0/ext/standard/fsock.c#L26-L46))**
Before:
```c
char *result = emalloc(total_len + 1);
if (prefix_len > 0) {
memcpy(result, prefix, prefix_len);
}
memcpy(result + prefix_len, host, host_len);
memcpy(result + prefix_len + host_len, portbuf, portlen);
result[total_len] = '\0';
*message = result;
```
After:
```
*message = zend_str_concat3_to_raw(prefix, prefix_len, host, host_len, portbuf, portlen);
```