1*e38b8307SConrad Meyer /* $OpenBSD: strlcpy.c,v 1.12 2015/01/15 03:54:12 millert Exp $ */
2a41df9e3SWarner Losh
3*e38b8307SConrad Meyer /*
4*e38b8307SConrad Meyer * Copyright (c) 1998, 2015 Todd C. Miller <Todd.Miller@courtesan.com>
5a41df9e3SWarner Losh *
6299ff0d7SXin LI * Permission to use, copy, modify, and distribute this software for any
7299ff0d7SXin LI * purpose with or without fee is hereby granted, provided that the above
8299ff0d7SXin LI * copyright notice and this permission notice appear in all copies.
9a41df9e3SWarner Losh *
10299ff0d7SXin LI * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11299ff0d7SXin LI * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12299ff0d7SXin LI * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13299ff0d7SXin LI * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14299ff0d7SXin LI * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15299ff0d7SXin LI * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16299ff0d7SXin LI * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17a41df9e3SWarner Losh */
18a41df9e3SWarner Losh
19a41df9e3SWarner Losh #include <sys/types.h>
20105d189bSPeter Wemm #include <sys/libkern.h>
21a41df9e3SWarner Losh
22a41df9e3SWarner Losh /*
23*e38b8307SConrad Meyer * Copy string src to buffer dst of size dsize. At most dsize-1
24*e38b8307SConrad Meyer * chars will be copied. Always NUL terminates (unless dsize == 0).
25*e38b8307SConrad Meyer * Returns strlen(src); if retval >= dsize, truncation occurred.
26a41df9e3SWarner Losh */
27299ff0d7SXin LI size_t
strlcpy(char * __restrict dst,const char * __restrict src,size_t dsize)28*e38b8307SConrad Meyer strlcpy(char * __restrict dst, const char * __restrict src, size_t dsize)
29a41df9e3SWarner Losh {
30*e38b8307SConrad Meyer const char *osrc = src;
31*e38b8307SConrad Meyer size_t nleft = dsize;
32a41df9e3SWarner Losh
33*e38b8307SConrad Meyer /* Copy as many bytes as will fit. */
34*e38b8307SConrad Meyer if (nleft != 0) {
35*e38b8307SConrad Meyer while (--nleft != 0) {
36*e38b8307SConrad Meyer if ((*dst++ = *src++) == '\0')
37d64292d2SWarner Losh break;
38299ff0d7SXin LI }
39a41df9e3SWarner Losh }
40a41df9e3SWarner Losh
41*e38b8307SConrad Meyer /* Not enough room in dst, add NUL and traverse rest of src. */
42*e38b8307SConrad Meyer if (nleft == 0) {
43*e38b8307SConrad Meyer if (dsize != 0)
44*e38b8307SConrad Meyer *dst = '\0'; /* NUL-terminate dst */
45*e38b8307SConrad Meyer while (*src++)
46d64292d2SWarner Losh ;
47d64292d2SWarner Losh }
48d64292d2SWarner Losh
49*e38b8307SConrad Meyer return(src - osrc - 1); /* count does not include NUL */
50a41df9e3SWarner Losh }
51