File: str_diffn.c

package info (click to toggle)
libowfat 0.34-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,288 kB
  • sloc: ansic: 20,181; makefile: 16
file content (38 lines) | stat: -rw-r--r-- 1,284 bytes parent folder | download
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
#include "byte.h"

/* str_diff returns negative, 0, or positive, depending on whether the
 * string a[0], a[1], ..., a[n]=='\0' is lexicographically smaller than,
 * equal to, or greater than the string b[0], b[1], ..., b[m-1]=='\0'.
 * When the strings are different, str_diff does not read bytes past the
 * first difference. */
int str_diffn(const char* a, const char* b, size_t limit) {
  register const unsigned char* s=(const unsigned char*)a;
  register const unsigned char* t=(const unsigned char*)b;
  register const unsigned char* u=t+limit;
  register int j;
  j=0;
  for (;;) {
    if (t>=u || (j=(*s-*t)) || !*t) break;
                                           ++s; ++t;
    if (t>=u || (j=(*s-*t)) || !*t) break;
                                           ++s; ++t;
    if (t>=u || (j=(*s-*t)) || !*t) break;
                                           ++s; ++t;
    if (t>=u || (j=(*s-*t)) || !*t) break;
                                           ++s; ++t;
  }
  return j;
}

#ifdef UNITTEST
#include <assert.h>
#include <string.h>

int main() {
  assert(str_diffn("foo","foo",3)==0);
  assert(str_diffn("foo","fob",3)==('o'-'b'));
  assert(str_diffn("foo","foox",4)==(-'x'));
  assert(str_diffn("foox","foo",4)=='x');
  assert(str_diffn("foo","fob",2)==0);
}
#endif