summaryrefslogtreecommitdiffstats
path: root/src/strcasecmp.c
blob: a1a360596971954e1e9b47caea388b47d1afabbd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/* -*- Mode: c; c-basic-offset: 2 -*-
 *
 * strcasecmp.c - strcasecmp compatibility
 *
 * This file is in the public domain.
 * 
 */

#ifdef HAVE_CONFIG_H
#include <raptor_config.h>
#endif

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int raptor_strcasecmp(const char* s1, const char* s2);
int raptor_strncasecmp(const char* s1, const char* s2, size_t n);


int
raptor_strcasecmp(const char* s1, const char* s2)
{
  register int c1, c2;
  
  while(*s1 && *s2) {
    c1 = tolower((int)*s1);
    c2 = tolower((int)*s2);
    if(c1 != c2)
      return (c1 - c2);
    s1++;
    s2++;
  }
  return (int) (*s1 - *s2);
}


int
raptor_strncasecmp(const char* s1, const char* s2, size_t n)
{
  register int c1, c2;
  
  while(*s1 && *s2 && n) {
    c1 = tolower((int)*s1);
    c2 = tolower((int)*s2);
    if(c1 != c2)
      return (c1 - c2);
    s1++;
    s2++;
    n--;
  }
  return 0;
}



#ifdef STANDALONE


static int
assert_strcasecmp (const char *s1, const char *s2, int expected)
{
  int result = raptor_strcasecmp(s1, s2);
  result = (result > 0) ? 1 : ((result <0) ? -1 : 0);

  if(result != expected)
    {
      fprintf(stderr, "FAIL strcasecmp (%s, %s) gave %d != %d\n",
              s1, s2, result, expected);
      return 1;
    }
  return 0;
}


static int
assert_strncasecmp (const char *s1, const char *s2, size_t size, int expected)
{
  int result = raptor_strncasecmp(s1, s2, size);
  result = (result > 0) ? 1 : ((result <0) ? -1 : 0);

  if(result != expected)
    {
      fprintf(stderr, "FAIL strncasecmp (%s, %s, %d) gave %d != %d\n",
              s1, s2, (unsigned int)size, result, expected);
      return 1;
    }
  return 0;
}


int
main(int argc, char *argv[]) 
{
  int failures = 0;
  
  failures += assert_strcasecmp("foo", "foo", 0);
  failures += assert_strcasecmp("foo", "FOO", 0);
  failures += assert_strcasecmp("foo", "BaR", 1);

  failures += assert_strncasecmp("foo", "foobar", 3, 0);
  failures += assert_strncasecmp("foo", "FOOxyz", 3, 0);
  failures += assert_strncasecmp("foo", "BaRfoo", 3, 1);

  return failures;
}

#endif