Move some conditionals from the .c file to the .m4 file.
[gnulib.git] / lib / stpncpy.c
1 /* Copyright (C) 1993, 1995-1997, 2002-2003, 2005 Free Software Foundation, Inc.
2
3    NOTE: The canonical source of this file is maintained with the GNU C Library.
4    Bugs can be reported to bug-glibc@gnu.org.
5
6    This program is free software; you can redistribute it and/or modify it
7    under the terms of the GNU General Public License as published by the
8    Free Software Foundation; either version 2, or (at your option) any
9    later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
19    USA.  */
20
21 /* This is almost copied from strncpy.c, written by Torbjorn Granlund.  */
22
23 #ifdef HAVE_CONFIG_H
24 # include <config.h>
25 #endif
26
27 /* Specification.  */
28 #include "stpncpy.h"
29
30 #ifndef weak_alias
31 # define __stpncpy stpncpy
32 #endif
33
34 /* Copy no more than N bytes of SRC to DST, returning a pointer past the
35    last non-NUL byte written into DST.  */
36 char *
37 __stpncpy (char *dest, const char *src, size_t n)
38 {
39   char c;
40   char *s = dest;
41
42   if (n >= 4)
43     {
44       size_t n4 = n >> 2;
45
46       for (;;)
47         {
48           c = *src++;
49           *dest++ = c;
50           if (c == '\0')
51             break;
52           c = *src++;
53           *dest++ = c;
54           if (c == '\0')
55             break;
56           c = *src++;
57           *dest++ = c;
58           if (c == '\0')
59             break;
60           c = *src++;
61           *dest++ = c;
62           if (c == '\0')
63             break;
64           if (--n4 == 0)
65             goto last_chars;
66         }
67       n -= dest - s;
68       goto zero_fill;
69     }
70
71  last_chars:
72   n &= 3;
73   if (n == 0)
74     return dest;
75
76   for (;;)
77     {
78       c = *src++;
79       --n;
80       *dest++ = c;
81       if (c == '\0')
82         break;
83       if (n == 0)
84         return dest;
85     }
86
87  zero_fill:
88   while (n-- > 0)
89     dest[n] = '\0';
90
91   return dest - 1;
92 }
93 #ifdef weak_alias
94 weak_alias (__stpncpy, stpncpy)
95 #endif