]> git.proxmox.com Git - mirror_frr.git/blob - lib/strlcpy.c
Merge pull request #13649 from donaldsharp/unlock_the_node_or_else
[mirror_frr.git] / lib / strlcpy.c
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2 /* Copy a null-terminated string to a fixed-size buffer, with length checking.
3 * Copyright (C) 2016 Free Software Foundation, Inc.
4 * This file is part of the GNU C Library.
5 */
6
7 /* adapted for Quagga from glibc patch submission originally from
8 * Florian Weimer <fweimer@redhat.com>, 2016-05-18 */
9
10 #ifdef HAVE_CONFIG_H
11 #include "config.h"
12 #endif
13
14 #include <string.h>
15
16 #ifndef HAVE_STRLCPY
17 #undef strlcpy
18
19 size_t strlcpy(char *__restrict dest,
20 const char *__restrict src, size_t destsize);
21
22 size_t strlcpy(char *__restrict dest,
23 const char *__restrict src, size_t destsize)
24 {
25 size_t src_length = strlen(src);
26
27 if (__builtin_expect(src_length >= destsize, 0)) {
28 if (destsize > 0) {
29 /*
30 * Copy the leading portion of the string. The last
31 * character is subsequently overwritten with the NUL
32 * terminator, but the destination destsize is usually
33 * a multiple of a small power of two, so writing it
34 * twice should be more efficient than copying an odd
35 * number of bytes.
36 */
37 memcpy(dest, src, destsize);
38 dest[destsize - 1] = '\0';
39 }
40 } else
41 /* Copy the string and its terminating NUL character. */
42 memcpy(dest, src, src_length + 1);
43 return src_length;
44 }
45 #endif /* HAVE_STRLCPY */