Skip to content

Commit ebf843f

Browse files
committed
feat(util): add strhash()
1 parent bdd1d1c commit ebf843f

4 files changed

Lines changed: 16 additions & 1 deletion

File tree

include/LCUI/util/string.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,8 @@ LCUI_API int strtrim(char *outstr, const char *instr, const char *charlist);
5757
LCUI_API int wcstrim(wchar_t *outstr, const wchar_t *instr,
5858
const wchar_t *charlist);
5959

60+
LCUI_API unsigned strhash(unsigned hash, const char *str);
61+
6062
/**
6163
* 字符串替换
6264
* @param[in][out] str 需要处理的字符串,替换成功后字符串内容也会被修改

src/util/dict.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -676,7 +676,7 @@ void Dict_DisableResize(void)
676676
static unsigned int StringCopyKeyDict_KeyHash(const void *key)
677677
{
678678
const char *buf = key;
679-
unsigned int hash = 5381;
679+
unsigned int hash = dict_hash_function_seed;
680680
while (*buf) {
681681
hash = ((hash << 5) + hash) + (*buf++);
682682
}

src/util/string.c

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,16 @@ int wcstrim(wchar_t *outstr, const wchar_t *instr, const wchar_t *charlist)
143143
STRTRIM_CODE(wchar_t, outstr, instr, charlist, L"\t\n\r ");
144144
}
145145

146+
unsigned strhash(unsigned hash, const char *str)
147+
{
148+
const unsigned char *p = (unsigned char *)str;
149+
150+
while (*p) {
151+
hash = ((hash << 5) + hash) + (*p++);
152+
}
153+
return hash;
154+
}
155+
146156
size_t strreplace(char *str, size_t max_len, const char *substr,
147157
const char *newstr)
148158
{

test/test_string.c

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,9 @@ int test_strs(void)
4545
CHECK(!strlist_has(strs, "first-child"));
4646
CHECK(!strlist_has(strs, "one"));
4747
CHECK(strlist_has(strs, "two"));
48+
CHECK(strhash(123, "123") == strhash(123, "123"));
49+
CHECK(strhash(123, "123") != strhash(123, "312"));
50+
CHECK(strhash(100, "123") != strhash(123, "123"));
4851
CHECK(strlist_add(&strs, "first-child"));
4952
strlist_free(strs);
5053
return ret;

0 commit comments

Comments
 (0)