Prepare new maemo release
[maemo-rb.git] / apps / plugins / lib / strncpy.c
blob8a78b238822f1eb4943ceab756dddfb7db167149
1 /*
2 FUNCTION
3 <<strncpy>>---counted copy string
5 INDEX
6 strncpy
8 ANSI_SYNOPSIS
9 #include <string.h>
10 char *strncpy(char *<[dst]>, const char *<[src]>, size_t <[length]>);
12 TRAD_SYNOPSIS
13 #include <string.h>
14 char *strncpy(<[dst]>, <[src]>, <[length]>)
15 char *<[dst]>;
16 char *<[src]>;
17 size_t <[length]>;
19 DESCRIPTION
20 <<strncpy>> copies not more than <[length]> characters from the
21 the string pointed to by <[src]> (including the terminating
22 null character) to the array pointed to by <[dst]>. If the
23 string pointed to by <[src]> is shorter than <[length]>
24 characters, null characters are appended to the destination
25 array until a total of <[length]> characters have been
26 written.
28 RETURNS
29 This function returns the initial value of <[dst]>.
31 PORTABILITY
32 <<strncpy>> is ANSI C.
34 <<strncpy>> requires no supporting OS subroutines.
36 QUICKREF
37 strncpy ansi pure
40 #include <string.h>
41 #include <limits.h>
42 #include "plugin.h"
43 #include "_ansi.h"
45 /*SUPPRESS 560*/
46 /*SUPPRESS 530*/
48 /* Nonzero if either X or Y is not aligned on a "long" boundary. */
49 #define UNALIGNED(X, Y) \
50 (((long)X & (sizeof (long) - 1)) | ((long)Y & (sizeof (long) - 1)))
52 #if LONG_MAX == 2147483647L
53 #define DETECTNULL(X) (((X) - 0x01010101) & ~(X) & 0x80808080)
54 #else
55 #if LONG_MAX == 9223372036854775807L
56 /* Nonzero if X (a long int) contains a NULL byte. */
57 #define DETECTNULL(X) (((X) - 0x0101010101010101) & ~(X) & 0x8080808080808080)
58 #else
59 #error long int is not a 32bit or 64bit type.
60 #endif
61 #endif
63 #ifndef DETECTNULL
64 #error long int is not a 32bit or 64bit byte
65 #endif
67 #define TOO_SMALL(LEN) ((LEN) < sizeof (long))
69 char *
70 _DEFUN (strncpy, (dst0, src0),
71 char *dst0 _AND
72 _CONST char *src0 _AND
73 size_t count)
75 #if defined(PREFER_SIZE_OVER_SPEED) || defined(__OPTIMIZE_SIZE__)
76 char *dscan;
77 _CONST char *sscan;
79 dscan = dst0;
80 sscan = src0;
81 while (count > 0)
83 --count;
84 if ((*dscan++ = *sscan++) == '\0')
85 break;
87 while (count-- > 0)
88 *dscan++ = '\0';
90 return dst0;
91 #else
92 char *dst = dst0;
93 _CONST char *src = src0;
94 long *aligned_dst;
95 _CONST long *aligned_src;
97 /* If SRC and DEST is aligned and count large enough, then copy words. */
98 if (!UNALIGNED (src, dst) && !TOO_SMALL (count))
100 aligned_dst = (long*)dst;
101 aligned_src = (long*)src;
103 /* SRC and DEST are both "long int" aligned, try to do "long int"
104 sized copies. */
105 while (count >= sizeof (long int) && !DETECTNULL(*aligned_src))
107 count -= sizeof (long int);
108 *aligned_dst++ = *aligned_src++;
111 dst = (char*)aligned_dst;
112 src = (char*)aligned_src;
115 while (count > 0)
117 --count;
118 if ((*dst++ = *src++) == '\0')
119 break;
122 while (count-- > 0)
123 *dst++ = '\0';
125 return dst0;
126 #endif /* not PREFER_SIZE_OVER_SPEED */