Cygwin: mmap: allow remapping part of an existing anonymous mapping
[newlib-cygwin.git] / newlib / libc / string / strncpy.c
blobe7eb34d7210bb71f86f5686fdfa87e2f15b49464
1 /*
2 FUNCTION
3 <<strncpy>>---counted copy string
5 INDEX
6 strncpy
8 SYNOPSIS
9 #include <string.h>
10 char *strncpy(char *restrict <[dst]>, const char *restrict <[src]>,
11 size_t <[length]>);
13 DESCRIPTION
14 <<strncpy>> copies not more than <[length]> characters from the
15 the string pointed to by <[src]> (including the terminating
16 null character) to the array pointed to by <[dst]>. If the
17 string pointed to by <[src]> is shorter than <[length]>
18 characters, null characters are appended to the destination
19 array until a total of <[length]> characters have been
20 written.
22 RETURNS
23 This function returns the initial value of <[dst]>.
25 PORTABILITY
26 <<strncpy>> is ANSI C.
28 <<strncpy>> requires no supporting OS subroutines.
30 QUICKREF
31 strncpy ansi pure
34 #include <string.h>
35 #include <limits.h>
37 /*SUPPRESS 560*/
38 /*SUPPRESS 530*/
40 /* Nonzero if either X or Y is not aligned on a "long" boundary. */
41 #define UNALIGNED(X, Y) \
42 (((long)X & (sizeof (long) - 1)) | ((long)Y & (sizeof (long) - 1)))
44 #if LONG_MAX == 2147483647L
45 #define DETECTNULL(X) (((X) - 0x01010101) & ~(X) & 0x80808080)
46 #else
47 #if LONG_MAX == 9223372036854775807L
48 /* Nonzero if X (a long int) contains a NULL byte. */
49 #define DETECTNULL(X) (((X) - 0x0101010101010101) & ~(X) & 0x8080808080808080)
50 #else
51 #error long int is not a 32bit or 64bit type.
52 #endif
53 #endif
55 #ifndef DETECTNULL
56 #error long int is not a 32bit or 64bit byte
57 #endif
59 #define TOO_SMALL(LEN) ((LEN) < sizeof (long))
61 char *
62 strncpy (char *__restrict dst0,
63 const char *__restrict src0,
64 size_t count)
66 #if defined(PREFER_SIZE_OVER_SPEED) || defined(__OPTIMIZE_SIZE__)
67 char *dscan;
68 const char *sscan;
70 dscan = dst0;
71 sscan = src0;
72 while (count > 0)
74 --count;
75 if ((*dscan++ = *sscan++) == '\0')
76 break;
78 while (count-- > 0)
79 *dscan++ = '\0';
81 return dst0;
82 #else
83 char *dst = dst0;
84 const char *src = src0;
85 long *aligned_dst;
86 const long *aligned_src;
88 /* If SRC and DEST is aligned and count large enough, then copy words. */
89 if (!UNALIGNED (src, dst) && !TOO_SMALL (count))
91 aligned_dst = (long*)dst;
92 aligned_src = (long*)src;
94 /* SRC and DEST are both "long int" aligned, try to do "long int"
95 sized copies. */
96 while (count >= sizeof (long int) && !DETECTNULL(*aligned_src))
98 count -= sizeof (long int);
99 *aligned_dst++ = *aligned_src++;
102 dst = (char*)aligned_dst;
103 src = (char*)aligned_src;
106 while (count > 0)
108 --count;
109 if ((*dst++ = *src++) == '\0')
110 break;
113 while (count-- > 0)
114 *dst++ = '\0';
116 return dst0;
117 #endif /* not PREFER_SIZE_OVER_SPEED */