2015-06-24 13:22:09 +08:00
|
|
|
// Copyright (c) 2015 GitHub, Inc.
|
|
|
|
// Use of this source code is governed by the MIT license that can be
|
|
|
|
// found in the LICENSE file.
|
|
|
|
|
|
|
|
#ifndef ATOM_COMMON_ID_WEAK_MAP_H_
|
|
|
|
#define ATOM_COMMON_ID_WEAK_MAP_H_
|
|
|
|
|
|
|
|
#include <unordered_map>
|
|
|
|
#include <vector>
|
|
|
|
|
|
|
|
#include "base/memory/linked_ptr.h"
|
|
|
|
#include "v8/include/v8.h"
|
|
|
|
|
|
|
|
namespace atom {
|
|
|
|
|
|
|
|
// Like ES6's WeakMap, but the key is Integer and the value is Weak Pointer.
|
2016-05-11 13:40:33 +09:00
|
|
|
class KeyWeakMap {
|
2015-06-24 13:22:09 +08:00
|
|
|
public:
|
2016-05-11 14:26:32 +09:00
|
|
|
// Records the key and self, used by SetWeak.
|
|
|
|
struct KeyObject {
|
|
|
|
int32_t key;
|
|
|
|
KeyWeakMap* self;
|
|
|
|
};
|
|
|
|
|
2016-05-11 13:40:33 +09:00
|
|
|
KeyWeakMap();
|
|
|
|
virtual ~KeyWeakMap();
|
2015-06-24 13:22:09 +08:00
|
|
|
|
2015-10-28 21:29:46 +05:30
|
|
|
// Sets the object to WeakMap with the given |id|.
|
|
|
|
void Set(v8::Isolate* isolate, int32_t id, v8::Local<v8::Object> object);
|
|
|
|
|
2015-06-24 13:22:09 +08:00
|
|
|
// Gets the object from WeakMap by its |id|.
|
|
|
|
v8::MaybeLocal<v8::Object> Get(v8::Isolate* isolate, int32_t id);
|
|
|
|
|
|
|
|
// Whethere there is an object with |id| in this WeakMap.
|
|
|
|
bool Has(int32_t id) const;
|
|
|
|
|
2015-06-24 16:54:20 +08:00
|
|
|
// Returns all objects.
|
|
|
|
std::vector<v8::Local<v8::Object>> Values(v8::Isolate* isolate);
|
|
|
|
|
2015-06-24 13:22:09 +08:00
|
|
|
// Remove object with |id| in the WeakMap.
|
|
|
|
void Remove(int32_t key);
|
|
|
|
|
2016-05-11 13:40:33 +09:00
|
|
|
private:
|
|
|
|
// Map of stored objects.
|
2016-05-11 14:26:32 +09:00
|
|
|
std::unordered_map<
|
|
|
|
int32_t,
|
|
|
|
std::pair<KeyObject, linked_ptr<v8::Global<v8::Object>>>> map_;
|
2016-05-11 13:40:33 +09:00
|
|
|
|
|
|
|
DISALLOW_COPY_AND_ASSIGN(KeyWeakMap);
|
|
|
|
};
|
|
|
|
|
|
|
|
// Provides key increments service in addition to KeyWeakMap.
|
|
|
|
class IDWeakMap : public KeyWeakMap {
|
|
|
|
public:
|
|
|
|
IDWeakMap();
|
|
|
|
~IDWeakMap() override;
|
|
|
|
|
|
|
|
// Adds |object| to WeakMap and returns its allocated |id|.
|
|
|
|
int32_t Add(v8::Isolate* isolate, v8::Local<v8::Object> object);
|
|
|
|
|
2015-06-24 13:22:09 +08:00
|
|
|
private:
|
|
|
|
// Returns next available ID.
|
2015-06-24 13:35:39 +08:00
|
|
|
int32_t GetNextID();
|
2015-06-24 13:22:09 +08:00
|
|
|
|
|
|
|
// ID of next stored object.
|
|
|
|
int32_t next_id_;
|
|
|
|
|
|
|
|
DISALLOW_COPY_AND_ASSIGN(IDWeakMap);
|
|
|
|
};
|
|
|
|
|
|
|
|
} // namespace atom
|
|
|
|
|
|
|
|
#endif // ATOM_COMMON_ID_WEAK_MAP_H_
|