3 <<strncmp>>---character string compare
10 int strncmp(const char *<[a]>, const char * <[b]>, size_t <[length]>);
14 int strncmp(<[a]>, <[b]>, <[length]>)
20 <<strncmp>> compares up to <[length]> characters
21 from the string at <[a]> to the string at <[b]>.
24 If <<*<[a]>>> sorts lexicographically after <<*<[b]>>>,
25 <<strncmp>> returns a number greater than zero. If the two
26 strings are equivalent, <<strncmp>> returns zero. If <<*<[a]>>>
27 sorts lexicographically before <<*<[b]>>>, <<strncmp>> returns a
28 number less than zero.
31 <<strncmp>> is ANSI C.
33 <<strncmp>> requires no supporting OS subroutines.
41 #include "_ansi.h" /* for _DEFUN */
43 /* Nonzero if either X or Y is not aligned on a "long" boundary. */
44 #define UNALIGNED(X, Y) \
45 (((long)X & (sizeof (long) - 1)) | ((long)Y & (sizeof (long) - 1)))
47 /* DETECTNULL returns nonzero if (long)X contains a NULL byte. */
48 #if LONG_MAX == 2147483647L
49 #define DETECTNULL(X) (((X) - 0x01010101) & ~(X) & 0x80808080)
51 #if LONG_MAX == 9223372036854775807L
52 #define DETECTNULL(X) (((X) - 0x0101010101010101) & ~(X) & 0x8080808080808080)
54 #error long int is not a 32bit or 64bit type.
59 #error long int is not a 32bit or 64bit byte
63 _DEFUN (strncmp
, (s1
, s2
, n
),
68 #if defined(PREFER_SIZE_OVER_SPEED) || defined(__OPTIMIZE_SIZE__)
72 while (n
-- != 0 && *s1
== *s2
)
74 if (n
== 0 || *s1
== '\0')
80 return (*(unsigned char *) s1
) - (*(unsigned char *) s2
);
88 /* If s1 or s2 are unaligned, then compare bytes. */
89 if (!UNALIGNED (s1
, s2
))
91 /* If s1 and s2 are word-aligned, compare them a word at a time. */
92 a1
= (unsigned long*)s1
;
93 a2
= (unsigned long*)s2
;
94 while (n
>= sizeof (long) && *a1
== *a2
)
98 /* If we've run out of bytes or hit a null, return zero
99 since we already know *a1 == *a2. */
100 if (n
== 0 || DETECTNULL (*a1
))
107 /* A difference was detected in last few bytes of s1, so search bytewise */
112 while (n
-- > 0 && *s1
== *s2
)
114 /* If we've run out of bytes or hit a null, return zero
115 since we already know *s1 == *s2. */
116 if (n
== 0 || *s1
== '\0')
121 return (*(unsigned char *) s1
) - (*(unsigned char *) s2
);
122 #endif /* not PREFER_SIZE_OVER_SPEED */