From 06b2c8ad8a33bb720ff03352e4d990e1dcf3d23c Mon Sep 17 00:00:00 2001 From: Andrew Kesterson Date: Tue, 2 Jun 2026 17:11:38 -0400 Subject: [PATCH] Add a DJB2 string hashing function --- include/akstdlib.h | 3 +++ src/stdlib.c | 14 ++++++++++++++ 2 files changed, 17 insertions(+) diff --git a/include/akstdlib.h b/include/akstdlib.h index 90ce834..0d64e9d 100644 --- a/include/akstdlib.h +++ b/include/akstdlib.h @@ -5,6 +5,7 @@ #include #include #include +#include akerr_ErrorContext AKERR_NOIGNORE *aksl_fopen(char *pathname, char *mode, FILE **fp); akerr_ErrorContext AKERR_NOIGNORE *aksl_fread(void *ptr, size_t size, size_t nmemb, FILE *stream); @@ -28,4 +29,6 @@ akerr_ErrorContext AKERR_NOIGNORE *aksl_atof(const char *nptr, double *dest); akerr_ErrorContext AKERR_NOIGNORE *aksl_realpath(const char *restrict path, char *restrict resolved_path); +akerr_ErrorContext AKERR_NOIGNORE *aksl_strhash_djb2(char *str, size_t len, uint32_t *hashval); + #endif diff --git a/src/stdlib.c b/src/stdlib.c index b6cc060..6b1c110 100644 --- a/src/stdlib.c +++ b/src/stdlib.c @@ -4,6 +4,7 @@ #include #include #include +#include akerr_ErrorContext AKERR_NOIGNORE *aksl_malloc(size_t size, void **dst) { @@ -174,3 +175,16 @@ akerr_ErrorContext AKERR_NOIGNORE *aksl_realpath(const char *restrict path, char FAIL_ZERO_RETURN(e, result, errno, "path=%s, dest=%s", path, resolved_path); SUCCEED_RETURN(e); } + +akerr_ErrorContext AKERR_NOIGNORE *aksl_strhash_djb2(char *str, size_t len, uint32_t *hashval) +{ + PREPARE_ERROR(e); + FAIL_ZERO_RETURN(e, str, AKERR_NULLPOINTER, "str"); + FAIL_ZERO_RETURN(e, hashval, AKERR_NULLPOINTER, "hashval"); + uint32_t h = 5381; + while (len--) { + h = ((h << 5) + h) + *str++; + } + *hashval = h; + SUCCEED_RETURN(e); +}