Keep sorted state when transmitting id maps

This commit is contained in:
Maxime Coste 2015-09-16 22:29:19 +01:00
parent 36828e6059
commit bab95491c8
2 changed files with 19 additions and 9 deletions

View File

@ -36,11 +36,16 @@ public:
IdMap(std::initializer_list<Element> val) IdMap(std::initializer_list<Element> val)
: m_content{val}, : m_content{val},
m_sorted(std::is_sorted(begin(), end(), m_sorted(std::is_sorted(begin(), end(), cmp_hashes))
[](const Element& lhs, const Element& rhs)
{ return lhs.hash < rhs.hash; }))
{} {}
bool sorted() const { return m_sorted; }
void assume_sorted()
{
kak_assert(std::is_sorted(begin(), end(), cmp_hashes));
m_sorted = true;
}
void append(const Element& value, bool keep_sorted = false) void append(const Element& value, bool keep_sorted = false)
{ {
if (keep_sorted and m_sorted) if (keep_sorted and m_sorted)
@ -61,9 +66,7 @@ public:
{ {
if (keep_sorted and m_sorted) if (keep_sorted and m_sorted)
{ {
auto it = std::lower_bound(begin(), end(), value.hash, auto it = std::lower_bound(begin(), end(), value, cmp_hashes);
[](const Element& e, size_t hash)
{ return e.hash < hash; });
m_content.insert(it, std::move(value)); m_content.insert(it, std::move(value));
} }
else else
@ -143,9 +146,7 @@ public:
void sort() void sort()
{ {
std::sort(begin(), end(), std::sort(begin(), end(), cmp_hashes);
[](const Element& lhs, const Element& rhs)
{ return lhs.hash < rhs.hash; });
m_sorted = true; m_sorted = true;
} }
@ -164,6 +165,11 @@ public:
const_iterator end() const { return m_content.end(); } const_iterator end() const { return m_content.end(); }
private: private:
static bool cmp_hashes(const Element& lhs, const Element& rhs)
{
return lhs.hash < rhs.hash;
}
container_type m_content; container_type m_content;
bool m_sorted; bool m_sorted;
}; };

View File

@ -89,6 +89,7 @@ public:
void write(const IdMap<Val, domain>& map) void write(const IdMap<Val, domain>& map)
{ {
write<uint32_t>(map.size()); write<uint32_t>(map.size());
write<bool>(map.sorted());
for (auto& val : map) for (auto& val : map)
{ {
write(val.key); write(val.key);
@ -220,6 +221,7 @@ template<typename Val, MemoryDomain domain>
IdMap<Val, domain> read_idmap(int socket) IdMap<Val, domain> read_idmap(int socket)
{ {
uint32_t size = read<uint32_t>(socket); uint32_t size = read<uint32_t>(socket);
bool sorted = read<bool>(socket);
IdMap<Val, domain> res; IdMap<Val, domain> res;
res.reserve(size); res.reserve(size);
while (size--) while (size--)
@ -228,6 +230,8 @@ IdMap<Val, domain> read_idmap(int socket)
auto val = read<Val>(socket); auto val = read<Val>(socket);
res.append({std::move(key), std::move(val)}); res.append({std::move(key), std::move(val)});
} }
if (sorted)
res.assume_sorted();
return res; return res;
} }