#ifndef HOARD_MANAGEONESUPERBLOCK_H
#define HOARD_MANAGEONESUPERBLOCK_H
#define likely(x) (x)
#define unlikely(x) __builtin_expect(!!(x), 0)
namespace Hoard {
template <class SuperHeap>
class ManageOneSuperblock : public SuperHeap {
public:
ManageOneSuperblock()
: _current (nullptr)
{}
typedef typename SuperHeap::SuperblockType SuperblockType;
inline void * malloc (size_t sz) {
if (likely(_current)) {
void * ptr = _current->malloc (sz);
if (ptr) {
assert (_current->getSize(ptr) >= sz);
return ptr;
}
}
return slowMallocPath (sz);
}
inline void free (void * ptr) {
SuperblockType * s = SuperHeap::getSuperblock (ptr);
if (likely(s == _current)) {
_current->free (ptr);
} else {
SuperHeap::free (ptr);
}
}
SuperblockType * get() {
if (likely(_current)) {
SuperblockType * s = _current;
_current = nullptr;
return s;
} else {
return SuperHeap::get();
}
}
inline void put (SuperblockType * s) {
if (!s || (s == _current) || (!s->isValidSuperblock())) {
return;
}
if (_current) {
SuperHeap::put (_current);
}
_current = s;
}
private:
void * slowMallocPath (size_t sz) {
void * ptr = nullptr;
while (!ptr) {
if (!_current) {
_current = SuperHeap::get();
if (!_current) {
return nullptr;
}
}
ptr = _current->malloc (sz);
if (!ptr) {
SuperHeap::put (_current);
_current = nullptr;
}
}
return ptr;
}
SuperblockType * _current;
};
}
#endif