Line data Source code
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 560 : size_t strlcpy(char *__restrict dest,
23 : const char *__restrict src, size_t destsize)
24 : {
25 560 : size_t src_length = strlen(src);
26 :
27 560 : if (__builtin_expect(src_length >= destsize, 0)) {
28 0 : 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 0 : memcpy(dest, src, destsize);
38 0 : dest[destsize - 1] = '\0';
39 : }
40 : } else
41 : /* Copy the string and its terminating NUL character. */
42 560 : memcpy(dest, src, src_length + 1);
43 560 : return src_length;
44 : }
45 : #endif /* HAVE_STRLCPY */
|