1236769Sobrien/*	$NetBSD: strlcpy.c,v 1.3 2007/06/04 18:19:27 christos Exp $	*/
2236769Sobrien/*	$OpenBSD: strlcpy.c,v 1.7 2003/04/12 21:56:39 millert Exp $	*/
3236769Sobrien
4236769Sobrien/*
5236769Sobrien * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
6236769Sobrien *
7236769Sobrien * Permission to use, copy, modify, and distribute this software for any
8236769Sobrien * purpose with or without fee is hereby granted, provided that the above
9236769Sobrien * copyright notice and this permission notice appear in all copies.
10236769Sobrien *
11236769Sobrien * THE SOFTWARE IS PROVIDED "AS IS" AND TODD C. MILLER DISCLAIMS ALL
12236769Sobrien * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
13236769Sobrien * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL TODD C. MILLER BE LIABLE
14236769Sobrien * FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15236769Sobrien * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
16236769Sobrien * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
17236769Sobrien * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18236769Sobrien */
19236769Sobrien
20236769Sobrien#ifdef HAVE_CONFIG_H
21236769Sobrien# include <config.h>
22236769Sobrien#endif
23236769Sobrien#ifndef HAVE_STRLCPY
24236769Sobrien
25236769Sobrien#include <sys/cdefs.h>
26236769Sobrien
27236769Sobrien#include <sys/types.h>
28236769Sobrien#include <string.h>
29236769Sobrien
30236769Sobrien/*
31236769Sobrien * Copy src to string dst of size siz.  At most siz-1 characters
32236769Sobrien * will be copied.  Always NUL terminates (unless siz == 0).
33236769Sobrien * Returns strlen(src); if retval >= siz, truncation occurred.
34236769Sobrien */
35236769Sobriensize_t
36236769Sobrienstrlcpy(char *dst, const char *src, size_t siz)
37236769Sobrien{
38236769Sobrien	char *d = dst;
39236769Sobrien	const char *s = src;
40236769Sobrien	size_t n = siz;
41236769Sobrien
42236769Sobrien	if (!dst || !src)
43236769Sobrien		return 0;
44236769Sobrien
45236769Sobrien	/* Copy as many bytes as will fit */
46236769Sobrien	if (n != 0 && --n != 0) {
47236769Sobrien		do {
48236769Sobrien			if ((*d++ = *s++) == 0)
49236769Sobrien				break;
50236769Sobrien		} while (--n != 0);
51236769Sobrien	}
52236769Sobrien
53236769Sobrien	/* Not enough room in dst, add NUL and traverse rest of src */
54236769Sobrien	if (n == 0) {
55236769Sobrien		if (siz != 0)
56236769Sobrien			*d = '\0';		/* NUL-terminate dst */
57236769Sobrien		while (*s++)
58236769Sobrien			;
59236769Sobrien	}
60236769Sobrien
61236769Sobrien	return(s - src - 1);	/* count does not include NUL */
62236769Sobrien}
63236769Sobrien#endif
64