1
1
#include " node_internals.h"
2
2
#include " node_watchdog.h"
3
+ #include " base_object-inl.h"
3
4
4
5
namespace node {
5
6
namespace util {
@@ -9,8 +10,10 @@ using v8::Array;
9
10
using v8::Boolean ;
10
11
using v8::Context;
11
12
using v8::FunctionCallbackInfo;
13
+ using v8::FunctionTemplate;
12
14
using v8::IndexFilter;
13
15
using v8::Integer;
16
+ using v8::Isolate;
14
17
using v8::KeyCollectionMode;
15
18
using v8::Local;
16
19
using v8::NewStringType;
@@ -178,6 +181,37 @@ void SafeGetenv(const FunctionCallbackInfo<Value>& args) {
178
181
NewStringType::kNormal ).ToLocalChecked ());
179
182
}
180
183
184
+ class WeakReference : public BaseObject {
185
+ public:
186
+ WeakReference (Environment* env, Local<Object> object, Local<Object> target)
187
+ : BaseObject(env, object) {
188
+ MakeWeak ();
189
+ target_.Reset (env->isolate (), target);
190
+ target_.SetWeak ();
191
+ }
192
+
193
+ static void New (const FunctionCallbackInfo<Value>& args) {
194
+ Environment* env = Environment::GetCurrent (args);
195
+ CHECK (args.IsConstructCall ());
196
+ CHECK (args[0 ]->IsObject ());
197
+ new WeakReference (env, args.This (), args[0 ].As <Object>());
198
+ }
199
+
200
+ static void Get (const FunctionCallbackInfo<Value>& args) {
201
+ WeakReference* weak_ref = Unwrap<WeakReference>(args.Holder ());
202
+ Isolate* isolate = args.GetIsolate ();
203
+ if (!weak_ref->target_ .IsEmpty ())
204
+ args.GetReturnValue ().Set (weak_ref->target_ .Get (isolate));
205
+ }
206
+
207
+ SET_MEMORY_INFO_NAME (WeakReference)
208
+ SET_SELF_SIZE (WeakReference)
209
+ SET_NO_MEMORY_INFO ()
210
+
211
+ private:
212
+ Persistent<Object> target_;
213
+ };
214
+
181
215
void Initialize (Local<Object> target,
182
216
Local<Value> unused,
183
217
Local<Context> context) {
@@ -235,6 +269,16 @@ void Initialize(Local<Object> target,
235
269
target->Set (context,
236
270
FIXED_ONE_BYTE_STRING (env->isolate (), " propertyFilter" ),
237
271
constants).FromJust ();
272
+
273
+ Local<String> weak_ref_string =
274
+ FIXED_ONE_BYTE_STRING (env->isolate (), " WeakReference" );
275
+ Local<FunctionTemplate> weak_ref =
276
+ env->NewFunctionTemplate (WeakReference::New);
277
+ weak_ref->InstanceTemplate ()->SetInternalFieldCount (1 );
278
+ weak_ref->SetClassName (weak_ref_string);
279
+ env->SetProtoMethod (weak_ref, " get" , WeakReference::Get);
280
+ target->Set (context, weak_ref_string,
281
+ weak_ref->GetFunction (context).ToLocalChecked ()).FromJust ();
238
282
}
239
283
240
284
} // namespace util
0 commit comments