i2pd/libi2pd/util.h

128 lines
2.4 KiB
C
Raw Normal View History

2014-01-30 03:28:07 +00:00
#ifndef UTIL_H
#define UTIL_H
#include <string>
2017-01-12 00:45:04 +00:00
#include <functional>
#include <memory>
2017-01-16 20:40:01 +00:00
#include <mutex>
2014-10-31 18:17:52 +00:00
#include <boost/asio.hpp>
#ifdef ANDROID
#include <boost/lexical_cast.hpp>
namespace std
{
template <typename T>
std::string to_string(T value)
{
return boost::lexical_cast<std::string>(value);
}
2016-10-26 20:19:32 +00:00
inline int stoi(const std::string& str)
{
return boost::lexical_cast<int>(str);
}
}
#endif
2014-01-30 03:28:07 +00:00
namespace i2p
{
namespace util
{
2017-01-10 21:14:18 +00:00
template<class T>
class MemoryPool
{
public:
MemoryPool (): m_Head (nullptr) {};
~MemoryPool ()
{
while (m_Head)
{
auto tmp = m_Head;
m_Head = static_cast<T*>(*(void * *)m_Head); // next
delete tmp;
}
}
template<typename... TArgs>
2017-01-12 00:45:04 +00:00
T * Acquire (TArgs&&... args)
2017-01-10 21:14:18 +00:00
{
if (!m_Head) return new T(args...);
else
{
auto tmp = m_Head;
m_Head = static_cast<T*>(*(void * *)m_Head); // next
return new (tmp)T(args...);
}
}
void Release (T * t)
{
2017-01-11 02:31:52 +00:00
if (!t) return;
2017-01-10 21:14:18 +00:00
t->~T ();
2017-01-11 02:31:52 +00:00
*(void * *)t = m_Head; // next
2017-01-10 21:14:18 +00:00
m_Head = t;
}
2017-01-12 00:45:04 +00:00
template<typename... TArgs>
std::unique_ptr<T, std::function<void(T*)> > AcquireUnique (TArgs&&... args)
{
return std::unique_ptr<T, std::function<void(T*)> >(Acquire (args...),
std::bind (&MemoryPool<T>::Release, this, std::placeholders::_1));
}
2017-01-19 15:20:34 +00:00
template<typename... TArgs>
std::shared_ptr<T> AcquireShared (TArgs&&... args)
{
return std::shared_ptr<T>(Acquire (args...), std::bind (&MemoryPool<T>::Release, this, std::placeholders::_1));
}
2017-01-16 20:40:01 +00:00
protected:
2017-01-10 21:14:18 +00:00
T * m_Head;
};
2017-01-16 20:40:01 +00:00
template<class T>
class MemoryPoolMt: public MemoryPool<T>
{
public:
MemoryPoolMt () {};
template<typename... TArgs>
T * AcquireMt (TArgs&&... args)
{
if (!this->m_Head) return new T(args...);
std::lock_guard<std::mutex> l(m_Mutex);
return this->Acquire (args...);
}
void ReleaseMt (T * t)
{
std::lock_guard<std::mutex> l(m_Mutex);
this->Release (t);
}
template<template<typename, typename...>class C, typename... R>
void ReleaseMt(const C<T *, R...>& c)
{
std::lock_guard<std::mutex> l(m_Mutex);
for (auto& it: c)
this->Release (it);
}
private:
std::mutex m_Mutex;
};
2014-10-31 18:17:52 +00:00
namespace net
{
int GetMTU (const boost::asio::ip::address& localAddress);
2016-06-29 15:06:51 +00:00
const boost::asio::ip::address GetInterfaceAddress(const std::string & ifname, bool ipv6=false);
2014-10-31 18:17:52 +00:00
}
2014-01-30 03:28:07 +00:00
}
}
#endif