Pārlūkot izejas kodu

[hash.h/.c] Converting to header only lib

Vinicius Teshima 2 gadi atpakaļ
vecāks
revīzija
21c54c390c
2 mainītis faili ar 33 papildinājumiem un 22 dzēšanām
  1. 33 4
      include/toolbox/hash.h
  2. 0 18
      src/toolbox/hash.c

+ 33 - 4
include/toolbox/hash.h

@@ -1,9 +1,38 @@
-#ifndef TOOLBOX_HASH_H
-#define TOOLBOX_HASH_H
+#ifndef HASH_H
+#define HASH_H
 
 #include <stdint.h>
+#include <stdlib.h>
 
-uint64_t
-hash_cstr(const char *r_p_cstr);
+typedef char byte;
+
+__attribute__((access (read_only, 1), nonnull, pure))
+uint64_t hash(const byte* data, size_t size);
+
+#if defined(CSTRING_IMP) || defined(IMPLEMENTATIONS)
+
+uint64_t hash(const byte* data, size_t size) {
+	static uint8_t _primes_list[] = {
+		3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59,
+		61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127,
+		131, 137, 139, 149, 151, 157, 163, 167, 173
+	};
+	static uint8_t _primes_list_size = 10;
+	uint64_t max = UINT64_MAX >> 1;
+	uint64_t ret = 1;
+	uint8_t p = 0;
+	size_t i = 0;
+	byte b = 0;
+
+	for ( i = 0; i < size; ++i ) {
+		b = data[i];
+		p = _primes_list[(i + b) % _primes_list_size];
+		ret = (ret * (b * p)) % max;
+	}
+
+	return ret;
+}
+
+#endif /* HASH_IMP || IMPLEMENTATIONS */
 
 #endif

+ 0 - 18
src/toolbox/hash.c

@@ -1,18 +0,0 @@
-#include "toolbox/hash.h"
-
-#include <stdint.h>
-
-// Copied From
-// http://www.cse.yorku.ca/~oz/hash.html
-
-uint64_t
-hash_cstr(const char *r_p_cstr) {
-	uint64_t hash = 5381;
-	int c;
-
-	while ( (c = *(r_p_cstr++)) != '\0' ) {
-		hash = ((hash << 5) + hash) + (uint64_t) c; /* hash * 33 + c */
-	}
-
-	return hash;
-}