forked from tiltedphoques/TiltedEvolution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStringCache.cpp
116 lines (89 loc) · 2.48 KB
/
StringCache.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
113
114
115
116
#include <StringCache.h>
#include <iostream>
bool StringCache::Contains(const TiltedPhoques::String& acValue) const noexcept
{
return m_stringToId.contains(acValue);
}
std::optional<uint32_t> StringCache::operator[](const TiltedPhoques::String& acValue) const noexcept
{
if (const auto itor = m_stringToId.find(acValue); itor != std::end(m_stringToId))
return itor->second;
return std::nullopt;
}
std::optional<const TiltedPhoques::String> StringCache::operator[](uint32_t aValue) const noexcept
{
if (aValue < m_idToString.size())
return m_idToString[aValue];
return std::nullopt;
}
uint32_t StringCache::Add(const TiltedPhoques::String& acValue) noexcept
{
if (auto id = this->operator[](acValue))
return *id;
const auto allocatedId = m_idToString.size();
m_stringToId[acValue] = allocatedId & 0xFFFFFFFF;
m_idToString.push_back(acValue);
return allocatedId;
}
void StringCache::AddWanted(const TiltedPhoques::String& acValue) noexcept
{
m_wantedStrings.insert(acValue);
}
size_t StringCache::Size() const noexcept
{
return m_idToString.size();
}
StringCacheUpdate StringCache::Serialize(uint32_t& aStartId) const noexcept
{
StringCacheUpdate update;
update.StartId = aStartId;
if (aStartId < m_idToString.size())
{
auto itor = std::begin(m_idToString);
std::advance(itor, aStartId);
update.Values.insert(std::begin(update.Values), itor, std::end(m_idToString));
aStartId = m_idToString.size();
}
return update;
}
void StringCache::Deserialize(const StringCacheUpdate& aMessage) noexcept
{
// We should only receive contiguous updates
assert(aMessage.StartId == m_idToString.size());
for (auto& value : aMessage.Values)
{
const auto expectedId = m_idToString.size();
auto id = Add(value);
assert(id == expectedId);
}
}
void StringCache::Clear() noexcept
{
m_idToString.clear();
m_wantedStrings.clear();
m_stringToId.clear();
}
bool StringCache::ProcessDirty() noexcept
{
if (m_wantedStrings.empty())
return false;
for (auto& s : m_wantedStrings)
Add(s);
ClearDirty();
return true;
}
void StringCache::ClearDirty() noexcept
{
m_wantedStrings.clear();
}
StringCache& StringCache::Get() noexcept
{
TiltedPhoques::ScopedAllocator _{TiltedPhoques::Allocator::GetDefault()};
{
static StringCache s_instance;
return s_instance;
}
}
StringCache::StringCache()
{
}