xref: /dragonfly/sys/sys/fnv_hash.h (revision 3d760772)
1 /*
2  * Fowler / Noll / Vo Hash (FNV Hash)
3  * http://www.isthe.com/chongo/tech/comp/fnv/
4  *
5  * This is an implementation of the algorithms posted above.
6  * This file is placed in the public domain by Peter Wemm.
7  *
8  * $FreeBSD: src/sys/sys/fnv_hash.h,v 1.2.2.1 2001/03/21 10:50:59 peter Exp $
9  */
10 
11 #ifndef _SYS_FNV_HASH_H_
12 #define _SYS_FNV_HASH_H_
13 
14 #ifndef _SYS_TYPES_H_
15 #include <sys/types.h>
16 #endif
17 
18 typedef u_int32_t Fnv32_t;
19 typedef u_int64_t Fnv64_t;
20 
21 #define FNV1_32_INIT ((Fnv32_t) 33554467UL)
22 #define FNV1_64_INIT ((Fnv64_t) 0xcbf29ce484222325ULL)
23 
24 #define FNV_32_PRIME ((Fnv32_t) 0x01000193UL)
25 #define FNV_64_PRIME ((Fnv64_t) 0x100000001b3ULL)
26 
27 static __inline Fnv32_t
28 fnv_32_buf(const void *buf, size_t len, Fnv32_t hval)
29 {
30 	const u_int8_t *s = (const u_int8_t *)buf;
31 
32 	while (len-- != 0) {
33 		hval *= FNV_32_PRIME;
34 		hval ^= *s++;
35 	}
36 	return hval;
37 }
38 
39 static __inline Fnv32_t
40 fnv_32_str(const char *str, Fnv32_t hval)
41 {
42 	const u_int8_t *s = (const u_int8_t *)str;
43 	Fnv32_t c;
44 
45 	while ((c = *s++) != 0) {
46 		hval *= FNV_32_PRIME;
47 		hval ^= c;
48 	}
49 	return hval;
50 }
51 
52 static __inline Fnv64_t
53 fnv_64_buf(const void *buf, size_t len, Fnv64_t hval)
54 {
55 	const u_int8_t *s = (const u_int8_t *)buf;
56 
57 	while (len-- != 0) {
58 		hval *= FNV_64_PRIME;
59 		hval ^= *s++;
60 	}
61 	return hval;
62 }
63 
64 static __inline Fnv64_t
65 fnv_64_str(const char *str, Fnv64_t hval)
66 {
67 	const u_int8_t *s = (const u_int8_t *)str;
68 	u_register_t c;		 /* 64 bit on x86_64 */
69 
70 	while ((c = *s++) != 0) {
71 		hval *= FNV_64_PRIME;
72 		hval ^= c;
73 	}
74 	return hval;
75 }
76 
77 #endif
78