Files
integration/luprex/core/cpp/eng-malloc.hpp

106 lines
2.5 KiB
C++

#ifndef ENG_MALLOC_HPP
#define ENG_MALLOC_HPP
#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <sstream>
// dlmalloc is only used on linux.
extern "C" {
#ifdef __linux__
void* dlmalloc(size_t x);
void dlfree(void *p);
void* dlrealloc(void*, size_t);
#else
void* dlmalloc(size_t x) { return malloc(x); }
void dlfree(void *p) { free(p); }
void* dlrealloc(void *p, size_t x) { return realloc(p,x); }
#endif
}
// Return the current state of the dlmalloc allocator as a 30-bit hash.
extern int dlmalloc_hash();
// EngAllocator: a class meant to be used as an STL Allocator.
// Causes objects to be allocated using dlmalloc and dlfree.
template <class T>
class EngAllocator
{
public:
using value_type = T;
EngAllocator() noexcept {}
template <class U> EngAllocator(EngAllocator<U> const&) noexcept {}
value_type* allocate(std::size_t n)
{
return static_cast<value_type*>(dlmalloc(n*sizeof(value_type)));
}
void deallocate(value_type* p, std::size_t) noexcept
{
dlfree(p);
}
};
template <class T, class U>
bool operator==(EngAllocator<T> const&, EngAllocator<U> const&) noexcept
{
return true;
}
template <class T, class U>
bool operator!=(EngAllocator<T> const&, EngAllocator<U> const&) noexcept
{
return false;
}
namespace eng {
template<class T>
using hash = std::hash<T>;
template<class T>
using less = std::less<T>;
template<class T>
using equal_to = std::equal_to<T>;
template<class T>
using char_traits = std::char_traits<T>;
template<class A, class B>
using pair = std::pair<A, B>;
template<class C, class T=char_traits<C>>
using basic_string = std::basic_string<C, T, EngAllocator<C>>;
template<class C, class T=char_traits<C>>
using basic_stringstream = std::basic_stringstream<C, T, EngAllocator<C>>;
template<class T>
using vector = std::vector<T, EngAllocator<T>>;
template<class K, class V, class C=less<K>>
using map = std::map<K, V, C, EngAllocator<pair<const K, V>>>;
template<class K, class V, class H=hash<K>, class E=equal_to<K>>
using unordered_map = std::unordered_map<K, V, H, E, EngAllocator<pair<const K, V>>>;
template<class K, class C=std::less<K>>
using set = std::set<K, C, EngAllocator<K>>;
template<class K, class H=hash<K>, class E=equal_to<K>>
using unordered_set = std::unordered_set<K, H, E, EngAllocator<K>>;
using string = basic_string<char>;
using stringstream = basic_stringstream<char>;
}
#endif // ENG_MALLOC_HPP