1 /*
2 * Copyright (c) 2017-2021 Free Software Foundation, Inc.
3 *
4 * This file is part of libwget.
5 *
6 * Libwget is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * Libwget is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with libwget. If not, see <https://www.gnu.org/licenses/>.
18 *
19 */
20
21 #include <config.h>
22
23 #include <stddef.h>
24 #include <string.h>
25
26 #include <wget.h>
27
28 /**
29 * \ingroup libwget-utils
30 * \param[out] dst Output string buffer
31 * \param[in] src Input string
32 * \param[in] size Size of \p dst
33 * \return Number of copied bytes (excluding trailing 0) or -1 when \p src doesn't fit into \p dst
34 *
35 * Copy string \p src into \p dst with overflow checking.
36 *
37 * If either \p dst is %NULL or \p size is 0, the return value is -1 and nothing is written.
38 * If \p src is %NULL and size is 0, the return value is -1.
39 * If \p src is %NULL and size is >0, the return value is 0 and \p dst is an empty string.
40 *
41 * Else the return value is the number of bytes copied to \p dst excluding the terminating 0.
42 */
wget_strscpy(char * dst,const char * src,size_t size)43 ssize_t wget_strscpy(char *dst, const char *src, size_t size)
44 {
45 if (unlikely(!dst))
46 return -1;
47
48 if (unlikely(!src)) {
49 if (size) {
50 *dst = 0;
51 return 0;
52 } else
53 return -1;
54 }
55
56 const char *old = src;
57
58 // Copy as many bytes as will fit
59 if (likely(size)) {
60 while (--size) {
61 if (!(*dst++ = *src++))
62 return src - old - 1;
63 }
64
65 *dst = 0;
66 return src - old;
67 }
68
69 return -1;
70 }
71