-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSingleton.cpp
More file actions
45 lines (37 loc) · 1.06 KB
/
Copy pathSingleton.cpp
File metadata and controls
45 lines (37 loc) · 1.06 KB
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
#include "Singleton.hpp"
#include <cstring>
#include <algorithm>
namespace sh::core
{
std::mutex ISingleton::mu{};
std::vector<ISingleton::InstanceInfo> ISingleton::instance{};
auto ISingleton::CreateInstance(uint64_t hash, std::size_t size) -> Result
{
std::lock_guard<std::mutex> lock{ mu };
auto it = std::find_if(instance.begin(), instance.end(), [&](const InstanceInfo& info)
{
return info.hash == hash && info.size == size;
}
);
if (it != instance.end())
return Result{ it->ptr, false };
void* ptr = ::operator new(size);
std::memset(ptr, 0, size);
instance.push_back(InstanceInfo{ hash, size, ptr });
return Result{ ptr, true };
}
void ISingleton::DeleteInstance(uint64_t hash, std::size_t size)
{
std::lock_guard<std::mutex> lock{ mu };
auto it = std::find_if(instance.begin(), instance.end(), [&](const InstanceInfo& info)
{
return info.hash == hash && info.size == size;
}
);
if (it == instance.end())
return;
void* instancePtr = it->ptr;
::operator delete(instancePtr);
instance.erase(it);
}
}//namespace