diff --git a/shell/common/gin_helper/trackable_object.h b/shell/common/gin_helper/trackable_object.h index a4e3214418fa..3ee141e16f73 100644 --- a/shell/common/gin_helper/trackable_object.h +++ b/shell/common/gin_helper/trackable_object.h @@ -107,7 +107,7 @@ class TrackableObject : public TrackableObjectBase, public EventEmitter { // Removes this instance from the weak map. void RemoveFromWeakMap() { - if (weak_map_ && weak_map_->Has(weak_map_id())) + if (weak_map_) weak_map_->Remove(weak_map_id()); } diff --git a/shell/common/key_weak_map.h b/shell/common/key_weak_map.h index d5ab86a71569..b3e4f36675f8 100644 --- a/shell/common/key_weak_map.h +++ b/shell/common/key_weak_map.h @@ -9,24 +9,17 @@ #include #include -#include "base/containers/contains.h" #include "base/memory/raw_ptr.h" #include "v8/include/v8.h" namespace electron { -// Like ES6's WeakMap, but the key is Integer and the value is Weak Pointer. +// Like ES6's WeakMap, with a K key and Weak Pointer value. template class KeyWeakMap { public: - // Records the key and self, used by SetWeak. - struct KeyObject { - K key; - raw_ptr self; - }; - KeyWeakMap() {} - virtual ~KeyWeakMap() { + ~KeyWeakMap() { for (auto& p : map_) p.second.second.ClearWeak(); } @@ -45,23 +38,19 @@ class KeyWeakMap { // Gets the object from WeakMap by its |key|. v8::MaybeLocal Get(v8::Isolate* isolate, const K& key) { - auto iter = map_.find(key); - if (iter == map_.end()) - return v8::MaybeLocal(); - else + if (auto iter = map_.find(key); iter != map_.end()) return v8::Local::New(isolate, iter->second.second); + return {}; } - // Whether there is an object with |key| in this WeakMap. - constexpr bool Has(const K& key) const { return base::Contains(map_, key); } - // Returns all objects. std::vector> Values(v8::Isolate* isolate) const { - std::vector> keys; - keys.reserve(map_.size()); + std::vector> values; + values.reserve(map_.size()); for (const auto& it : map_) - keys.emplace_back(v8::Local::New(isolate, it.second.second)); - return keys; + values.emplace_back( + v8::Local::New(isolate, it.second.second)); + return values; } // Remove object with |key| in the WeakMap. @@ -75,6 +64,12 @@ class KeyWeakMap { } private: + // Records the key and self, used by SetWeak. + struct KeyObject { + K key; + raw_ptr self; + }; + static void OnObjectGC( const v8::WeakCallbackInfo::KeyObject>& data) { KeyWeakMap::KeyObject* key_object = data.GetParameter();