key_weak_map.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 ELECTRON_SHELL_COMMON_KEY_WEAK_MAP_H_
  5. #define ELECTRON_SHELL_COMMON_KEY_WEAK_MAP_H_
  6. #include <unordered_map>
  7. #include <vector>
  8. #include "base/containers/to_vector.h"
  9. #include "base/memory/raw_ptr.h"
  10. #include "v8/include/v8-forward.h"
  11. namespace electron {
  12. // Like ES6's WeakMap, with a K key and Weak Pointer value.
  13. template <typename K>
  14. class KeyWeakMap {
  15. public:
  16. KeyWeakMap() = default;
  17. ~KeyWeakMap() {
  18. for (auto& p : map_)
  19. p.second.value.ClearWeak();
  20. }
  21. // disable copy
  22. KeyWeakMap(const KeyWeakMap&) = delete;
  23. KeyWeakMap& operator=(const KeyWeakMap&) = delete;
  24. // Sets the object to WeakMap with the given |key|.
  25. void Set(v8::Isolate* isolate, const K& key, v8::Local<v8::Object> value) {
  26. auto& mapped = map_[key] =
  27. Mapped{this, key, v8::Global<v8::Object>(isolate, value)};
  28. mapped.value.SetWeak(&mapped, OnObjectGC, v8::WeakCallbackType::kParameter);
  29. }
  30. // Gets the object from WeakMap by its |key|.
  31. v8::MaybeLocal<v8::Object> Get(v8::Isolate* isolate, const K& key) {
  32. if (auto iter = map_.find(key); iter != map_.end())
  33. return v8::Local<v8::Object>::New(isolate, iter->second.value);
  34. return {};
  35. }
  36. // Returns all objects.
  37. std::vector<v8::Local<v8::Object>> Values(v8::Isolate* isolate) const {
  38. return base::ToVector(map_, [isolate](const auto& iter) {
  39. return v8::Local<v8::Object>::New(isolate, iter.second.value);
  40. });
  41. }
  42. // Remove object with |key| in the WeakMap.
  43. void Remove(const K& key) {
  44. if (auto item = map_.extract(key))
  45. item.mapped().value.ClearWeak();
  46. }
  47. private:
  48. // Records the key and self, used by SetWeak.
  49. struct Mapped {
  50. raw_ptr<KeyWeakMap> self;
  51. K key;
  52. v8::Global<v8::Object> value;
  53. };
  54. static void OnObjectGC(const v8::WeakCallbackInfo<Mapped>& data) {
  55. auto* mapped = data.GetParameter();
  56. mapped->self->Remove(mapped->key);
  57. }
  58. // Map of stored objects.
  59. std::unordered_map<K, Mapped> map_;
  60. };
  61. } // namespace electron
  62. #endif // ELECTRON_SHELL_COMMON_KEY_WEAK_MAP_H_