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