xref: /netbsd-src/external/bsd/libpcap/dist/missing/strlcpy.c (revision f73a5f05f638a81353839a8e4bfc90d1189181e7)
1*f73a5f05Schristos /*	$OpenBSD: strlcpy.c,v 1.12 2015/01/15 03:54:12 millert Exp $	*/
24a71e5f3Schristos 
34a71e5f3Schristos /*
44a71e5f3Schristos  * Copyright (c) 1998, 2015 Todd C. Miller <Todd.Miller@courtesan.com>
54a71e5f3Schristos  *
64a71e5f3Schristos  * Permission to use, copy, modify, and distribute this software for any
74a71e5f3Schristos  * purpose with or without fee is hereby granted, provided that the above
84a71e5f3Schristos  * copyright notice and this permission notice appear in all copies.
94a71e5f3Schristos  *
104a71e5f3Schristos  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
114a71e5f3Schristos  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
124a71e5f3Schristos  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
134a71e5f3Schristos  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
144a71e5f3Schristos  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
154a71e5f3Schristos  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
164a71e5f3Schristos  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
174a71e5f3Schristos  */
184a71e5f3Schristos 
194a71e5f3Schristos #include <config.h>
204a71e5f3Schristos 
214a71e5f3Schristos #include <stddef.h>
224a71e5f3Schristos #include <string.h>
234a71e5f3Schristos 
244a71e5f3Schristos #include "portability.h"
254a71e5f3Schristos 
264a71e5f3Schristos /*
274a71e5f3Schristos  * Copy string src to buffer dst of size dsize.  At most dsize-1
284a71e5f3Schristos  * chars will be copied.  Always NUL terminates (unless dsize == 0).
294a71e5f3Schristos  * Returns strlen(src); if retval >= dsize, truncation occurred.
304a71e5f3Schristos  */
314a71e5f3Schristos size_t
32*f73a5f05Schristos pcapint_strlcpy(char * restrict dst, const char * restrict src, size_t dsize)
334a71e5f3Schristos {
344a71e5f3Schristos 	const char *osrc = src;
354a71e5f3Schristos 	size_t nleft = dsize;
364a71e5f3Schristos 
374a71e5f3Schristos 	/* Copy as many bytes as will fit. */
384a71e5f3Schristos 	if (nleft != 0) {
394a71e5f3Schristos 		while (--nleft != 0) {
404a71e5f3Schristos 			if ((*dst++ = *src++) == '\0')
414a71e5f3Schristos 				break;
424a71e5f3Schristos 		}
434a71e5f3Schristos 	}
444a71e5f3Schristos 
454a71e5f3Schristos 	/* Not enough room in dst, add NUL and traverse rest of src. */
464a71e5f3Schristos 	if (nleft == 0) {
474a71e5f3Schristos 		if (dsize != 0)
484a71e5f3Schristos 			*dst = '\0';		/* NUL-terminate dst */
494a71e5f3Schristos 		while (*src++)
504a71e5f3Schristos 			;
514a71e5f3Schristos 	}
524a71e5f3Schristos 
534a71e5f3Schristos 	return(src - osrc - 1);	/* count does not include NUL */
544a71e5f3Schristos }
55