diff options
author | Paul Duncan <pabs@pablotron.org> | 2019-01-15 09:16:56 -0500 |
---|---|---|
committer | Paul Duncan <pabs@pablotron.org> | 2019-01-15 09:16:56 -0500 |
commit | 3e658ed87b5795b2be8f50d683dc19241aba0111 (patch) | |
tree | 0bc3b6e61e476e7ecdcb3c20429b159ea5465ae2 /src/core/sok-ctx-hash.c | |
parent | 914ca426630ccadcbb6f1ff02a599bdaf10b6cb2 (diff) | |
download | sok-3e658ed87b5795b2be8f50d683dc19241aba0111.tar.bz2 sok-3e658ed87b5795b2be8f50d683dc19241aba0111.zip |
s/libsok/core/g
Diffstat (limited to 'src/core/sok-ctx-hash.c')
-rw-r--r-- | src/core/sok-ctx-hash.c | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/src/core/sok-ctx-hash.c b/src/core/sok-ctx-hash.c new file mode 100644 index 0000000..61689ea --- /dev/null +++ b/src/core/sok-ctx-hash.c @@ -0,0 +1,41 @@ +#include <stdint.h> // uint16_t +#include "sok.h" + +// fnv64 +// src: https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function +#define FNV_OFFSET 1099511628211 +#define FNV_PRIME 0xcbf29ce484222325 + +static uint64_t +fnv1a( + const uint8_t * const buf, + const size_t len +) { + uint64_t hash = FNV_OFFSET; + + for (size_t i = 0; i < len; i++) { + hash ^= buf[i]; + hash *= FNV_PRIME; + } + + return hash; +} + +uint64_t +sok_ctx_hash( + const sok_ctx_t * const ctx +) { + uint16_t buf[512] = {ctx->home.x, ctx->home.y, 0}; + const size_t BUF_MASK = (sizeof(buf) / sizeof(uint16_t) - 1); + + for (size_t i = 0; i < ctx->level.num_boxes; i++) { + buf[(2 * (i + 1) + 0) & BUF_MASK] = ctx->boxes[i].x; + buf[(2 * (i + 1) + 1) & BUF_MASK] = ctx->boxes[i].y; + } + + // calculate buffer length + const size_t used = 2 * (ctx->level.num_boxes + 1) * sizeof(uint16_t); + const size_t len = (used < sizeof(buf)) ? used : sizeof(buf); + + return fnv1a((uint8_t*) buf, len); +} |