17 #ifndef NDB_HASHMAP_HPP
18 #define NDB_HASHMAP_HPP
20 #include <ndb_global.h>
34 inline const void* HashMap__get_key(
const void* key_ptr,
size_t* key_length)
36 key_length = key_length;
45 template<
typename K,
typename T,
46 const void* G(
const void*,
size_t*) = HashMap__get_key >
52 Entry(
const K& k,
const T& v) : m_key(k), m_value(v) {};
57 static void free_element(
void * ptr) {
58 Entry*
entry = (Entry*)ptr;
68 static uchar* _get_key(
const uchar* ptr,
69 size_t* key_length, my_bool first) {
70 const Entry *
entry =
reinterpret_cast<const Entry*
>(ptr);
71 const void* key_ptr = G(&entry->m_key, key_length);
72 return (uchar*)key_ptr;
75 const void* get_key_ptr(
const K* key,
size_t *key_length)
const {
76 if (G == HashMap__get_key)
78 return _get_key((
const uchar*)key, key_length,
false);
82 HashMap(ulong initial_size = 1024, uint grow_size = 256) {
86 if (my_hash_init2(&m_hash,
92 G == HashMap__get_key ? NULL : _get_key,
100 my_hash_free(&m_hash);
103 bool insert(
const K& k,
const T& v,
bool replace =
false) {
104 Entry*
entry =
new Entry(k, v);
105 if (my_hash_insert(&m_hash, (
const uchar*)entry) != 0) {
111 if (
replace && search(k, &p)) {
120 bool search(
const K& k, T& v)
const {
128 bool search(
const K& k, T** v)
const {
129 size_t key_length =
sizeof(K);
130 const void *key = get_key_ptr(&k, &key_length);
131 Entry*
entry= (Entry*)my_hash_search(&m_hash,
132 (
const uchar*)key, key_length);
136 *v = &(entry->m_value);
140 bool remove(
const K& k) {
141 size_t key_length =
sizeof(K);
142 const void *key = get_key_ptr(&k, &key_length);
143 Entry*
entry= (Entry*)my_hash_search(&m_hash,
144 (
const uchar*)key, key_length);
148 if (my_hash_delete(&m_hash, (uchar*)entry))
153 bool remove(
size_t i) {
154 Entry*
entry = (Entry*)my_hash_element(&m_hash, (ulong)
i);
158 if (my_hash_delete(&m_hash, (uchar*)
entry))
163 size_t entries(
void)
const {
164 return m_hash.records;
167 T* value(
size_t i)
const {
168 Entry*
entry = (Entry*)my_hash_element((
HASH*)&m_hash, (ulong)i);
171 return &(entry->m_value);