1 // Copyright 2019 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_BOXED_V8_MODULE_H_
6 #define THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_BOXED_V8_MODULE_H_
7 
8 #include "third_party/blink/renderer/core/core_export.h"
9 #include "third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h"
10 #include "third_party/blink/renderer/platform/heap/member.h"
11 #include "third_party/blink/renderer/platform/wtf/hash_functions.h"
12 #include "v8/include/v8.h"
13 
14 namespace blink {
15 
16 // BoxedV8Module wraps a handle to a v8::Module for use on heap.
17 //
18 // Hash of Member<BoxedV8Module> overrides HashTraits.
19 // Therefore, BoxedV8Module can be a key/value type of WTF::HashMap,
20 // HashSet,HashTable by using BoxedV8ModuleHash.
21 class CORE_EXPORT BoxedV8Module final : public GarbageCollected<BoxedV8Module> {
22  public:
BoxedV8Module(v8::Isolate * isolate,v8::Local<v8::Module> module)23   BoxedV8Module(v8::Isolate* isolate, v8::Local<v8::Module> module)
24       : record_(isolate, module),
25         identity_hash_(static_cast<unsigned>(module->GetIdentityHash())) {}
26 
Trace(Visitor * visitor)27   void Trace(Visitor* visitor) const {
28     // TODO(keishi): Remove UnsafeCast.
29     visitor->Trace(record_.UnsafeCast<v8::Value>());
30   }
31 
NewLocal(v8::Isolate * isolate)32   v8::Local<v8::Module> NewLocal(v8::Isolate* isolate) const {
33     return record_.NewLocal(isolate);
34   }
35 
36  private:
37   // TODO(keishi): Visitor only defines a trace method for v8::Value so this
38   // needs to be cast.
39   GC_PLUGIN_IGNORE("757708")
40   TraceWrapperV8Reference<v8::Module> record_;
41   const unsigned identity_hash_;
42   friend struct BoxedV8ModuleHash;
43 };
44 
45 struct BoxedV8ModuleHash {
46  public:
GetHashBoxedV8ModuleHash47   static unsigned GetHash(const Member<BoxedV8Module>& key) {
48     return key->identity_hash_;
49   }
50 
EqualBoxedV8ModuleHash51   static bool Equal(const Member<BoxedV8Module>& a,
52                     const Member<BoxedV8Module>& b) {
53     if (a.IsHashTableDeletedValue() && b.IsHashTableDeletedValue())
54       return true;
55     if (a.IsHashTableDeletedValue() || b.IsHashTableDeletedValue())
56       return false;
57 
58     if (!a && !b)
59       return true;
60     if (!a || !b)
61       return false;
62 
63     return a->record_ == b->record_;
64   }
65 
66   static constexpr bool safe_to_compare_to_empty_or_deleted = true;
67 };
68 
69 }  // namespace blink
70 
71 namespace WTF {
72 
73 template <>
74 struct DefaultHash<blink::Member<blink::BoxedV8Module>> {
75   using Hash = blink::BoxedV8ModuleHash;
76 };
77 
78 }  // namespace WTF
79 
80 #endif  // THIRD_PARTY_BLINK_RENDERER_BINDINGS_CORE_V8_BOXED_V8_MODULE_H_
81