Updates to libhashkit.
[awesomized/libmemcached] / libhashkit / hashkit.c
1 /* HashKit
2 * Copyright (C) 2006-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 static const hashkit_st global_default_hash= {
12 .base_hash= {
13 .type= HASHKIT_HASH_DEFAULT,
14 .function= hashkit_one_at_a_time,
15 .context= NULL
16 },
17 };
18
19 /**
20 @note We make no assumptions that "hashk" has been, or not been allocated from heap/stack. We just know we didn't do it.
21 */
22 hashkit_st *hashkit_create(hashkit_st *self)
23 {
24 if (self == NULL)
25 {
26 self= (hashkit_st *)malloc(sizeof(hashkit_st));
27 if (self == NULL)
28 {
29 return NULL;
30 }
31
32 self->options.is_allocated= true;
33 }
34 else
35 {
36 self->options.is_allocated= false;
37 }
38
39 self->base_hash= global_default_hash.base_hash;
40
41 return self;
42 }
43
44
45 void hashkit_free(hashkit_st *self)
46 {
47 if (hashkit_is_allocated(self))
48 {
49 free(self);
50 }
51 }
52
53 /**
54 @note We do assume source is valid. If source does not exist, we allocate.
55 */
56 hashkit_st *hashkit_clone(hashkit_st *destination, const hashkit_st *source)
57 {
58 if (source == NULL)
59 {
60 return hashkit_create(destination);
61 }
62
63 /* new_clone will be a pointer to destination */
64 destination= hashkit_create(destination);
65
66 // Should only happen on allocation failure.
67 if (destination == NULL)
68 {
69 return NULL;
70 }
71
72 destination->base_hash= source->base_hash;
73
74 return destination;
75 }
76
77
78 uint32_t hashkit_generate_value(const hashkit_st *self, const char *key, size_t key_length)
79 {
80 return self->base_hash.function(key, key_length);
81 }
82
83 uint32_t libhashkit_generate_value(const char *key, size_t key_length, hashkit_hash_algorithm_t hash_algorithm)
84 {
85 switch (hash_algorithm)
86 {
87 case HASHKIT_HASH_DEFAULT:
88 return hashkit_one_at_a_time(key, key_length);
89 case HASHKIT_HASH_MD5:
90 return hashkit_md5(key, key_length);
91 case HASHKIT_HASH_CRC:
92 return hashkit_crc32(key, key_length);
93 case HASHKIT_HASH_FNV1_64:
94 return hashkit_fnv1_64(key, key_length);
95 case HASHKIT_HASH_FNV1A_64:
96 return hashkit_fnv1a_64(key, key_length);
97 case HASHKIT_HASH_FNV1_32:
98 return hashkit_fnv1_32(key, key_length);
99 case HASHKIT_HASH_FNV1A_32:
100 return hashkit_fnv1a_32(key, key_length);
101 case HASHKIT_HASH_HSIEH:
102 #ifdef HAVE_HSIEH_HASH
103 return hashkit_hsieh(key, key_length);
104 #else
105 return 1;
106 #endif
107 case HASHKIT_HASH_MURMUR:
108 return hashkit_murmur(key, key_length);
109 case HASHKIT_HASH_JENKINS:
110 return hashkit_jenkins(key, key_length);
111 case HASHKIT_HASH_MAX:
112 default:
113 #ifdef HAVE_DEBUG
114 fprintf(stderr, "hashkit_hash_t was extended but libhashkit_generate_value was not updated\n");
115 fflush(stderr);
116 assert(0);
117 #endif
118 break;
119 }
120
121 return 1;
122 }