/src/sudo/lib/util/strlcat.c
Line | Count | Source |
1 | | /* $OpenBSD: strlcat.c,v 1.15 2015/03/02 21:41:08 millert Exp $ */ |
2 | | |
3 | | /* |
4 | | * SPDX-License-Identifier: ISC |
5 | | * |
6 | | * Copyright (c) 1998, 2003-2005, 2010-2011, 2013-2015 |
7 | | * Todd C. Miller <Todd.Miller@sudo.ws> |
8 | | * |
9 | | * Permission to use, copy, modify, and distribute this software for any |
10 | | * purpose with or without fee is hereby granted, provided that the above |
11 | | * copyright notice and this permission notice appear in all copies. |
12 | | * |
13 | | * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES |
14 | | * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |
15 | | * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR |
16 | | * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |
17 | | * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |
18 | | * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF |
19 | | * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
20 | | */ |
21 | | |
22 | | #include <config.h> |
23 | | |
24 | | #ifndef HAVE_STRLCAT |
25 | | |
26 | | #include <string.h> |
27 | | |
28 | | #include <sudo_compat.h> |
29 | | |
30 | | /* |
31 | | * Appends src to string dst of size dsize (unlike strncat, dsize is the |
32 | | * full size of dst, not space left). At most dsize-1 characters |
33 | | * will be copied. Always NUL terminates (unless dsize <= strlen(dst)). |
34 | | * Returns strlen(src) + MIN(dsize, strlen(initial dst)). |
35 | | * If retval >= dsize, truncation occurred. |
36 | | */ |
37 | | size_t |
38 | | sudo_strlcat(char * restrict dst, const char * restrict src, size_t dsize) |
39 | 457k | { |
40 | 457k | const char *odst = dst; |
41 | 457k | const char *osrc = src; |
42 | 457k | size_t n = dsize; |
43 | 457k | size_t dlen; |
44 | | |
45 | | /* Find the end of dst and adjust bytes left but don't go past end. */ |
46 | 4.03M | while (n-- != 0 && *dst != '\0') |
47 | 3.57M | dst++; |
48 | 457k | dlen = (size_t)(dst - odst); |
49 | 457k | n = dsize - dlen; |
50 | | |
51 | 457k | if (n-- == 0) |
52 | 0 | return(dlen + strlen(src)); |
53 | 88.6M | while (*src != '\0') { |
54 | 88.1M | if (n != 0) { |
55 | 88.1M | *dst++ = *src; |
56 | 88.1M | n--; |
57 | 88.1M | } |
58 | 88.1M | src++; |
59 | 88.1M | } |
60 | 457k | *dst = '\0'; |
61 | | |
62 | 457k | return(dlen + (size_t)(src - osrc)); /* count does not include NUL */ |
63 | 457k | } |
64 | | #endif /* HAVE_STRLCAT */ |