Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | None | 0 0
  1. #include <vector>
  2.  
  3. class FixedAllocator {
  4.  public:
  5.   FixedAllocator(size_t chunk_size, size_t page_size);
  6.   void *Allocate();
  7.   void Deallocate(void *value);
  8.  
  9.  private:
  10.   size_t chunk_size;
  11.   size_t page_size;
  12.   std::vector<std::vector<unsigned char>> pool;
  13.   size_t free_memory = 0;
  14.   unsigned char *memory;
  15. };
  16.  
  17. FixedAllocator::FixedAllocator(size_t chunk_size, size_t page_size) {
  18.   this->chunk_size = chunk_size;
  19.   this->page_size = page_size;
  20. }
  21.  
  22. void *FixedAllocator::Allocate() {
  23.   if (chunk_size > free_memory) {
  24.     pool.emplace_back(page_size * chunk_size);
  25.     free_memory = pool.back().size();
  26.     memory = &pool.back().front();
  27.   }
  28.   auto front_memory = memory;
  29.   free_memory -= chunk_size;
  30.   memory += chunk_size;
  31.   return front_memory;
  32. }
  33.  
  34. void FixedAllocator::Deallocate(void *value) {
  35.   auto front_memory = (unsigned char *) value;
  36.   memory = front_memory;
  37.   free_memory += chunk_size;
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement