]> git.proxmox.com Git - mirror_frr.git/blob - lib/strlcpy.c
Merge remote-tracking branch 'origin/stable/3.0'
[mirror_frr.git] / lib / strlcpy.c
1 /* Copy a null-terminated string to a fixed-size buffer, with length checking.
2 * Copyright (C) 2016 Free Software Foundation, Inc.
3 * This file is part of the GNU C Library.
4 *
5 * The GNU C Library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * The GNU C Library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with the GNU C Library; if not, see
17 * <http://www.gnu.org/licenses/>.
18 */
19
20 /* adapted for Quagga from glibc patch submission originally from
21 * Florian Weimer <fweimer@redhat.com>, 2016-05-18 */
22
23 #include <string.h>
24
25 #include "config.h"
26
27 #ifndef HAVE_STRLCPY
28 #undef strlcpy
29
30 size_t
31 strlcpy (char *__restrict dest, const char *__restrict src, size_t size);
32
33 size_t
34 strlcpy (char *__restrict dest, const char *__restrict src, size_t size)
35 {
36 size_t src_length = strlen (src);
37
38 if (__builtin_expect (src_length >= size, 0))
39 {
40 if (size > 0)
41 {
42 /* Copy the leading portion of the string. The last
43 character is subsequently overwritten with the NUL
44 terminator, but the destination size is usually a
45 multiple of a small power of two, so writing it twice
46 should be more efficient than copying an odd number of
47 bytes. */
48 memcpy (dest, src, size);
49 dest[size - 1] = '\0';
50 }
51 }
52 else
53 /* Copy the string and its terminating NUL character. */
54 memcpy (dest, src, src_length + 1);
55 return src_length;
56 }
57 #endif /* HAVE_STRLCPY */