Skip to content

Commit 3162703

Browse files
fix up logic in string library
1 parent 33eda62 commit 3162703

File tree

1 file changed

+25
-9
lines changed

1 file changed

+25
-9
lines changed

code/logic/cstring.c

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -336,23 +336,32 @@ cstring fossil_io_cstring_pad_right(ccstring str, size_t total_length, char pad_
336336
}
337337

338338
int fossil_io_cstring_icmp(ccstring str1, ccstring str2) {
339+
if (!str1 || !str2) return (str1 == str2) ? 0 : (str1 ? 1 : -1);
339340
while (*str1 && *str2) {
340-
if (tolower((unsigned char)*str1) != tolower((unsigned char)*str2)) {
341-
return 0; // Not equal
341+
int c1 = tolower((unsigned char)*str1);
342+
int c2 = tolower((unsigned char)*str2);
343+
if (c1 != c2) {
344+
return c1 - c2;
342345
}
343346
str1++;
344347
str2++;
345348
}
346-
return (*str1 == '\0' && *str2 == '\0'); // Both strings must end at the same time
349+
return tolower((unsigned char)*str1) - tolower((unsigned char)*str2);
347350
}
348351

349352
int fossil_io_cstring_icontains(ccstring str, ccstring substr) {
350-
const char *p = str;
351-
while (*p) {
352-
if (fossil_io_cstring_icmp(p, substr) == 1) {
353-
return 1; // Found
353+
if (!str || !substr || !*substr) return 0;
354+
size_t substr_len = strlen(substr);
355+
for (const char *p = str; *p; ++p) {
356+
size_t i = 0;
357+
while (i < substr_len &&
358+
tolower((unsigned char)p[i]) == tolower((unsigned char)substr[i])) {
359+
i++;
354360
}
355-
p++;
361+
if (i == substr_len) {
362+
return 1; // Found (case-insensitive)
363+
}
364+
if (!p[i]) break;
356365
}
357366
return 0; // Not found
358367
}
@@ -489,7 +498,14 @@ cstring fossil_io_cstring_normalize_spaces(cstring str) {
489498

490499
int in_space = 0;
491500
char *dst = result;
492-
for (const char *src = str; *src; ++src) {
501+
const char *src = str;
502+
503+
// Skip leading spaces
504+
while (*src && isspace((unsigned char)*src)) {
505+
src++;
506+
}
507+
508+
for (; *src; ++src) {
493509
if (isspace((unsigned char)*src)) {
494510
if (!in_space) {
495511
*dst++ = ' ';

0 commit comments

Comments
 (0)