4eb99bef26f180e667ce552ee442b9d1f3329da1
[platform/upstream/groff.git] / src / libs / libgroff / strcasecmp.c
1 /* strcasecmp.c -- case insensitive string comparator
2    Copyright (C) 1998-2014  Free Software Foundation, Inc.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program. If not, see <http://www.gnu.org/licenses/>.  */
16
17 #if HAVE_CONFIG_H
18 # include <config.h>
19 #endif
20
21 #ifdef LENGTH_LIMIT
22 # define STRXCASECMP_FUNCTION strncasecmp
23 # define STRXCASECMP_DECLARE_N , size_t n
24 # define LENGTH_LIMIT_EXPR(Expr) Expr
25 #else
26 # define STRXCASECMP_FUNCTION strcasecmp
27 # define STRXCASECMP_DECLARE_N /* empty */
28 # define LENGTH_LIMIT_EXPR(Expr) 0
29 #endif
30
31 #include <stddef.h>
32 #include <ctype.h>
33
34 #define TOLOWER(Ch) (isupper (Ch) ? tolower (Ch) : (Ch))
35
36 /* Compare {{no more than N characters of }}strings S1 and S2,
37    ignoring case, returning less than, equal to or
38    greater than zero if S1 is lexicographically less
39    than, equal to or greater than S2.  */
40
41 int
42 STRXCASECMP_FUNCTION (const char *s1, const char *s2 STRXCASECMP_DECLARE_N)
43 {
44   register const unsigned char *p1 = (const unsigned char *) s1;
45   register const unsigned char *p2 = (const unsigned char *) s2;
46   unsigned char c1, c2;
47
48   if (p1 == p2 || LENGTH_LIMIT_EXPR (n == 0))
49     return 0;
50
51   do
52     {
53       c1 = TOLOWER (*p1);
54       c2 = TOLOWER (*p2);
55
56       if (LENGTH_LIMIT_EXPR (--n == 0) || c1 == '\0')
57         break;
58
59       ++p1;
60       ++p2;
61     }
62   while (c1 == c2);
63
64   return c1 - c2;
65 }