1281135Spfg/*	$OpenBSD: strlcpy.c,v 1.12 2015/01/15 03:54:12 millert Exp $	*/
249593Simp
349593Simp/*
4281135Spfg * Copyright (c) 1998, 2015 Todd C. Miller <Todd.Miller@courtesan.com>
549593Simp *
6184059Sdelphij * Permission to use, copy, modify, and distribute this software for any
7184059Sdelphij * purpose with or without fee is hereby granted, provided that the above
8184059Sdelphij * copyright notice and this permission notice appear in all copies.
949593Simp *
10184059Sdelphij * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11184059Sdelphij * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12184059Sdelphij * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13184059Sdelphij * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14184059Sdelphij * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15184059Sdelphij * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16184059Sdelphij * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1749593Simp */
1849593Simp
1986170Sobrien#include <sys/cdefs.h>
2086170Sobrien__FBSDID("$FreeBSD$");
2149593Simp
2249593Simp#include <sys/types.h>
2349593Simp#include <string.h>
2449593Simp
2549593Simp/*
26281135Spfg * Copy string src to buffer dst of size dsize.  At most dsize-1
27281135Spfg * chars will be copied.  Always NUL terminates (unless dsize == 0).
28281135Spfg * Returns strlen(src); if retval >= dsize, truncation occurred.
2949593Simp */
30159644Smaximsize_t
31281135Spfgstrlcpy(char * __restrict dst, const char * __restrict src, size_t dsize)
3249593Simp{
33281135Spfg	const char *osrc = src;
34281135Spfg	size_t nleft = dsize;
3549593Simp
36281135Spfg	/* Copy as many bytes as will fit. */
37281135Spfg	if (nleft != 0) {
38281135Spfg		while (--nleft != 0) {
39281135Spfg			if ((*dst++ = *src++) == '\0')
4049594Simp				break;
41184059Sdelphij		}
4249593Simp	}
4349593Simp
44281135Spfg	/* Not enough room in dst, add NUL and traverse rest of src. */
45281135Spfg	if (nleft == 0) {
46281135Spfg		if (dsize != 0)
47281135Spfg			*dst = '\0';		/* NUL-terminate dst */
48281135Spfg		while (*src++)
4949594Simp			;
5049594Simp	}
5149594Simp
52281135Spfg	return(src - osrc - 1);	/* count does not include NUL */
5349593Simp}
54