From a10103ed9735b083200dfb78233fce325a9329dc Mon Sep 17 00:00:00 2001 From: 3gg <3gg@shellblade.net> Date: Sat, 1 Nov 2025 14:21:37 -0700 Subject: Add hash library --- CMakeLists.txt | 1 + hash/CMakeLists.txt | 14 ++++++++++++++ hash/include/fnv1a.h | 9 +++++++++ hash/src/fnv1a.c | 23 +++++++++++++++++++++++ 4 files changed, 47 insertions(+) create mode 100644 hash/CMakeLists.txt create mode 100644 hash/include/fnv1a.h create mode 100644 hash/src/fnv1a.c diff --git a/CMakeLists.txt b/CMakeLists.txt index d1fb3ab..a7ce893 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,6 +8,7 @@ add_subdirectory(cassert) add_subdirectory(cstring) add_subdirectory(error) add_subdirectory(filesystem) +add_subdirectory(hash) add_subdirectory(list) add_subdirectory(log) add_subdirectory(mem) diff --git a/hash/CMakeLists.txt b/hash/CMakeLists.txt new file mode 100644 index 0000000..8191f25 --- /dev/null +++ b/hash/CMakeLists.txt @@ -0,0 +1,14 @@ +cmake_minimum_required(VERSION 3.5) + +project(hash) + +set(CMAKE_C_STANDARD 23) +set(CMAKE_C_STANDARD_REQUIRED On) +set(CMAKE_C_EXTENSIONS Off) + +add_library(hash + src/fnv1a.c) + +target_include_directories(hash PUBLIC include) + +target_compile_options(hash PRIVATE -Wall -Wextra) diff --git a/hash/include/fnv1a.h b/hash/include/fnv1a.h new file mode 100644 index 0000000..0d2e7cf --- /dev/null +++ b/hash/include/fnv1a.h @@ -0,0 +1,9 @@ +#pragma once + +#include +#include + +uint32_t fnv1a32(const void* buffer, size_t size_bytes); + +uint32_t fnv1a32_begin(); +uint32_t fnv1a32_update(uint32_t hash, const void* buffer, size_t size_bytes); diff --git a/hash/src/fnv1a.c b/hash/src/fnv1a.c new file mode 100644 index 0000000..32cb538 --- /dev/null +++ b/hash/src/fnv1a.c @@ -0,0 +1,23 @@ +#include + +#include + +#define FNV_PRIME 2166136261 +#define FNV_OFFSET_BASIS 16777619 + +uint32_t fnv1a_32(const void* buffer, size_t size) { + assert(buffer); + return fnv1a32_update(fnv1a32_begin(), buffer, size); +} + +uint32_t fnv1a32_begin() { return FNV_PRIME; } + +uint32_t fnv1a32_update(uint32_t hash, const void* buffer, size_t size) { + assert(buffer); + const uint8_t* bytes = buffer; + for (size_t i = 0; i < size; i++) { + hash = hash ^ bytes[i]; + hash = hash * FNV_OFFSET_BASIS; + } + return hash; +} -- cgit v1.2.3