blob: eb65a5f46f871799a130fadab015f3c3f2b785ab [file] [log] [blame]
lh9ed821d2023-04-07 01:36:19 -07001/* Copyright (C) 1993-2015 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
8
9 The GNU C Library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
13
14 You should have received a copy of the GNU Lesser General Public
15 License along with the GNU C Library; if not, see
16 <http://www.gnu.org/licenses/>. */
17
18/* This is almost copied from strncpy.c, written by Torbjorn Granlund. */
19
20#ifdef HAVE_CONFIG_H
21# include <config.h>
22#endif
23
24#ifdef _LIBC
25# include <string.h>
26#else
27# include <sys/types.h>
28#endif
29
30#ifndef STPNCPY
31# ifdef weak_alias
32# define STPNCPY __stpncpy
33weak_alias (__stpncpy, stpncpy)
34# else
35# define STPNCPY stpncpy
36# endif
37#endif
38
39/* Copy no more than N characters of SRC to DEST, returning the address of
40 the terminating '\0' in DEST, if any, or else DEST + N. */
41char *
42STPNCPY (char *dest, const char *src, size_t n)
43{
44 char c;
45 char *s = dest;
46
47 if (n >= 4)
48 {
49 size_t n4 = n >> 2;
50
51 for (;;)
52 {
53 c = *src++;
54 *dest++ = c;
55 if (c == '\0')
56 break;
57 c = *src++;
58 *dest++ = c;
59 if (c == '\0')
60 break;
61 c = *src++;
62 *dest++ = c;
63 if (c == '\0')
64 break;
65 c = *src++;
66 *dest++ = c;
67 if (c == '\0')
68 break;
69 if (--n4 == 0)
70 goto last_chars;
71 }
72 n -= dest - s;
73 goto zero_fill;
74 }
75
76 last_chars:
77 n &= 3;
78 if (n == 0)
79 return dest;
80
81 for (;;)
82 {
83 c = *src++;
84 --n;
85 *dest++ = c;
86 if (c == '\0')
87 break;
88 if (n == 0)
89 return dest;
90 }
91
92 zero_fill:
93 while (n-- > 0)
94 dest[n] = '\0';
95
96 return dest - 1;
97}
98#ifdef weak_alias
99libc_hidden_def (__stpncpy)
100#endif