Skip to content

Commit 3c8bbc5

Browse files
committed
Add WaitFreeHashMap::remove_if.
1 parent 571e9c7 commit 3c8bbc5

3 files changed

Lines changed: 42 additions & 0 deletions

File tree

‎tdutils/td/utils/WaitFreeHashMap.h‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,21 @@ class WaitFreeHashMap {
161161
}
162162
}
163163

164+
template <class F>
165+
bool remove_if(const F &f) {
166+
if (wait_free_storage_ == nullptr) {
167+
return default_map_.remove_if(f);
168+
}
169+
170+
bool is_removed = false;
171+
for (auto &it : wait_free_storage_->maps_) {
172+
if (it.remove_if(f)) {
173+
is_removed = true;
174+
}
175+
}
176+
return is_removed;
177+
}
178+
164179
size_t calc_size() const {
165180
if (wait_free_storage_ == nullptr) {
166181
return default_map_.size();

‎tdutils/td/utils/algorithm.h‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,4 +301,12 @@ bool table_remove_if(FlatHashTable<NodeT, HashT, EqT> &table, FuncT &&func) {
301301
return table.remove_if(func);
302302
}
303303

304+
template <class KeyT, class ValueT, class HashT, class EqT>
305+
class WaitFreeHashMap;
306+
307+
template <class KeyT, class ValueT, class HashT, class EqT, class FuncT>
308+
bool table_remove_if(WaitFreeHashMap<KeyT, ValueT, HashT, EqT> &table, const FuncT &func) {
309+
return table.remove_if(func);
310+
}
311+
304312
} // namespace td

‎tdutils/test/WaitFreeHashMap.cpp‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,3 +93,22 @@ TEST(WaitFreeHashMap, stress_test) {
9393
}
9494
}
9595
}
96+
97+
TEST(WaitFreeHashMap, remove_if) {
98+
td::WaitFreeHashMap<td::uint64, td::uint64> map;
99+
bool is_removed;
100+
for (td::uint64 i = 0; i < 10000; i++) {
101+
map[2 * i + 1] = 0;
102+
map[2 * i + 2] = 1;
103+
is_removed = map.remove_if([i](const auto &num) { return num.first <= i; });
104+
CHECK(!is_removed);
105+
CHECK(map.calc_size() == i + 2);
106+
is_removed = map.remove_if([i](const auto &num) { return num.first <= i + 1; });
107+
CHECK(is_removed);
108+
CHECK(map.calc_size() == i + 1);
109+
}
110+
is_removed = map.remove_if([](const auto &num) { return num.first <= 19999; });
111+
CHECK(map.calc_size() == 1);
112+
is_removed = map.remove_if([](const auto &num) { return num.first <= 20000; });
113+
CHECK(map.calc_size() == 0);
114+
}

0 commit comments

Comments
 (0)