]> git.proxmox.com Git - mirror_frr.git/blame - lib/strlcpy.c
Merge pull request #13649 from donaldsharp/unlock_the_node_or_else
[mirror_frr.git] / lib / strlcpy.c
CommitLineData
47a3a827 1// SPDX-License-Identifier: LGPL-2.1-or-later
c5d9d3bb 2/* Copy a null-terminated string to a fixed-size buffer, with length checking.
896014f4
DL
3 * Copyright (C) 2016 Free Software Foundation, Inc.
4 * This file is part of the GNU C Library.
896014f4 5 */
c5d9d3bb
DL
6
7/* adapted for Quagga from glibc patch submission originally from
8 * Florian Weimer <fweimer@redhat.com>, 2016-05-18 */
9
b45ac5f5 10#ifdef HAVE_CONFIG_H
c5d9d3bb 11#include "config.h"
b45ac5f5
DL
12#endif
13
14#include <string.h>
c5d9d3bb
DL
15
16#ifndef HAVE_STRLCPY
17#undef strlcpy
18
c9a164df
DS
19size_t strlcpy(char *__restrict dest,
20 const char *__restrict src, size_t destsize);
c5d9d3bb 21
c9a164df
DS
22size_t strlcpy(char *__restrict dest,
23 const char *__restrict src, size_t destsize)
c5d9d3bb 24{
d62a17ae 25 size_t src_length = strlen(src);
c5d9d3bb 26
c9a164df
DS
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';
d62a17ae 39 }
40 } else
41 /* Copy the string and its terminating NUL character. */
42 memcpy(dest, src, src_length + 1);
43 return src_length;
c5d9d3bb
DL
44}
45#endif /* HAVE_STRLCPY */