remove unnecessary stddef include
[single-header-libcext.git] / strlcat.h
1 /*
2 * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
16
17 /* https://git.datadissipation.net */
18 #ifndef STRLCAT_H_
19 #define STRLCAT_H_ 1
20
21 #ifdef STRLCAT_INCLUDE_LIBC
22 #include <stdio.h>
23 #include <string.h>
24 #endif /* !STRLCAT_INCLUDE_LIBC */
25
26 #ifndef HAVE_STRLCAT
27 #define HAVE_STRLCAT 1
28 #define strlcat i_strlcat_
29 #define strlcpy i_strlcpy_
30 size_t i_strlcat_(char *dst, const char *src, size_t siz);
31 size_t i_strlcpy_(char *dst, const char *src, size_t siz);
32 #endif /* !HAVE_STRLCAT */
33
34 #ifdef STRLCAT_IMPLEMENTATION
35 /*
36 * Appends src to string dst of size siz (unlike strncat, siz is the
37 * full size of dst, not space left). At most siz-1 characters
38 * will be copied. Always NUL terminates (unless siz <= strlen(dst)).
39 * Returns strlen(src) + MIN(siz, strlen(initial dst)).
40 * If retval >= siz, truncation occurred.
41 */
42 size_t
43 i_strlcat_(char *dst, const char *src, size_t siz)
44 {
45 char *d = dst;
46 const char *s = src;
47 size_t n = siz;
48 size_t dlen;
49 /* Find the end of dst and adjust bytes left but don't go past end */
50 while (n-- != 0 && *d != '\0')
51 d++;
52 dlen = d - dst;
53 n = siz - dlen;
54 if (n == 0)
55 return (dlen + strlen(s));
56 while (*s != '\0') {
57 if (n != 1) {
58 *d++ = *s;
59 n--;
60 }
61 s++;
62 }
63 *d = '\0';
64 return (dlen + (s - src)); /* count does not include NUL */
65 }
66
67 /*
68 * Copy src to string dst of size siz. At most siz-1 characters
69 * will be copied. Always NUL terminates (unless siz == 0).
70 * Returns strlen(src); if retval >= siz, truncation occurred.
71 */
72 size_t
73 i_strlcpy_(char *dst, const char *src, size_t siz)
74 {
75 char *d = dst;
76 const char *s = src;
77 size_t n = siz;
78 /* Copy as many bytes as will fit */
79 if (n != 0) {
80 while (--n != 0) {
81 if ((*d++ = *s++) == '\0')
82 break;
83 }
84 }
85 /* Not enough room in dst, add NUL and traverse rest of src */
86 if (n == 0) {
87 if (siz != 0)
88 *d = '\0'; /* NUL-terminate dst */
89 while (*s++)
90 ;
91 }
92 return(s - src - 1); /* count does not include NUL */
93 }
94 #endif /* STRLCAT_IMPLEMENTATION */
95 #endif /* !STRLCAT_H_ */