HashMap.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #ifndef HASHMAP_H
  2. #define HASHMAP_H
  3. #include "common/utils/Types.h"
  4. template<typename K, typename V, uint L>
  5. class HashMap final {
  6. public:
  7. HashMap(K emptyKey, V emptyValue) : entries(0), emptyKey(emptyKey), emptyValue(emptyValue) {
  8. for(uint i = 0; i < LENGTH; i++) {
  9. data[i].key = emptyKey;
  10. data[i].value = emptyValue;
  11. }
  12. }
  13. static constexpr uint getCapacity() {
  14. return LENGTH;
  15. }
  16. void add(const K key, const V value) {
  17. if(entries >= L) {
  18. return;
  19. }
  20. uint hash = hashCode(key) % LENGTH;
  21. while(true) {
  22. if(data[hash].key == key) {
  23. data[hash].value = value;
  24. return;
  25. } else if(data[hash].key == emptyKey) {
  26. data[hash].key = key;
  27. data[hash].value = value;
  28. entries++;
  29. return;
  30. }
  31. hash = (hash + 1) % LENGTH;
  32. }
  33. }
  34. V search(const K key) const {
  35. uint hash = hashCode(key) % LENGTH;
  36. while(true) {
  37. if(data[hash].key == key) {
  38. return data[hash].value;
  39. } else if(data[hash].key == emptyKey) {
  40. return emptyValue;
  41. }
  42. hash = (hash + 1) % LENGTH;
  43. }
  44. }
  45. void forEach(void (*f)(const K&, V&)) {
  46. for(uint i = 0; i < LENGTH; i++) {
  47. if(data[i].key != emptyKey) {
  48. f(data[i].key, data[i].value);
  49. }
  50. }
  51. }
  52. private:
  53. static constexpr uint getLength() {
  54. constexpr uint SIZE_TABLE[] = {
  55. 2, 3, 7, 11, 23, 43, 89, 173, 347, 683, 1367, 2731, 5471, 10937, 21851, 43691, 87383, 174763, 349529, 699053,
  56. 1398107, 2796203, 5592407, 11184829, 22369661, 44739259, 89478503, 178956983, 357913951, 715827883, 1431655777,
  57. 2863311551
  58. };
  59. uint i = 0;
  60. while(SIZE_TABLE[i] < L) {
  61. i++;
  62. }
  63. return SIZE_TABLE[i];
  64. }
  65. template<typename H>
  66. uint hashCode(const H& h) const {
  67. return h.hashCode();
  68. }
  69. uint hashCode(const uint& h) const {
  70. return h;
  71. }
  72. static constexpr uint LENGTH = getLength();
  73. uint entries;
  74. K emptyKey;
  75. V emptyValue;
  76. struct KeyValuePair {
  77. K key;
  78. V value;
  79. };
  80. KeyValuePair data[LENGTH];
  81. };
  82. #endif