]> git.kaiwu.me - haproxy.git/commitdiff
MINOR: tools: add memcpy_opt_small() for ultra-small copies
authorWilly Tarreau <w@1wt.eu>
Tue, 24 Nov 2026 08:46:37 +0000 (08:46 +0000)
committerWilly Tarreau <w@1wt.eu>
Tue, 24 Nov 2026 09:50:37 +0000 (10:50 +0100)
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.

include/haproxy/tools.h

index 888bc8be9dbe59a76dcf23e134861f3930d3e9eb..bea024e50eff8e5193ff4b330a66faf53ab53ded 100644 (file)
@@ -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 <key> in
  * ID tree <root>. Zero is returned if no place is found.
  */