key_weak_map.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright (c) 2016 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #ifndef ATOM_COMMON_KEY_WEAK_MAP_H_
  5. #define ATOM_COMMON_KEY_WEAK_MAP_H_
  6. #include <unordered_map>
  7. #include <utility>
  8. #include <vector>
  9. #include "base/macros.h"
  10. #include "v8/include/v8.h"
  11. namespace atom {
  12. // Like ES6's WeakMap, but the key is Integer and the value is Weak Pointer.
  13. template <typename K>
  14. class KeyWeakMap {
  15. public:
  16. // Records the key and self, used by SetWeak.
  17. struct KeyObject {
  18. K key;
  19. KeyWeakMap* self;
  20. };
  21. KeyWeakMap() {}
  22. virtual ~KeyWeakMap() {
  23. for (auto& p : map_)
  24. p.second.second.ClearWeak();
  25. }
  26. // Sets the object to WeakMap with the given |key|.
  27. void Set(v8::Isolate* isolate, const K& key, v8::Local<v8::Object> object) {
  28. KeyObject key_object = {key, this};
  29. auto& p = map_[key] =
  30. std::make_pair(key_object, v8::Global<v8::Object>(isolate, object));
  31. p.second.SetWeak(&(p.first), OnObjectGC, v8::WeakCallbackType::kParameter);
  32. }
  33. // Gets the object from WeakMap by its |key|.
  34. v8::MaybeLocal<v8::Object> Get(v8::Isolate* isolate, const K& key) {
  35. auto iter = map_.find(key);
  36. if (iter == map_.end())
  37. return v8::MaybeLocal<v8::Object>();
  38. else
  39. return v8::Local<v8::Object>::New(isolate, iter->second.second);
  40. }
  41. // Whethere there is an object with |key| in this WeakMap.
  42. bool Has(const K& key) const { return map_.find(key) != map_.end(); }
  43. // Returns all objects.
  44. std::vector<v8::Local<v8::Object>> Values(v8::Isolate* isolate) const {
  45. std::vector<v8::Local<v8::Object>> keys;
  46. keys.reserve(map_.size());
  47. for (const auto& it : map_)
  48. keys.emplace_back(v8::Local<v8::Object>::New(isolate, it.second.second));
  49. return keys;
  50. }
  51. // Remove object with |key| in the WeakMap.
  52. void Remove(const K& key) {
  53. auto iter = map_.find(key);
  54. if (iter == map_.end())
  55. return;
  56. iter->second.second.ClearWeak();
  57. map_.erase(iter);
  58. }
  59. private:
  60. static void OnObjectGC(
  61. const v8::WeakCallbackInfo<typename KeyWeakMap<K>::KeyObject>& data) {
  62. KeyWeakMap<K>::KeyObject* key_object = data.GetParameter();
  63. key_object->self->Remove(key_object->key);
  64. }
  65. // Map of stored objects.
  66. std::unordered_map<K, std::pair<KeyObject, v8::Global<v8::Object>>> map_;
  67. DISALLOW_COPY_AND_ASSIGN(KeyWeakMap);
  68. };
  69. } // namespace atom
  70. #endif // ATOM_COMMON_KEY_WEAK_MAP_H_