strlcpy.c revision 4642e01f
105b261ecSmrg/*
205b261ecSmrg * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
305b261ecSmrg *
405b261ecSmrg * Permission to use, copy, modify, and distribute this software for any
505b261ecSmrg * purpose with or without fee is hereby granted, provided that the above
605b261ecSmrg * copyright notice and this permission notice appear in all copies.
705b261ecSmrg *
805b261ecSmrg * THE SOFTWARE IS PROVIDED "AS IS" AND TODD C. MILLER DISCLAIMS ALL
905b261ecSmrg * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
1005b261ecSmrg * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL TODD C. MILLER BE LIABLE
1105b261ecSmrg * FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
1205b261ecSmrg * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
1305b261ecSmrg * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
1405b261ecSmrg * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
1505b261ecSmrg */
1605b261ecSmrg
1705b261ecSmrg#ifdef HAVE_XORG_CONFIG_H
1805b261ecSmrg#include <xorg-config.h>
1905b261ecSmrg#endif
2005b261ecSmrg
2105b261ecSmrg#include <sys/types.h>
2205b261ecSmrg#include <string.h>
234642e01fSmrg#include "os.h"
2405b261ecSmrg
2505b261ecSmrg/*
2605b261ecSmrg * Copy src to string dst of size siz.  At most siz-1 characters
2705b261ecSmrg * will be copied.  Always NUL terminates (unless siz == 0).
2805b261ecSmrg * Returns strlen(src); if retval >= siz, truncation occurred.
2905b261ecSmrg */
3005b261ecSmrgsize_t
3105b261ecSmrgstrlcpy(char *dst, const char *src, size_t siz)
3205b261ecSmrg{
3305b261ecSmrg	register char *d = dst;
3405b261ecSmrg	register const char *s = src;
3505b261ecSmrg	register size_t n = siz;
3605b261ecSmrg
3705b261ecSmrg	/* Copy as many bytes as will fit */
3805b261ecSmrg	if (n != 0 && --n != 0) {
3905b261ecSmrg		do {
4005b261ecSmrg			if ((*d++ = *s++) == 0)
4105b261ecSmrg				break;
4205b261ecSmrg		} while (--n != 0);
4305b261ecSmrg	}
4405b261ecSmrg
4505b261ecSmrg	/* Not enough room in dst, add NUL and traverse rest of src */
4605b261ecSmrg	if (n == 0) {
4705b261ecSmrg		if (siz != 0)
4805b261ecSmrg			*d = '\0';		/* NUL-terminate dst */
4905b261ecSmrg		while (*s++)
5005b261ecSmrg			;
5105b261ecSmrg	}
5205b261ecSmrg
5305b261ecSmrg	return(s - src - 1);	/* count does not include NUL */
5405b261ecSmrg}
55