Map.hpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. #ifndef ZT_MAP_HPP
  14. #define ZT_MAP_HPP
  15. #include "Constants.hpp"
  16. #include "Utils.hpp"
  17. #ifdef __CPP11__
  18. #include <unordered_map>
  19. #else
  20. #include <map>
  21. #endif
  22. namespace ZeroTier {
  23. #ifdef __CPP11__
  24. struct _MapHasher
  25. {
  26. template<typename O>
  27. std::size_t operator()(const O &obj) const noexcept { return (std::size_t)obj.hashCode() ^ (std::size_t)Utils::s_mapNonce; }
  28. std::size_t operator()(const uint64_t i) const noexcept { return (std::size_t)Utils::hash64(i ^ Utils::s_mapNonce); }
  29. std::size_t operator()(const int64_t i) const noexcept { return (std::size_t)Utils::hash64((uint64_t)i ^ Utils::s_mapNonce); }
  30. std::size_t operator()(const uint32_t i) const noexcept { return (std::size_t)Utils::hash32(i ^ (uint32_t)Utils::s_mapNonce); }
  31. std::size_t operator()(const int32_t i) const noexcept { return (std::size_t)Utils::hash32((uint32_t)i ^ (uint32_t)Utils::s_mapNonce); }
  32. };
  33. template<typename K,typename V>
  34. class Map : public std::unordered_map<K,V,_MapHasher>
  35. {
  36. public:
  37. ZT_INLINE V *get(const K &key) noexcept
  38. {
  39. typename Map::iterator i(this->find(key));
  40. if (i == this->end())
  41. return nullptr;
  42. return &(i->second);
  43. }
  44. ZT_INLINE const V *get(const K &key) const noexcept
  45. {
  46. typename Map::const_iterator i(this->find(key));
  47. if (i == this->end())
  48. return nullptr;
  49. return &(i->second);
  50. }
  51. ZT_INLINE void set(const K &key,const V &value)
  52. {
  53. this->emplace(key,value);
  54. }
  55. };
  56. #else
  57. template<typename K,typename V>
  58. class Map : public std::map<K,V>
  59. {
  60. public:
  61. ZT_INLINE V *get(const K &key) noexcept
  62. {
  63. typename Map::iterator i(this->find(key));
  64. if (i == this->end())
  65. return nullptr;
  66. return &(i->second);
  67. }
  68. ZT_INLINE const V *get(const K &key) const noexcept
  69. {
  70. typename Map::const_iterator i(this->find(key));
  71. if (i == this->end())
  72. return nullptr;
  73. return &(i->second);
  74. }
  75. ZT_INLINE void set(const K &key,const V &value)
  76. {
  77. this->emplace(key,value);
  78. }
  79. };
  80. #endif
  81. } // ZeroTier
  82. #endif