1242507Sdelphij/* $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 * 6242507Sdelphij * Permission to use, copy, modify, and distribute this software for any 7242507Sdelphij * purpose with or without fee is hereby granted, provided that the above 8242507Sdelphij * copyright notice and this permission notice appear in all copies. 949593Simp * 10242507Sdelphij * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 11242507Sdelphij * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 12242507Sdelphij * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 13242507Sdelphij * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 14242507Sdelphij * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 15242507Sdelphij * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 16242507Sdelphij * 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 */ 30242507Sdelphijsize_t 31242507Sdelphijstrlcpy(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 */ 38242507Sdelphij if (n != 0) { 39242507Sdelphij while (--n != 0) { 40242507Sdelphij if ((*d++ = *s++) == '\0') 4149594Simp break; 42242507Sdelphij } 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