xref: /reactos/sdk/lib/ucrt/string/strncmp.c (revision b09b5584)
1 /***
2 *strncmp.c - compare first n characters of two strings
3 *
4 *       Copyright (c) Microsoft Corporation. All rights reserved.
5 *
6 *Purpose:
7 *       defines strncmp() - compare first n characters of two strings
8 *       for ordinal order.
9 *
10 *******************************************************************************/
11 
12 #include <string.h>
13 
14 #ifdef _M_ARM
15     #pragma function(strncmp)
16 #endif
17 
18 /***
19 *int strncmp(first, last, count) - compare first count chars of strings
20 *
21 *Purpose:
22 *       Compares two strings for ordinal order.  The comparison stops
23 *       after: (1) a difference between the strings is found, (2) the end
24 *       of the strings is reached, or (3) count characters have been
25 *       compared.
26 *
27 *Entry:
28 *       char *first, *last - strings to compare
29 *       unsigned count - maximum number of characters to compare
30 *
31 *Exit:
32 *       returns <0 if first < last
33 *       returns  0 if first == last
34 *       returns >0 if first > last
35 *
36 *Exceptions:
37 *
38 *******************************************************************************/
39 
40 int __cdecl strncmp
41 (
42     const char *first,
43     const char *last,
44     size_t      count
45 )
46 {
47     size_t x = 0;
48 
49     if (!count)
50     {
51         return 0;
52     }
53 
54     /*
55      * This explicit guard needed to deal correctly with boundary
56      * cases: strings shorter than 4 bytes and strings longer than
57      * UINT_MAX-4 bytes .
58      */
59     if( count >= 4 )
60     {
61         /* unroll by four */
62         for (; x < count-4; x+=4)
63         {
64             first+=4;
65             last +=4;
66 
67             if (*(first-4) == 0 || *(first-4) != *(last-4))
68             {
69                 return(*(unsigned char *)(first-4) - *(unsigned char *)(last-4));
70             }
71 
72             if (*(first-3) == 0 || *(first-3) != *(last-3))
73             {
74                 return(*(unsigned char *)(first-3) - *(unsigned char *)(last-3));
75             }
76 
77             if (*(first-2) == 0 || *(first-2) != *(last-2))
78             {
79                 return(*(unsigned char *)(first-2) - *(unsigned char *)(last-2));
80             }
81 
82             if (*(first-1) == 0 || *(first-1) != *(last-1))
83             {
84                 return(*(unsigned char *)(first-1) - *(unsigned char *)(last-1));
85             }
86         }
87     }
88 
89     /* residual loop */
90     for (; x < count; x++)
91     {
92         if (*first == 0 || *first != *last)
93         {
94             return(*(unsigned char *)first - *(unsigned char *)last);
95         }
96         first+=1;
97         last+=1;
98     }
99 
100     return 0;
101 }
102