Blame


1 6303eedc 2020-10-24 stsp /* $OpenBSD: strlcpy.c,v 1.16 2019/01/25 00:19:25 millert Exp $ */
2 6303eedc 2020-10-24 stsp
3 6303eedc 2020-10-24 stsp /*
4 6303eedc 2020-10-24 stsp * Copyright (c) 1998, 2015 Todd C. Miller <millert@openbsd.org>
5 6303eedc 2020-10-24 stsp *
6 6303eedc 2020-10-24 stsp * Permission to use, copy, modify, and distribute this software for any
7 6303eedc 2020-10-24 stsp * purpose with or without fee is hereby granted, provided that the above
8 6303eedc 2020-10-24 stsp * copyright notice and this permission notice appear in all copies.
9 6303eedc 2020-10-24 stsp *
10 6303eedc 2020-10-24 stsp * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 6303eedc 2020-10-24 stsp * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 6303eedc 2020-10-24 stsp * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 6303eedc 2020-10-24 stsp * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 6303eedc 2020-10-24 stsp * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 6303eedc 2020-10-24 stsp * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 6303eedc 2020-10-24 stsp * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 6303eedc 2020-10-24 stsp */
18 6303eedc 2020-10-24 stsp
19 6303eedc 2020-10-24 stsp #include <sys/types.h>
20 6303eedc 2020-10-24 stsp #include <string.h>
21 6303eedc 2020-10-24 stsp
22 6303eedc 2020-10-24 stsp /*
23 6303eedc 2020-10-24 stsp * Copy string src to buffer dst of size dsize. At most dsize-1
24 6303eedc 2020-10-24 stsp * chars will be copied. Always NUL terminates (unless dsize == 0).
25 6303eedc 2020-10-24 stsp * Returns strlen(src); if retval >= dsize, truncation occurred.
26 6303eedc 2020-10-24 stsp */
27 6303eedc 2020-10-24 stsp size_t
28 6303eedc 2020-10-24 stsp strlcpy(char *dst, const char *src, size_t dsize)
29 6303eedc 2020-10-24 stsp {
30 6303eedc 2020-10-24 stsp const char *osrc = src;
31 6303eedc 2020-10-24 stsp size_t nleft = dsize;
32 6303eedc 2020-10-24 stsp
33 6303eedc 2020-10-24 stsp /* Copy as many bytes as will fit. */
34 6303eedc 2020-10-24 stsp if (nleft != 0) {
35 6303eedc 2020-10-24 stsp while (--nleft != 0) {
36 6303eedc 2020-10-24 stsp if ((*dst++ = *src++) == '\0')
37 6303eedc 2020-10-24 stsp break;
38 6303eedc 2020-10-24 stsp }
39 6303eedc 2020-10-24 stsp }
40 6303eedc 2020-10-24 stsp
41 6303eedc 2020-10-24 stsp /* Not enough room in dst, add NUL and traverse rest of src. */
42 6303eedc 2020-10-24 stsp if (nleft == 0) {
43 6303eedc 2020-10-24 stsp if (dsize != 0)
44 6303eedc 2020-10-24 stsp *dst = '\0'; /* NUL-terminate dst */
45 6303eedc 2020-10-24 stsp while (*src++)
46 6303eedc 2020-10-24 stsp ;
47 6303eedc 2020-10-24 stsp }
48 6303eedc 2020-10-24 stsp
49 6303eedc 2020-10-24 stsp return(src - osrc - 1); /* count does not include NUL */
50 6303eedc 2020-10-24 stsp }