#include "atom/common/api/atom_api_id_weak_map.h"
-#include <algorithm>
-
-#include "base/logging.h"
#include "native_mate/constructor.h"
#include "native_mate/object_template_builder.h"
namespace api {
-IDWeakMap::IDWeakMap()
- : next_id_(0) {
+IDWeakMap::IDWeakMap() {
}
IDWeakMap::~IDWeakMap() {
}
int32_t IDWeakMap::Add(v8::Isolate* isolate, v8::Local<v8::Object> object) {
- int32_t key = GetNextID();
- object->SetHiddenValue(mate::StringToV8(isolate, "IDWeakMapKey"),
- mate::Converter<int32_t>::ToV8(isolate, key));
-
- map_[key] = new mate::RefCountedPersistent<v8::Object>(isolate, object);
- map_[key]->SetWeak(this, WeakCallback);
- return key;
+ return map_.Add(isolate, object);
}
v8::Local<v8::Value> IDWeakMap::Get(v8::Isolate* isolate, int32_t key) {
- if (!Has(key)) {
- node::ThrowError(isolate, "Invalid key");
+ v8::MaybeLocal<v8::Object> result = map_.Get(isolate, key);
+ if (result.IsEmpty()) {
+ isolate->ThrowException(v8::Exception::Error(
+ mate::StringToV8(isolate, "Invalid key")));
return v8::Undefined(isolate);
+ } else {
+ return result.ToLocalChecked();
}
-
- return map_[key]->NewHandle();
}
bool IDWeakMap::Has(int32_t key) const {
- return map_.find(key) != map_.end();
+ return map_.Has(key);
}
std::vector<int32_t> IDWeakMap::Keys() const {
- std::vector<int32_t> keys;
- keys.reserve(map_.size());
- for (auto it = map_.begin(); it != map_.end(); ++it)
- keys.push_back(it->first);
- return keys;
+ return map_.Keys();
}
void IDWeakMap::Remove(int32_t key) {
- if (Has(key))
- map_.erase(key);
- else
- LOG(WARNING) << "Object with key " << key << " is being GCed for twice.";
-}
-
-int IDWeakMap::GetNextID() {
- return ++next_id_;
+ map_.Remove(key);
}
// static
.SetMethod("remove", &IDWeakMap::Remove);
}
-// static
-void IDWeakMap::WeakCallback(
- const v8::WeakCallbackData<v8::Object, IDWeakMap>& data) {
- int32_t key = data.GetValue()->GetHiddenValue(
- mate::StringToV8(data.GetIsolate(), "IDWeakMapKey"))->Int32Value();
- data.GetParameter()->Remove(key);
-}
-
} // namespace api
} // namespace atom
isolate,
"IDWeakMap",
base::Bind(&mate::NewOperatorFactory<IDWeakMap>));
- exports->Set(mate::StringToV8(isolate, "IDWeakMap"), constructor);
+ exports->Set(mate::StringToSymbol(isolate, "IDWeakMap"), constructor);
}
} // namespace
#ifndef ATOM_COMMON_API_ATOM_API_ID_WEAK_MAP_H_
#define ATOM_COMMON_API_ATOM_API_ID_WEAK_MAP_H_
-#include <map>
#include <vector>
-#include "base/basictypes.h"
-#include "native_mate/scoped_persistent.h"
+#include "atom/common/id_weak_map.h"
#include "native_mate/wrappable.h"
namespace atom {
bool Has(int32_t key) const;
std::vector<int32_t> Keys() const;
void Remove(int32_t key);
- int GetNextID();
- static void WeakCallback(
- const v8::WeakCallbackData<v8::Object, IDWeakMap>& data);
-
- int32_t next_id_;
-
- typedef scoped_refptr<mate::RefCountedPersistent<v8::Object> >
- RefCountedV8Object;
- std::map<int32_t, RefCountedV8Object> map_;
+ atom::IDWeakMap map_;
DISALLOW_COPY_AND_ASSIGN(IDWeakMap);
};