1 /*
2 FUNCTION
3 	<<wcslcpy>>---copy a wide-character string to specified length
4 
5 SYNOPSIS
6 	#include <wchar.h>
7 	size_t wcslcpy(wchar_t *<[dst]>, const wchar_t *<[src]>, size_t <[siz]>);
8 
9 DESCRIPTION
10 	<<wcslcpy>> copies wide characters from <[src]> to <[dst]>
11 	such that up to <[siz]> - 1 characters are copied.  A
12 	terminating null is appended to the result, unless <[siz]>
13 	is zero.
14 
15 RETURNS
16 	<<wcslcpy>> returns the number of wide characters in <[src]>,
17 	not including the terminating null wide character.  If the
18 	return value is greater than or equal to <[siz]>, then
19 	not all wide characters were copied from <[src]> and truncation
20 	occurred.
21 
22 PORTABILITY
23 No supporting OS subroutines are required.
24 */
25 
26 /*      $OpenBSD: wcslcpy.c,v 1.8 2019/01/25 00:19:25 millert Exp $     */
27 
28 /*
29  * Copyright (c) 1998, 2015 Todd C. Miller <millert@openbsd.org>
30  *
31  * Permission to use, copy, modify, and distribute this software for any
32  * purpose with or without fee is hereby granted, provided that the above
33  * copyright notice and this permission notice appear in all copies.
34  *
35  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
36  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
37  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
38  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
39  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
40  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
41  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
42  */
43 
44 #include <sys/types.h>
45 #include <wchar.h>
46 
47 /*
48  * Copy string src to buffer dst of size dsize.  At most dsize-1
49  * chars will be copied.  Always NUL terminates (unless dsize == 0).
50  * Returns wcslen(src); if retval >= dsize, truncation occurred.
51  */
52 size_t
wcslcpy(wchar_t * dst,const wchar_t * src,size_t dsize)53 wcslcpy (wchar_t *dst,
54         const wchar_t *src,
55         size_t dsize)
56 {
57         const wchar_t *osrc = src;
58         size_t nleft = dsize;
59 
60         /* Copy as many bytes as will fit. */
61         if (nleft != 0) {
62                 while (--nleft != 0) {
63                         if ((*dst++ = *src++) == L'\0')
64                                 break;
65                 }
66         }
67 
68         /* Not enough room in dst, add NUL and traverse rest of src. */
69         if (nleft == 0) {
70                 if (dsize != 0)
71                         *dst = L'\0';           /* NUL-terminate dst */
72                 while (*src++)
73                         ;
74         }
75 
76         return(src - osrc - 1); /* count does not include NUL */
77 }
78