From 22c20b522fcc9cc0743ad04fe6c3203c7a778401 Mon Sep 17 00:00:00 2001 From: Tyge Løvset Date: Tue, 31 May 2022 21:19:06 +0200 Subject: Added simple utf8 case insensitive wrappers: cstr_iequals(), cstr_istarts_with(), and cstr_iends_with(). --- include/stc/cstr.h | 25 ++++++++++++++++++++----- src/utf8code.c | 4 ++-- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/include/stc/cstr.h b/include/stc/cstr.h index ce8b9e26..41e29a84 100644 --- a/include/stc/cstr.h +++ b/include/stc/cstr.h @@ -243,10 +243,13 @@ STC_INLINE bool cstr_eq(const cstr* s1, const cstr* s2) { } STC_INLINE bool cstr_equals(cstr s1, const char* str) - { return strcmp(cstr_str(&s1), str) == 0; } + { return !strcmp(cstr_str(&s1), str); } + +STC_INLINE bool cstr_iequals(cstr s1, const char* str) + { return !utf8_icmp(cstr_str(&s1), str); } STC_INLINE bool cstr_equals_s(cstr s1, cstr s2) - { return cstr_cmp(&s1, &s2) == 0; } + { return !cstr_cmp(&s1, &s2); } STC_INLINE size_t cstr_find(cstr s, const char* search) { const char *str = cstr_str(&s), *res = strstr((char*)str, search); @@ -265,15 +268,27 @@ STC_INLINE bool cstr_contains_s(cstr s, cstr search) STC_INLINE bool cstr_starts_with(cstr s, const char* sub) { const char* str = cstr_str(&s); while (*sub && *str == *sub) ++str, ++sub; - return *sub == 0; + return !*sub; +} +STC_INLINE bool cstr_istarts_with(cstr s, const char* sub) { + csview sv = cstr_sv(&s); + size_t n = strlen(sub); + return n <= sv.size && !utf8_icmp_n(cstr_npos, sv.str, sv.size, sub, n); } STC_INLINE bool cstr_starts_with_s(cstr s, cstr sub) { return cstr_starts_with(s, cstr_str(&sub)); } STC_INLINE bool cstr_ends_with(cstr s, const char* sub) { - csview sv = cstr_sv(&s); size_t n = strlen(sub); - return n <= sv.size && memcmp(sv.str + sv.size - n, sub, n) == 0; + csview sv = cstr_sv(&s); + size_t n = strlen(sub); + return n <= sv.size && !memcmp(sv.str + sv.size - n, sub, n); +} + +STC_INLINE bool cstr_iends_with(cstr s, const char* sub) { + csview sv = cstr_sv(&s); + size_t n = strlen(sub); + return n <= sv.size && !utf8_icmp(sv.str + sv.size - n, sub); } STC_INLINE bool cstr_ends_with_s(cstr s, cstr sub) diff --git a/src/utf8code.c b/src/utf8code.c index 0f74ffb6..cda730ce 100644 --- a/src/utf8code.c +++ b/src/utf8code.c @@ -87,8 +87,8 @@ uint32_t utf8_toupper(uint32_t c) { int utf8_icmp(const char* s1, const char* s2) { utf8_decode_t d1 = {.state=0}, d2 = {.state=0}; for (;;) { - do { utf8_decode(&d1, (uint8_t)s1[j1++]); } while (d1.state); - do { utf8_decode(&d2, (uint8_t)s2[j2++]); } while (d2.state); + do { utf8_decode(&d1, (uint8_t)*s1++); } while (d1.state); + do { utf8_decode(&d2, (uint8_t)*s2++); } while (d2.state); int c = utf8_tolower(d1.codep) - utf8_tolower(d2.codep); if (c || !*s2) return c; -- cgit v1.2.3