OSDN Git Service

Updated mksh to ToT as of 12 October 2011.
[android-x86/external-mksh.git] / src / strlcpy.c
1 /*-
2  * Copyright (c) 2006, 2008, 2009
3  *      Thorsten Glaser <tg@mirbsd.org>
4  * 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
21 __RCSID("$MirOS: src/bin/mksh/strlcpy.c,v 1.7 2009/06/10 18:12:50 tg Rel $");
22
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  */
28 size_t
29 strlcpy(char *dst, const char *src, size_t siz)
30 {
31         const char *s = src;
32
33         if (siz == 0)
34                 goto traverse_src;
35
36         /* copy as many chars as will fit */
37         while (--siz && (*dst++ = *s++))
38                 ;
39
40         /* not enough room in dst */
41         if (siz == 0) {
42                 /* safe to NUL-terminate dst since we copied <= siz-1 chars */
43                 *dst = '\0';
44  traverse_src:
45                 /* traverse rest of src */
46                 while (*s++)
47                         ;
48         }
49
50         /* count does not include NUL */
51         return ((size_t)(s - src - 1));
52 }