hash_map.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. //
  6. #pragma once
  7. #include <algorithm>
  8. #include <array>
  9. #include <utility>
  10. #include "util/autovector.h"
  11. namespace ROCKSDB_NAMESPACE {
  12. // This is similar to std::unordered_map, except that it tries to avoid
  13. // allocating or deallocating memory as much as possible. With
  14. // std::unordered_map, an allocation/deallocation is made for every insertion
  15. // or deletion because of the requirement that iterators remain valid even
  16. // with insertions or deletions. This means that the hash chains will be
  17. // implemented as linked lists.
  18. //
  19. // This implementation uses autovector as hash chains insteads.
  20. //
  21. template <typename K, typename V, size_t size = 128>
  22. class HashMap {
  23. std::array<autovector<std::pair<K, V>, 1>, size> table_;
  24. public:
  25. bool Contains(K key) {
  26. auto& bucket = table_[key % size];
  27. auto it = std::find_if(
  28. bucket.begin(), bucket.end(),
  29. [key](const std::pair<K, V>& p) { return p.first == key; });
  30. return it != bucket.end();
  31. }
  32. void Insert(K key, V value) {
  33. auto& bucket = table_[key % size];
  34. bucket.push_back({key, value});
  35. }
  36. void Delete(K key) {
  37. auto& bucket = table_[key % size];
  38. auto it = std::find_if(
  39. bucket.begin(), bucket.end(),
  40. [key](const std::pair<K, V>& p) { return p.first == key; });
  41. if (it != bucket.end()) {
  42. auto last = bucket.end() - 1;
  43. if (it != last) {
  44. *it = *last;
  45. }
  46. bucket.pop_back();
  47. }
  48. }
  49. V& Get(K key) {
  50. auto& bucket = table_[key % size];
  51. auto it = std::find_if(
  52. bucket.begin(), bucket.end(),
  53. [key](const std::pair<K, V>& p) { return p.first == key; });
  54. return it->second;
  55. }
  56. };
  57. } // namespace ROCKSDB_NAMESPACE