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

View File

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