47c9e580c7b50df985b16ad7457939399c6eb24d
[m6w6/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 .function= hashkit_one_at_a_time,
14 .context= NULL
15 },
16 .flags= {
17 .is_base_same_distributed= false,
18 }
19 };
20
21 static inline bool _hashkit_init(hashkit_st *self)
22 {
23 self->base_hash= global_default_hash.base_hash;
24 self->distribution_hash= global_default_hash.base_hash;
25 self->flags= global_default_hash.flags;
26
27 return true;
28 }
29
30 static inline hashkit_st *_hashkit_create(hashkit_st *self)
31 {
32 if (self == NULL)
33 {
34 self= (hashkit_st *)malloc(sizeof(hashkit_st));
35 if (self == NULL)
36 {
37 return NULL;
38 }
39
40 self->options.is_allocated= true;
41 }
42 else
43 {
44 self->options.is_allocated= false;
45 }
46
47 return self;
48 }
49
50 hashkit_st *hashkit_create(hashkit_st *self)
51 {
52 self= _hashkit_create(self);
53 if (! self)
54 return self;
55
56 if (! _hashkit_init(self))
57 {
58 hashkit_free(self);
59 }
60
61 return self;
62 }
63
64
65 void hashkit_free(hashkit_st *self)
66 {
67 if (hashkit_is_allocated(self))
68 {
69 free(self);
70 }
71 }
72
73 hashkit_st *hashkit_clone(hashkit_st *destination, const hashkit_st *source)
74 {
75 if (source == NULL)
76 {
77 return hashkit_create(destination);
78 }
79
80 /* new_clone will be a pointer to destination */
81 destination= _hashkit_create(destination);
82
83 // Should only happen on allocation failure.
84 if (destination == NULL)
85 {
86 return NULL;
87 }
88
89 destination->base_hash= source->base_hash;
90 destination->distribution_hash= source->distribution_hash;
91 destination->flags= source->flags;
92
93 return destination;
94 }
95
96 bool hashkit_compare(const hashkit_st *first, const hashkit_st *second)
97 {
98 if (first->base_hash.function == second->base_hash.function &&
99 first->base_hash.context == second->base_hash.context &&
100 first->distribution_hash.function == second->distribution_hash.function &&
101 first->distribution_hash.context == second->distribution_hash.context &&
102 first->flags.is_base_same_distributed == second->flags.is_base_same_distributed)
103 {
104 return true;
105 }
106
107 return false;
108 }