]> git.ipfire.org Git - thirdparty/haproxy.git/commitdiff
MINOR: chunk: implement chunk_strncpy() to copy partial strings
authorWilly Tarreau <w@1wt.eu>
Fri, 14 Feb 2020 10:31:41 +0000 (11:31 +0100)
committerWilly Tarreau <w@1wt.eu>
Fri, 14 Feb 2020 18:02:06 +0000 (19:02 +0100)
This does like chunk_strcpy() except that the maximum string length may
be limited by the caller. A trailing zero is always appended. This is
particularly handy to extract portions of strings to put into the trash
for use with libc functions requiring a nul-terminated string.

include/common/chunk.h

index e44feea51647c169b9b59284e722b712ac5c8e1d..a061a344284955a0769d721d6e8c4cff2e9dd101 100644 (file)
@@ -176,6 +176,26 @@ static inline int chunk_strcpy(struct buffer *chk, const char *str)
        return 1;
 }
 
+/* copies at most <max> chars from str into <chk> followed by a trailing zero.
+ * Returns 0 in case of failure.
+ */
+static inline int chunk_strncpy(struct buffer *chk, const char *str, size_t max)
+{
+       size_t len;
+
+       len = strlen(str);
+       if (len > max)
+               len = max;
+
+       if (unlikely(len >= chk->size))
+               return 0;
+
+       memcpy(chk->area, str, len);
+       chk->area[len] = 0;
+       chk->data = len;
+       return 1;
+}
+
 /* appends str after <chk> followed by a trailing zero. Returns 0 in
  * case of failure.
  */