forked from aseprite/aseprite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobject.cpp
112 lines (94 loc) · 2.21 KB
/
object.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// Aseprite Document Library
// Copyright (C) 2019-2022 Igara Studio S.A.
// Copyright (C) 2001-2016 David Capello
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "doc/object.h"
#include "base/debug.h"
#include <map>
#include <mutex>
namespace doc {
static std::mutex g_mutex;
static ObjectId newId = 0;
// TODO Profile this and see if an unordered_map is better
static std::map<ObjectId, Object*> objects;
Object::Object(ObjectType type)
: m_type(type)
, m_id(0)
, m_version(0)
{
}
Object::Object(const Object& other)
: m_type(other.m_type)
, m_id(0) // We don't copy the ID
, m_version(0) // We don't copy the version
{
}
Object::~Object()
{
if (m_id)
setId(0);
}
int Object::getMemSize() const
{
return sizeof(Object);
}
const ObjectId Object::id() const
{
// The first time the ID is request, we store the object in the
// "objects" hash table.
if (!m_id) {
std::lock_guard lock(g_mutex);
m_id = ++newId;
objects.insert(std::make_pair(m_id, const_cast<Object*>(this)));
}
return m_id;
}
void Object::setId(ObjectId id)
{
std::lock_guard lock(g_mutex);
if (m_id) {
auto it = objects.find(m_id);
ASSERT(it != objects.end());
ASSERT(it->second == this);
if (it != objects.end())
objects.erase(it);
}
m_id = id;
if (m_id) {
#ifdef _DEBUG
if (objects.find(m_id) != objects.end()) {
Object* obj = objects.find(m_id)->second;
if (obj) {
TRACEARGS("ASSERT FAILED: Object with id", m_id,
"of kind", int(obj->type()),
"version", obj->version(), "should not exist");
}
else {
TRACEARGS("ASSERT FAILED: Object with id", m_id,
"registered as nullptr should not exist");
}
}
ASSERT(objects.find(m_id) == objects.end());
#endif
objects.insert(std::make_pair(m_id, this));
}
}
void Object::setVersion(ObjectVersion version)
{
m_version = version;
}
Object* get_object(ObjectId id)
{
std::lock_guard lock(g_mutex);
auto it = objects.find(id);
if (it != objects.end())
return it->second;
else
return nullptr;
}
} // namespace doc