blob: ba8581ef68a5c32d0013eba3b247dfce287c5425 [file] [log] [blame]
Geremy Condra03ebf062011-10-12 18:17:24 -07001/*-
Elliott Hughes737fdce2014-08-07 12:59:26 -07002 * Copyright (c) 2006, 2008, 2009, 2013
Elliott Hughesfc0307d2016-02-02 15:26:47 -08003 * mirabilos <m@mirbsd.org>
Geremy Condra03ebf062011-10-12 18:17:24 -07004 * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19#include "sh.h"
20
Elliott Hughesfc0307d2016-02-02 15:26:47 -080021__RCSID("$MirOS: src/bin/mksh/strlcpy.c,v 1.10 2015/11/29 17:05:02 tg Exp $");
Geremy Condra03ebf062011-10-12 18:17:24 -070022
23/*
24 * Copy src to string dst of size siz. At most siz-1 characters
25 * will be copied. Always NUL terminates (unless siz == 0).
26 * Returns strlen(src); if retval >= siz, truncation occurred.
27 */
Elliott Hughes737fdce2014-08-07 12:59:26 -070028#undef strlcpy
Geremy Condra03ebf062011-10-12 18:17:24 -070029size_t
30strlcpy(char *dst, const char *src, size_t siz)
31{
32 const char *s = src;
33
34 if (siz == 0)
35 goto traverse_src;
36
37 /* copy as many chars as will fit */
38 while (--siz && (*dst++ = *s++))
39 ;
40
41 /* not enough room in dst */
42 if (siz == 0) {
43 /* safe to NUL-terminate dst since we copied <= siz-1 chars */
44 *dst = '\0';
45 traverse_src:
46 /* traverse rest of src */
47 while (*s++)
48 ;
49 }
50
51 /* count does not include NUL */
52 return ((size_t)(s - src - 1));
53}