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