64 lines
1.7 KiB
C
64 lines
1.7 KiB
C
#include <c_StrHashOps.h>
|
|
|
|
#include "c_Allocator.h"
|
|
|
|
C_STATIC_FORCE_INLINE
|
|
uint32_t hash_fmix32(uint32_t h) {
|
|
h ^= h >> 16;
|
|
h *= 0x3243f6a9U;
|
|
h ^= h >> 16;
|
|
return h;
|
|
}
|
|
|
|
// Hashing: Using djb2 for string data
|
|
uint32_t c_StrHashOps_Hash(const void *data, void *arg) {
|
|
uint32_t hash = 5381;
|
|
const char *str = (const char*) data;
|
|
char c;
|
|
while((c = *str++)) {
|
|
hash = ((hash << 5) + hash) + c; // hash * 33 + c
|
|
}
|
|
return hash_fmix32(hash);
|
|
}
|
|
|
|
|
|
// Deep Copy: Duplicating the string in memory
|
|
void* c_StrHashOps_Cp(const void *data, void *arg) {
|
|
if (!data || !arg) {
|
|
return NULL;
|
|
}
|
|
c_Allocator_t* allocator = arg;
|
|
const char *input = (const char*) data;
|
|
c_size_t len = strlen(input);
|
|
c_size_t size = len + 1;
|
|
char *result = c_Allocator_Alloc(allocator, size);
|
|
if (!result) {
|
|
return NULL;
|
|
}
|
|
memcpy(result, input, len);
|
|
result[len] = '\0';
|
|
|
|
return result;
|
|
}
|
|
|
|
// Equality: Comparing string contents
|
|
bool c_StrHashOps_Eq(const void *data1, const void *data2, void *arg) {
|
|
return strcmp((const char*)data1, (const char*)data2) == 0;
|
|
}
|
|
|
|
// Memory Cleanup
|
|
void c_StrHashOps_Free(void *data, void *arg) {
|
|
if (!data || !arg) {
|
|
return;
|
|
}
|
|
c_Allocator_t* allocator = arg;
|
|
c_Allocator_Free(allocator, data);
|
|
}
|
|
|
|
/* ------------------------------------------------------------------------------------------------------------------ */
|
|
/* */
|
|
|
|
c_HashKeyOps_t c_StrKeyOps={.hash = c_StrHashOps_Hash, .cp = c_StrHashOps_Cp, .free = c_StrHashOps_Free, .eq = c_StrHashOps_Eq, .arg = &c_DefaultAllocator};
|
|
|
|
c_HashValOps_t c_StrValOps={.cp = c_StrHashOps_Cp, .free = c_StrHashOps_Free, .eq = c_StrHashOps_Eq, .arg = &c_DefaultAllocator};
|