MINOR: chunk: implement chunk_strncpy() to copy partial strings

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.
This commit is contained in:
Willy Tarreau 2020-02-14 11:31:41 +01:00
parent 36f586b694
commit d4ad669051
1 changed files with 20 additions and 0 deletions

View 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.
*/