]> eyrie.org Git - kerberos/krb5-strength.git/blob - portable/strlcat.c
Add a basic portability library
[kerberos/krb5-strength.git] / portable / strlcat.c
1 /*
2  * Replacement for a missing strlcat.
3  *
4  * Provides the same functionality as the *BSD function strlcat, originally
5  * developed by Todd Miller and Theo de Raadt.  strlcat works similarly to
6  * strncat, except simpler.  The result is always nul-terminated even if the
7  * source string is longer than the space remaining in the destination string,
8  * and the total space required is returned.  The third argument is the total
9  * space available in the destination buffer, not just the amount of space
10  * remaining.
11  *
12  * Written by Russ Allbery <rra@stanford.edu>
13  * This work is hereby placed in the public domain by its author.
14  */
15
16 #include <config.h>
17 #include <portable/system.h>
18
19 /*
20  * If we're running the test suite, rename strlcat to avoid conflicts with
21  * the system version.
22  */
23 #if TESTING
24 # define strlcat test_strlcat
25 size_t test_strlcat(char *, const char *, size_t);
26 #endif
27
28 size_t
29 strlcat(char *dst, const char *src, size_t size)
30 {
31     size_t used, length, copy;
32
33     used = strlen(dst);
34     length = strlen(src);
35     if (size > 0 && used < size - 1) {
36         copy = (length >= size - used) ? size - used - 1 : length;
37         memcpy(dst + used, src, copy);
38         dst[used + copy] = '\0';
39     }
40     return used + length;
41 }