lh | 9ed821d | 2023-04-07 01:36:19 -0700 | [diff] [blame^] | 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, write to the Free |
| 16 | Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA |
| 17 | 02111-1307 USA. */ |
| 18 | |
| 19 | #include <string.h> |
| 20 | #include "memcopy.h" |
| 21 | |
| 22 | char *strncpy (char *s1, const char *s2, size_t n) |
| 23 | { |
| 24 | reg_char c; |
| 25 | char *s = s1; |
| 26 | |
| 27 | --s1; |
| 28 | |
| 29 | if (n >= 4) |
| 30 | { |
| 31 | size_t n4 = n >> 2; |
| 32 | |
| 33 | for (;;) |
| 34 | { |
| 35 | c = *s2++; |
| 36 | *++s1 = c; |
| 37 | if (c == '\0') |
| 38 | break; |
| 39 | c = *s2++; |
| 40 | *++s1 = c; |
| 41 | if (c == '\0') |
| 42 | break; |
| 43 | c = *s2++; |
| 44 | *++s1 = c; |
| 45 | if (c == '\0') |
| 46 | break; |
| 47 | c = *s2++; |
| 48 | *++s1 = c; |
| 49 | if (c == '\0') |
| 50 | break; |
| 51 | if (--n4 == 0) |
| 52 | goto last_chars; |
| 53 | } |
| 54 | n = n - (s1 - s) - 1; |
| 55 | if (n == 0) |
| 56 | return s; |
| 57 | goto zero_fill; |
| 58 | } |
| 59 | |
| 60 | last_chars: |
| 61 | n &= 3; |
| 62 | if (n == 0) |
| 63 | return s; |
| 64 | |
| 65 | do |
| 66 | { |
| 67 | c = *s2++; |
| 68 | *++s1 = c; |
| 69 | if (--n == 0) |
| 70 | return s; |
| 71 | } |
| 72 | while (c != '\0'); |
| 73 | |
| 74 | zero_fill: |
| 75 | do |
| 76 | *++s1 = '\0'; |
| 77 | while (--n > 0); |
| 78 | |
| 79 | return s; |
| 80 | } |
| 81 | libc_hidden_def(strncpy) |