pool.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #include "pool.h"
  2. TMemoryPool::IGrowPolicy* TMemoryPool::TLinearGrow::Instance() noexcept {
  3. return SingletonWithPriority<TLinearGrow, 0>();
  4. }
  5. TMemoryPool::IGrowPolicy* TMemoryPool::TExpGrow::Instance() noexcept {
  6. return SingletonWithPriority<TExpGrow, 0>();
  7. }
  8. void TMemoryPool::AddChunk(size_t hint) {
  9. const size_t dataLen = Max(BlockSize_, hint);
  10. size_t allocSize = dataLen + sizeof(TChunk);
  11. if (Options_.RoundUpToNextPowerOfTwo) {
  12. allocSize = FastClp2(allocSize);
  13. }
  14. TBlock nb = Alloc_->Allocate(allocSize);
  15. // Add previous chunk's stats
  16. if (Current_ != &Empty_) {
  17. MemoryAllocatedBeforeCurrent_ += Current_->Used();
  18. MemoryWasteBeforeCurrent_ += Current_->Left();
  19. }
  20. BlockSize_ = GrowPolicy_->Next(dataLen);
  21. Current_ = new (nb.Data) TChunk(nb.Len - sizeof(TChunk));
  22. Chunks_.PushBack(Current_);
  23. }
  24. size_t TMemoryPool::DoClear(bool keepfirst) noexcept {
  25. size_t chunksUsed = 0;
  26. while (!Chunks_.Empty()) {
  27. chunksUsed += 1;
  28. TChunk* c = Chunks_.PopBack();
  29. if (keepfirst && Chunks_.Empty()) {
  30. c->ResetChunk();
  31. Chunks_.PushBack(c);
  32. Current_ = c;
  33. BlockSize_ = c->BlockLength() - sizeof(TChunk);
  34. MemoryAllocatedBeforeCurrent_ = 0;
  35. MemoryWasteBeforeCurrent_ = 0;
  36. return chunksUsed;
  37. }
  38. TBlock b = {c, c->BlockLength()};
  39. c->~TChunk();
  40. Alloc_->Release(b);
  41. }
  42. Current_ = &Empty_;
  43. BlockSize_ = Origin_;
  44. MemoryAllocatedBeforeCurrent_ = 0;
  45. MemoryWasteBeforeCurrent_ = 0;
  46. return chunksUsed;
  47. }