From: Willy Tarreau Date: Tue, 24 Nov 2026 08:46:37 +0000 (+0000) Subject: MINOR: tools: add memcpy_opt_small() for ultra-small copies X-Git-Url: https://git.kaiwu.me/http/ngx_http_proxy_module.html?a=commitdiff_plain;h=8ee28984452ca81d8727d71b842d08e3d870082f;p=haproxy.git MINOR: tools: add memcpy_opt_small() for ultra-small copies Some parsers need to copy many tiny objects of variable size (e.g. HTTP/1 chunks of a few bytes), for which calling the libc's memcpy() costs much more than the copy itself, because the compiler cannot inline a copy whose size it does not know. memcpy_opt_small() copies sizes from 1 to 32 inline after two to four tests, using at most two possibly overlapping fixed-size copies that the compiler turns into simple loads and stores: one byte then 2 bytes at the end for 1 to 3 bytes, then 4, 8 or 16 bytes at each end for 4 to 7, 8 to 16 and 17 to 32 bytes respectively. Larger sizes fall back to memcpy(). A size of zero is not supported since one byte is always copied. --- diff --git a/include/haproxy/tools.h b/include/haproxy/tools.h index 888bc8be9..bea024e50 100644 --- a/include/haproxy/tools.h +++ b/include/haproxy/tools.h @@ -567,6 +567,47 @@ size_t my_memspn(const void *, size_t, const void *, size_t); */ size_t my_memcspn(const void *, size_t, const void *, size_t); +/* Equivalent of memcpy() optimized for ultra-small copies of 32 bytes or less, + * typically when copying many tiny objects of variable size, for which the + * call to the libc's memcpy() would cost much more than the copy itself. + * Sizes from 1 to 32 are copied inline using at most two possibly overlapping + * fixed-size copies, after two to four tests. A size of zero is not supported + * (one byte is always copied). Larger sizes fall back to memcpy(). + */ +static forceinline void memcpy_opt_small(void *dst, const void *src, size_t len) +{ + char *d = dst; + const char *s = src; + + if (len < 4) { + /* 1..3 bytes */ + d[0] = s[0]; + if (len < 2) + return; + memcpy(d + len - 2, s + len - 2, 2); + } + else if (len <= 32) { + if (len <= 16) { + /* 4..16 bytes */ + if (len < 8) { + memcpy(d, s, 4); + memcpy(d + len - 4, s + len - 4, 4); + } + else { + memcpy(d, s, 8); + memcpy(d + len - 8, s + len - 8, 8); + } + } + else { + /* 17..32 bytes */ + memcpy(d, s, 16); + memcpy(d + len - 16, s + len - 16, 16); + } + } + else + memcpy(d, s, len); +} + /* This function returns the first unused key greater than or equal to in * ID tree . Zero is returned if no place is found. */