#include "packet.hpp" #include #include namespace packet { Memory::Memory() : countdown_(0) { } Memory::~Memory() { for (const Allocation& allocation : live_) { std::free(allocation.address); } } void* Memory::acquire(Kind kind, std::size_t bytes) { counters_.attempts += 1; if (countdown_ != 0) { countdown_ -= 1; if (countdown_ == 0) { counters_.failures += 1; return nullptr; } } void* address = std::malloc(bytes); if (address == nullptr) { counters_.failures += 1; return nullptr; } try { live_.push_back(Allocation{address, bytes, kind}); } catch (...) { std::free(address); throw; } counters_.allocated += 1; counters_.bytes += bytes; if (kind == Kind::Node) { counters_.nodes += 1; } else { counters_.payloads += 1; } return address; } void Memory::release(void* address) { if (address == nullptr) { return; } for (auto iterator = live_.begin(); iterator != live_.end(); ++iterator) { if (iterator->address != address) { continue; } counters_.released += 1; counters_.bytes -= iterator->bytes; if (iterator->kind == Kind::Node) { counters_.nodes -= 1; } else { counters_.payloads -= 1; } std::free(iterator->address); live_.erase(iterator); return; } counters_.invalid += 1; } void Memory::fail_after(std::uint64_t count) { countdown_ = count; } MemoryView Memory::view() const { return counters_; } }