1 /* Copyright (C) 1991, 1997, 2003 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 #include <string.h>
19 #include "memcopy.h"
20
strncpy(char * s1,const char * s2,size_t n)21 char *strncpy (char *s1, const char *s2, size_t n)
22 {
23 reg_char c;
24 char *s = s1;
25
26 --s1;
27
28 if (n >= 4)
29 {
30 size_t n4 = n >> 2;
31
32 for (;;)
33 {
34 c = *s2++;
35 *++s1 = c;
36 if (c == '\0')
37 break;
38 c = *s2++;
39 *++s1 = c;
40 if (c == '\0')
41 break;
42 c = *s2++;
43 *++s1 = c;
44 if (c == '\0')
45 break;
46 c = *s2++;
47 *++s1 = c;
48 if (c == '\0')
49 break;
50 if (--n4 == 0)
51 goto last_chars;
52 }
53 n = n - (s1 - s) - 1;
54 if (n == 0)
55 return s;
56 goto zero_fill;
57 }
58
59 last_chars:
60 n &= 3;
61 if (n == 0)
62 return s;
63
64 do
65 {
66 c = *s2++;
67 *++s1 = c;
68 if (--n == 0)
69 return s;
70 }
71 while (c != '\0');
72
73 zero_fill:
74 do
75 *++s1 = '\0';
76 while (--n > 0);
77
78 return s;
79 }
80 libc_hidden_def(strncpy)
81