| 1 | #ifndef __HASH_H__ |
| 2 | #define __HASH_H__ |
| 3 | |
| 4 | #include <stdlib.h> |
| 5 | |
| 6 | template<typename T> |
| 7 | class HashMap |
| 8 | { |
| 9 | public: |
| 10 | void init(unsigned power2) |
| 11 | { |
| 12 | _mask = (1 << power2) - 1; |
| 13 | _hashmap = (T**)malloc((_mask+1) * sizeof(T*)); |
| 14 | reset(); |
| 15 | } |
| 16 | |
| 17 | void destroy() |
| 18 | { |
| 19 | free(_hashmap); |
| 20 | } |
| 21 | |
| 22 | void reset() |
| 23 | { |
| 24 | memset(_hashmap, 0, (_mask+1) * sizeof(T*)); |
| 25 | } |
| 26 | |
| 27 | void insert(unsigned hash, T* data) |
| 28 | { |
| 29 | _hashmap[hash & _mask] = data; |
| 30 | } |
| 31 | |
| 32 | T* find(unsigned hash) |
| 33 | { |
| 34 | return _hashmap[hash & _mask]; |
| 35 | } |
| 36 | |
| 37 | protected: |
| 38 | T **_hashmap; |
| 39 | unsigned _mask; |
| 40 | }; |
| 41 | |
| 42 | #endif |