xref: /freebsd/sys/contrib/openzfs/lib/libspl/strlcat.c (revision 61145dc2b94f12f6a47344fb9aac702321880e43)
1 // SPDX-License-Identifier: CDDL-1.0
2 /*
3  * CDDL HEADER START
4  *
5  * The contents of this file are subject to the terms of the
6  * Common Development and Distribution License (the "License").
7  * You may not use this file except in compliance with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or https://opensource.org/licenses/CDDL-1.0.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 
23 /*
24  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
25  * Use is subject to license terms.
26  */
27 #ifndef HAVE_STRLCAT
28 
29 #include <string.h>
30 #include <sys/types.h>
31 
32 /*
33  * Appends src to the dstsize buffer at dst. The append will never
34  * overflow the destination buffer and the buffer will always be null
35  * terminated. Never reference beyond &dst[dstsize-1] when computing
36  * the length of the pre-existing string.
37  */
38 
39 size_t
strlcat(char * dst,const char * src,size_t dstsize)40 strlcat(char *dst, const char *src, size_t dstsize)
41 {
42 	char *df = dst;
43 	size_t left = dstsize;
44 	size_t l1;
45 	size_t l2 = strlen(src);
46 	size_t copied;
47 
48 	while (left-- != 0 && *df != '\0')
49 		df++;
50 	l1 = df - dst;
51 	if (dstsize == l1)
52 		return (l1 + l2);
53 
54 	copied = l1 + l2 >= dstsize ? dstsize - l1 - 1 : l2;
55 	(void) memcpy(dst + l1, src, copied);
56 	dst[l1+copied] = '\0';
57 
58 	return (l1 + l2);
59 }
60 
61 #endif
62