1
1
#include " node_errors.h"
2
2
#include " node_watchdog.h"
3
3
#include " util.h"
4
+ #include " base_object-inl.h"
4
5
5
6
namespace node {
6
7
namespace util {
@@ -11,6 +12,7 @@ using v8::Boolean;
11
12
using v8::Context;
12
13
using v8::Function;
13
14
using v8::FunctionCallbackInfo;
15
+ using v8::FunctionTemplate;
14
16
using v8::IndexFilter;
15
17
using v8::Integer;
16
18
using v8::Isolate;
@@ -181,6 +183,37 @@ void EnqueueMicrotask(const FunctionCallbackInfo<Value>& args) {
181
183
isolate->EnqueueMicrotask (args[0 ].As <Function>());
182
184
}
183
185
186
+ class WeakReference : public BaseObject {
187
+ public:
188
+ WeakReference (Environment* env, Local<Object> object, Local<Object> target)
189
+ : BaseObject(env, object) {
190
+ MakeWeak ();
191
+ target_.Reset (env->isolate (), target);
192
+ target_.SetWeak ();
193
+ }
194
+
195
+ static void New (const FunctionCallbackInfo<Value>& args) {
196
+ Environment* env = Environment::GetCurrent (args);
197
+ CHECK (args.IsConstructCall ());
198
+ CHECK (args[0 ]->IsObject ());
199
+ new WeakReference (env, args.This (), args[0 ].As <Object>());
200
+ }
201
+
202
+ static void Get (const FunctionCallbackInfo<Value>& args) {
203
+ WeakReference* weak_ref = Unwrap<WeakReference>(args.Holder ());
204
+ Isolate* isolate = args.GetIsolate ();
205
+ if (!weak_ref->target_ .IsEmpty ())
206
+ args.GetReturnValue ().Set (weak_ref->target_ .Get (isolate));
207
+ }
208
+
209
+ SET_MEMORY_INFO_NAME (WeakReference)
210
+ SET_SELF_SIZE (WeakReference)
211
+ SET_NO_MEMORY_INFO ()
212
+
213
+ private:
214
+ Persistent<Object> target_;
215
+ };
216
+
184
217
void Initialize (Local<Object> target,
185
218
Local<Value> unused,
186
219
Local<Context> context,
@@ -241,6 +274,16 @@ void Initialize(Local<Object> target,
241
274
should_abort_on_uncaught_toggle,
242
275
env->should_abort_on_uncaught_toggle ().GetJSArray ())
243
276
.FromJust ());
277
+
278
+ Local<String> weak_ref_string =
279
+ FIXED_ONE_BYTE_STRING (env->isolate (), " WeakReference" );
280
+ Local<FunctionTemplate> weak_ref =
281
+ env->NewFunctionTemplate (WeakReference::New);
282
+ weak_ref->InstanceTemplate ()->SetInternalFieldCount (1 );
283
+ weak_ref->SetClassName (weak_ref_string);
284
+ env->SetProtoMethod (weak_ref, " get" , WeakReference::Get);
285
+ target->Set (context, weak_ref_string,
286
+ weak_ref->GetFunction (context).ToLocalChecked ()).FromJust ();
244
287
}
245
288
246
289
} // namespace util
0 commit comments