Cygwin: mmap: use 64K pages for bookkeeping, second attempt
[newlib-cygwin.git] / newlib / libc / string / stpncpy.c
blob87fe268cf56ded712a81f8902af9f8586272f38c
1 /*
2 FUNCTION
3 <<stpncpy>>---counted copy string returning a pointer to its end
5 INDEX
6 stpncpy
8 SYNOPSIS
9 #include <string.h>
10 char *stpncpy(char *restrict <[dst]>, const char *restrict <[src]>,
11 size_t <[length]>);
13 DESCRIPTION
14 <<stpncpy>> 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 a pointer to the end of the destination string,
24 thus pointing to the trailing '\0', or, if the destination string is
25 not null-terminated, pointing to dst + n.
27 PORTABILITY
28 <<stpncpy>> is a GNU extension, candidate for inclusion into POSIX/SUSv4.
30 <<stpncpy>> requires no supporting OS subroutines.
32 QUICKREF
33 stpncpy gnu
36 #include <string.h>
37 #include <limits.h>
39 /*SUPPRESS 560*/
40 /*SUPPRESS 530*/
42 /* Nonzero if either X or Y is not aligned on a "long" boundary. */
43 #define UNALIGNED(X, Y) \
44 (((long)X & (sizeof (long) - 1)) | ((long)Y & (sizeof (long) - 1)))
46 #if LONG_MAX == 2147483647L
47 #define DETECTNULL(X) (((X) - 0x01010101) & ~(X) & 0x80808080)
48 #else
49 #if LONG_MAX == 9223372036854775807L
50 /* Nonzero if X (a long int) contains a NULL byte. */
51 #define DETECTNULL(X) (((X) - 0x0101010101010101) & ~(X) & 0x8080808080808080)
52 #else
53 #error long int is not a 32bit or 64bit type.
54 #endif
55 #endif
57 #ifndef DETECTNULL
58 #error long int is not a 32bit or 64bit byte
59 #endif
61 #define TOO_SMALL(LEN) ((LEN) < sizeof (long))
63 char *
64 stpncpy (char *__restrict dst,
65 const char *__restrict src,
66 size_t count)
68 char *ret = NULL;
70 #if !defined(PREFER_SIZE_OVER_SPEED) && !defined(__OPTIMIZE_SIZE__)
71 long *aligned_dst;
72 const long *aligned_src;
74 /* If SRC and DEST is aligned and count large enough, then copy words. */
75 if (!UNALIGNED (src, dst) && !TOO_SMALL (count))
77 aligned_dst = (long*)dst;
78 aligned_src = (long*)src;
80 /* SRC and DEST are both "long int" aligned, try to do "long int"
81 sized copies. */
82 while (count >= sizeof (long int) && !DETECTNULL(*aligned_src))
84 count -= sizeof (long int);
85 *aligned_dst++ = *aligned_src++;
88 dst = (char*)aligned_dst;
89 src = (char*)aligned_src;
91 #endif /* not PREFER_SIZE_OVER_SPEED */
93 while (count > 0)
95 --count;
96 if ((*dst++ = *src++) == '\0')
98 ret = dst - 1;
99 break;
103 while (count-- > 0)
104 *dst++ = '\0';
106 return ret ? ret : dst;