- 论坛徽章:
- 0
|
/* simple-assumption:
*
* most parts are equal and doing a case conversion needs time
*
*/
/*简单假定
大部分相等,并且做大小写转换需要一定的时间消耗
大小写不敏感比较
*/
int buffer_caseless_compare(const char *a, size_t a_len, const char *b, size_t b_len) {
size_t ndx = 0, max_ndx;
size_t *al, *bl;
size_t mask = sizeof(*al) - 1;
/*
??是这样的?
typedef unsigned int size_t;
类型强制转换
*/
al = (size_t *)a;
bl = (size_t *)b;
/* is the alignment correct ? */
/* 是否以4字节对齐(在32位下是以4字节,其它系统类似)
如果是,则做比较,如果大部分相等的情况下
这样的比较,速度快
*/
if ( ((size_t)al & mask) == 0 &&
((size_t)bl & mask) == 0 ) {
max_ndx = ((a_len < b_len) ? a_len : b_len) & ~mask;
for (; ndx < max_ndx; ndx += sizeof(*al)) {
if (*al != *bl) break; /*四字节比较失败,跳出*/
al++; bl++;
}
}
/*开始一个一个字节的比较*/
a = (char *)al;
b = (char *)bl;
max_ndx = ((a_len < b_len) ? a_len : b_len);
for (; ndx < max_ndx; ndx++) {
char a1 = *a++, b1 = *b++;
if (a1 != b1) {
if ((a1 >= 'A' && a1 <= 'Z') && (b1 >= 'a' && b1 <= 'z'))
a1 |= 32; /*把a1转为小写*/
else if ((a1 >= 'a' && a1 <= 'z') && (b1 >= 'A' && b1 <= 'Z'))
b1 |= 32; /*把b1转为小写*/
/*转换之后比较不相等则返回*/
if ((a1 - b1) != 0) return (a1 - b1);
}
}
/* all chars are the same, and the length match too
*
* they are the same */
if (a_len == b_len) return 0;
/* if a is shorter then b, then b is larger */
return (a_len - b_len);
}
|
|
|