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