Skip to content

Commit

Permalink
Added index_map::upsert
Browse files Browse the repository at this point in the history
  • Loading branch information
ltjax committed Jan 15, 2021
1 parent a6983a5 commit 68a6ad6
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
26 changes: 26 additions & 0 deletions include/replay/index_map.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,32 @@ template <class T> class index_map
insert(value.first, value.second);
}

/** Insert or update an value.
*/
template <class InitializerType>
void upsert(key_type const& key, InitializerType&& value)
{
// Make sure the arrays are big enough
size_to_include(key);

if (element_initialized(key))
{
buffer_[key] = std::move(value);
return;
}

new (buffer_ + key) mapped_type(std::forward<InitializerType>(value));

++size_;
mask_[key / bits_per_mask] |= mask_element_type{ 1 } << (key % bits_per_mask);

if (key >= smallest_key_bound_)
{
smallest_key_bound_ = key + 1;
}

}

template <class InitializerType>
void insert(key_type const& key, InitializerType&& value)
{
Expand Down
19 changes: 17 additions & 2 deletions test/index_map.t.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ namespace
{
struct sample_payload
{
std::uint8_t key;
double value;
std::uint8_t key=0;
double value=0.0;
};

bool operator==(sample_payload const& lhs, sample_payload const& rhs)
Expand Down Expand Up @@ -338,3 +338,18 @@ TEST_CASE("clear() does not change capacity")
many.clear();
REQUIRE(many.capacity() == capacity_before);
}

TEST_CASE("upsert()", "[index_map]")
{
auto many = multi_element_sample();
SECTION("inserts_if_key_does_not_exist")
{
many.upsert(17, sample_payload{});
REQUIRE(many.size() == 5);
}
SECTION("updates_if_key_exists")
{
many.upsert(11, sample_payload{});
REQUIRE(many[11].value == 0.0);
}
}

0 comments on commit 68a6ad6

Please sign in to comment.