From 896478de2dd7064189731ac008263ccbc48d57d3 Mon Sep 17 00:00:00 2001 From: orange Date: Sun, 16 Jun 2013 19:00:09 +0200 Subject: [PATCH] add fnv32_1 implementation --- .gitignore | 1 + Makefile | 2 +- bloom.c | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 bloom.c diff --git a/.gitignore b/.gitignore index 5245adb..d742c39 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,4 @@ ncurses-pong checkcheck multibrot multibrot.png +bloom diff --git a/Makefile b/Makefile index 5918cef..ae17d0a 100644 --- a/Makefile +++ b/Makefile @@ -1,7 +1,7 @@ CFLAGS=-std=c99 -Wall -g -O2 INDENTOPTS=-kr --no-tabs --braces-on-func-def-line --indent-level2 -TARGETS=approximate-pi linked-list mandelbrot threads circular-buffer structs ncurses-pong bit-fuckery bit-fuckery2 checkcheck multibrot +TARGETS=approximate-pi linked-list mandelbrot threads circular-buffer structs ncurses-pong bit-fuckery bit-fuckery2 checkcheck multibrot bloom EXTRAS=mandelbrot.bmp multibrot.png .PHONY: all diff --git a/bloom.c b/bloom.c new file mode 100644 index 0000000..7aa0f60 --- /dev/null +++ b/bloom.c @@ -0,0 +1,46 @@ +#include +#include +#include +#include + +/* + * FNV-1 hash implementation (32-bit aka FNV32_1). + * + * See http://isthe.com/chongo/tech/comp/fnv/ + */ +uint32_t fnv32_1(uint8_t *data, size_t data_len) { + uint32_t hash; + + /* Constants, for 32-bit only. */ + uint32_t offset_basis = (uint32_t) 2166136261UL; + uint32_t FNV_prime = (uint32_t) 16777619UL; + + hash = offset_basis; + for (size_t i = 0; i < data_len; i++) { + hash = hash * FNV_prime; /* implictly modulo 2^32 */ + hash = hash ^ data[i]; /* implictly only on lower octet. */ + } + return hash; +} + +/* Compute FNV-1 hash for the given string (without NUL byte). */ +uint32_t fnv32_1_str(char *string) { + return fnv32_1((uint8_t *) string, strlen(string)); +} + +int main(void) { + /* Test FNV32_1 */ + assert(fnv32_1_str("03SB[") == 0x00000000UL); + assert(fnv32_1_str("") == 0x811c9dc5UL); + assert(fnv32_1_str("a") == 0x050c5d7eUL); + assert(fnv32_1_str("b") == 0x050c5d7dUL); + assert(fnv32_1_str("c") == 0x050c5d7cUL); + assert(fnv32_1_str("d") == 0x050c5d7bUL); + assert(fnv32_1_str("e") == 0x050c5d7aUL); + assert(fnv32_1_str("f") == 0x050c5d79UL); + assert(fnv32_1_str("fo") == 0x6b772514UL); + assert(fnv32_1_str("foo") == 0x408f5e13UL); + assert(fnv32_1_str("foob") == 0xb4b1178bUL); + assert(fnv32_1_str("fooba") == 0xfdc80fb0UL); + assert(fnv32_1_str("foobar") == 0x31f0b262UL); +}