From 9c5dae413f3c5e0029f77de57c3d242b7205fe8e Mon Sep 17 00:00:00 2001 From: Krishna Vedala <7001608+kvedala@users.noreply.github.com> Date: Wed, 22 Jul 2020 12:55:13 -0400 Subject: [PATCH] split djb2 code from hash.c to independent program --- hash/hash_djb2.c | 49 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 hash/hash_djb2.c diff --git a/hash/hash_djb2.c b/hash/hash_djb2.c new file mode 100644 index 00000000..b3aca2aa --- /dev/null +++ b/hash/hash_djb2.c @@ -0,0 +1,49 @@ +/** + * @addtogroup hash Hash algorithms + * @{ + * @file hash_djb2.c + * @author [Christian Bender](https://github.com/christianbender) + * @brief [DJB2 hash algorithm](http://www.cse.yorku.ca/~oz/hash.html) + */ +#include +#include +#include + +/** + * @brief DJB2 algorithm implementation + * + * @param s NULL terminated string to hash + * @return 64-bit hash result + */ +uint64_t djb2(const char* s) +{ + uint64_t hash = 5381; /* init value */ + size_t i = 0; + while (s[i] != '\0') + { + hash = ((hash << 5) + hash) + s[i]; + i++; + } + return hash; +} + +/** + * @brief Test function for ::sdbm + */ +void test_djb2() +{ + assert(djb2("Hello World") == 13827776004929097857); + assert(djb2("Hello World!") == 13594750393630990530); + assert(djb2("Hello world") == 13827776004967047329); + assert(djb2("Hello world!") == 13594750394883323106); + printf("Tests passed\n"); +} + +/** @} */ + +/** Main function */ +int main() +{ + test_djb2(); + return 0; +}