1243811Sdelphij/* $OpenBSD: strlcpy.c,v 1.11 2006/05/05 15:27:38 millert Exp $ */ 249593Simp 3139815Simp/*- 449593Simp * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com> 549593Simp * 6243811Sdelphij * Permission to use, copy, modify, and distribute this software for any 7243811Sdelphij * purpose with or without fee is hereby granted, provided that the above 8243811Sdelphij * copyright notice and this permission notice appear in all copies. 949593Simp * 10243811Sdelphij * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 11243811Sdelphij * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 12243811Sdelphij * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 13243811Sdelphij * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 14243811Sdelphij * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 15243811Sdelphij * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 16243811Sdelphij * 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> 23103000Speter#include <sys/libkern.h> 2449593Simp 2549593Simp/* 2649593Simp * Copy src to string dst of size siz. At most siz-1 characters 2749593Simp * will be copied. Always NUL terminates (unless siz == 0). 2849593Simp * Returns strlen(src); if retval >= siz, truncation occurred. 2949593Simp */ 30243811Sdelphijsize_t 31243811Sdelphijstrlcpy(char * __restrict dst, const char * __restrict src, size_t siz) 3249593Simp{ 3392889Sobrien char *d = dst; 3492889Sobrien const char *s = src; 3592889Sobrien size_t n = siz; 3649593Simp 3749594Simp /* Copy as many bytes as will fit */ 38243811Sdelphij if (n != 0) { 39243811Sdelphij while (--n != 0) { 40243811Sdelphij if ((*d++ = *s++) == '\0') 4149594Simp break; 42243811Sdelphij } 4349593Simp } 4449593Simp 4549594Simp /* Not enough room in dst, add NUL and traverse rest of src */ 4649594Simp if (n == 0) { 4749594Simp if (siz != 0) 4849594Simp *d = '\0'; /* NUL-terminate dst */ 4949594Simp while (*s++) 5049594Simp ; 5149594Simp } 5249594Simp 5349594Simp return(s - src - 1); /* count does not include NUL */ 5449593Simp} 55