2019-12-30 20:15:19 +00:00
|
|
|
#ifndef LLARP_UTIL_DECAYING_HASHSET_HPP
|
|
|
|
#define LLARP_UTIL_DECAYING_HASHSET_HPP
|
|
|
|
|
|
|
|
#include <util/time.hpp>
|
|
|
|
#include <unordered_map>
|
|
|
|
|
|
|
|
namespace llarp
|
|
|
|
{
|
|
|
|
namespace util
|
|
|
|
{
|
2020-04-07 18:38:56 +00:00
|
|
|
template <typename Val_t, typename Hash_t = typename Val_t::Hash>
|
2019-12-30 20:15:19 +00:00
|
|
|
struct DecayingHashSet
|
|
|
|
{
|
2020-02-25 17:05:13 +00:00
|
|
|
using Time_t = std::chrono::milliseconds;
|
|
|
|
|
2020-04-07 18:38:56 +00:00
|
|
|
DecayingHashSet(Time_t cacheInterval = 5s) : m_CacheInterval(cacheInterval)
|
2019-12-30 20:15:19 +00:00
|
|
|
{
|
|
|
|
}
|
2019-12-30 22:03:19 +00:00
|
|
|
/// determine if we have v contained in our decaying hashset
|
2019-12-30 20:15:19 +00:00
|
|
|
bool
|
|
|
|
Contains(const Val_t& v) const
|
|
|
|
{
|
2020-05-21 14:23:54 +00:00
|
|
|
return m_Values.count(v) != 0;
|
2019-12-30 20:15:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// return true if inserted
|
|
|
|
/// return false if not inserted
|
|
|
|
bool
|
2020-02-24 15:26:46 +00:00
|
|
|
Insert(const Val_t& v, Time_t now = 0s)
|
2019-12-30 20:15:19 +00:00
|
|
|
{
|
2020-04-07 18:38:56 +00:00
|
|
|
if (now == 0s)
|
2020-02-25 17:05:13 +00:00
|
|
|
now = llarp::time_now_ms();
|
2020-05-21 14:23:54 +00:00
|
|
|
return m_Values.try_emplace(v, now).second;
|
2019-12-30 20:15:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// decay hashset entries
|
|
|
|
void
|
2020-02-24 15:26:46 +00:00
|
|
|
Decay(Time_t now = 0s)
|
2019-12-30 20:15:19 +00:00
|
|
|
{
|
2020-04-07 18:38:56 +00:00
|
|
|
if (now == 0s)
|
2020-02-25 17:05:13 +00:00
|
|
|
now = llarp::time_now_ms();
|
2020-05-22 19:47:42 +00:00
|
|
|
EraseIf([&](const auto& item) { return (m_CacheInterval + item.second) <= now; });
|
2019-12-30 20:15:19 +00:00
|
|
|
}
|
|
|
|
|
2020-02-24 15:26:46 +00:00
|
|
|
Time_t
|
2019-12-30 20:15:19 +00:00
|
|
|
DecayInterval() const
|
|
|
|
{
|
|
|
|
return m_CacheInterval;
|
|
|
|
}
|
|
|
|
|
2020-05-21 14:23:54 +00:00
|
|
|
bool
|
|
|
|
Empty() const
|
|
|
|
{
|
|
|
|
return m_Values.empty();
|
|
|
|
}
|
|
|
|
|
2020-01-21 17:31:48 +00:00
|
|
|
void
|
2020-02-24 15:26:46 +00:00
|
|
|
DecayInterval(Time_t interval)
|
2020-01-21 17:31:48 +00:00
|
|
|
{
|
|
|
|
m_CacheInterval = interval;
|
|
|
|
}
|
|
|
|
|
2019-12-30 20:15:19 +00:00
|
|
|
private:
|
2020-05-22 19:47:42 +00:00
|
|
|
template <typename Predicate_t>
|
|
|
|
void
|
|
|
|
EraseIf(Predicate_t pred)
|
|
|
|
{
|
|
|
|
for (auto i = m_Values.begin(), last = m_Values.end(); i != last;)
|
|
|
|
{
|
|
|
|
if (pred(*i))
|
|
|
|
{
|
|
|
|
i = m_Values.erase(i);
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
++i;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-24 15:26:46 +00:00
|
|
|
Time_t m_CacheInterval;
|
2020-04-07 18:38:56 +00:00
|
|
|
std::unordered_map<Val_t, Time_t, Hash_t> m_Values;
|
2019-12-30 20:15:19 +00:00
|
|
|
};
|
|
|
|
} // namespace util
|
|
|
|
} // namespace llarp
|
|
|
|
|
|
|
|
#endif
|