1 /* HashKit
2  * Copyright (C) 2009 Brian Aker
3  * All rights reserved.
4  *
5  * Use and distribution licensed under the BSD license.  See
6  * the COPYING file in the parent directory for full text.
7  */
8 
9 #include "common.h"
10 
11 /* FNV hash'es lifted from Dustin Sallings work */
12 static uint64_t FNV_64_INIT= UINT64_C(0xcbf29ce484222325);
13 static uint64_t FNV_64_PRIME= UINT64_C(0x100000001b3);
14 static uint32_t FNV_32_INIT= 2166136261UL;
15 static uint32_t FNV_32_PRIME= 16777619;
16 
hashkit_fnv1_64(const char *key, size_t key_length, void *context)17 uint32_t hashkit_fnv1_64(const char *key, size_t key_length, void *context)
18 {
19   /* Thanks to pierre@demartines.com for the pointer */
20   uint64_t hash= FNV_64_INIT;
21   size_t x;
22   (void)context;
23 
24   for (x= 0; x < key_length; x++)
25   {
26     hash *= FNV_64_PRIME;
27     hash ^= (uint64_t)key[x];
28   }
29 
30   return (uint32_t)hash;
31 }
32 
hashkit_fnv1a_64(const char *key, size_t key_length, void *context)33 uint32_t hashkit_fnv1a_64(const char *key, size_t key_length, void *context)
34 {
35   uint32_t hash= (uint32_t) FNV_64_INIT;
36   size_t x;
37   (void)context;
38 
39   for (x= 0; x < key_length; x++)
40   {
41     uint32_t val= (uint32_t)key[x];
42     hash ^= val;
43     hash *= (uint32_t) FNV_64_PRIME;
44   }
45 
46   return hash;
47 }
48 
hashkit_fnv1_32(const char *key, size_t key_length, void *context)49 uint32_t hashkit_fnv1_32(const char *key, size_t key_length, void *context)
50 {
51   uint32_t hash= FNV_32_INIT;
52   size_t x;
53   (void)context;
54 
55   for (x= 0; x < key_length; x++)
56   {
57     uint32_t val= (uint32_t)key[x];
58     hash *= FNV_32_PRIME;
59     hash ^= val;
60   }
61 
62   return hash;
63 }
64 
hashkit_fnv1a_32(const char *key, size_t key_length, void *context)65 uint32_t hashkit_fnv1a_32(const char *key, size_t key_length, void *context)
66 {
67   uint32_t hash= FNV_32_INIT;
68   size_t x;
69   (void)context;
70 
71   for (x= 0; x < key_length; x++)
72   {
73     uint32_t val= (uint32_t)key[x];
74     hash ^= val;
75     hash *= FNV_32_PRIME;
76   }
77 
78   return hash;
79 }
80