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
|
|
|
|
{
|
|
|
|
template < typename Val_t, typename Hash_t = typename Val_t::Hash >
|
|
|
|
struct DecayingHashSet
|
|
|
|
{
|
2020-01-30 22:10:56 +00:00
|
|
|
DecayingHashSet(Time_t cacheInterval)
|
2020-01-21 17:31:48 +00:00
|
|
|
: DecayingHashSet(cacheInterval.count())
|
|
|
|
{
|
|
|
|
}
|
2020-01-30 22:10:56 +00:00
|
|
|
explicit DecayingHashSet(llarp_time_t cacheInterval = 5000)
|
2019-12-30 20:15:19 +00:00
|
|
|
: m_CacheInterval(cacheInterval)
|
|
|
|
{
|
|
|
|
}
|
|
|
|
|
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
|
|
|
|
{
|
|
|
|
return m_Values.find(v) != m_Values.end();
|
|
|
|
}
|
|
|
|
|
|
|
|
/// return true if inserted
|
|
|
|
/// return false if not inserted
|
|
|
|
bool
|
|
|
|
Insert(const Val_t& v, llarp_time_t now = 0)
|
|
|
|
{
|
|
|
|
if(now == 0)
|
|
|
|
now = llarp::time_now_ms();
|
2020-01-21 17:31:48 +00:00
|
|
|
return m_Values.emplace(v, now).second;
|
2019-12-30 20:15:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// decay hashset entries
|
|
|
|
void
|
|
|
|
Decay(llarp_time_t now = 0)
|
|
|
|
{
|
|
|
|
if(now == 0)
|
|
|
|
now = llarp::time_now_ms();
|
|
|
|
auto itr = m_Values.begin();
|
|
|
|
while(itr != m_Values.end())
|
|
|
|
{
|
2020-01-21 17:31:48 +00:00
|
|
|
if((m_CacheInterval + itr->second) <= now)
|
2019-12-30 20:15:19 +00:00
|
|
|
itr = m_Values.erase(itr);
|
|
|
|
else
|
|
|
|
++itr;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
llarp_time_t
|
|
|
|
DecayInterval() const
|
|
|
|
{
|
|
|
|
return m_CacheInterval;
|
|
|
|
}
|
|
|
|
|
2020-01-21 17:31:48 +00:00
|
|
|
void
|
|
|
|
DecayInterval(llarp_time_t interval)
|
|
|
|
{
|
|
|
|
m_CacheInterval = interval;
|
|
|
|
}
|
|
|
|
|
2019-12-30 20:15:19 +00:00
|
|
|
private:
|
2020-01-21 17:31:48 +00:00
|
|
|
llarp_time_t m_CacheInterval;
|
2019-12-30 20:15:19 +00:00
|
|
|
std::unordered_map< Val_t, llarp_time_t, Hash_t > m_Values;
|
|
|
|
};
|
|
|
|
} // namespace util
|
|
|
|
} // namespace llarp
|
|
|
|
|
|
|
|
#endif
|