/src/wget2/libwget/strscpy.c
Line | Count | Source (jump to first uncovered line) |
1 | | /* |
2 | | * Copyright (c) 2017-2024 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 | | */ |
43 | | ssize_t wget_strscpy(char *dst, const char *src, size_t size) |
44 | 105k | { |
45 | 105k | if (unlikely(!dst)) |
46 | 0 | return -1; |
47 | | |
48 | 105k | if (unlikely(!src)) { |
49 | 0 | if (size) { |
50 | 0 | *dst = 0; |
51 | 0 | return 0; |
52 | 0 | } else |
53 | 0 | return -1; |
54 | 0 | } |
55 | | |
56 | 105k | const char *old = src; |
57 | | |
58 | | // Copy as many bytes as will fit |
59 | 105k | if (likely(size)) { |
60 | 521k | while (--size) { |
61 | 521k | if (!(*dst++ = *src++)) |
62 | 105k | return src - old - 1; |
63 | 521k | } |
64 | | |
65 | 194 | *dst = 0; |
66 | 194 | return src - old; |
67 | 105k | } |
68 | | |
69 | 0 | return -1; |
70 | 105k | } |