limiting_allocator.cpp 934 B

1234567891011121314151617181920212223242526272829303132333435
  1. #include "limiting_allocator.h"
  2. #include <util/memory/pool.h>
  3. #include <util/generic/yexception.h>
  4. namespace {
  5. class TLimitingAllocator : public IAllocator {
  6. public:
  7. TLimitingAllocator(size_t limit, IAllocator* allocator) : Alloc_(allocator), Limit_(limit) {};
  8. TBlock Allocate(size_t len) override final {
  9. if (Allocated_ + len > Limit_) {
  10. throw std::runtime_error("Out of memory");
  11. }
  12. Allocated_ += len;
  13. return Alloc_->Allocate(len);
  14. }
  15. void Release(const TBlock& block) override final {
  16. Y_ENSURE(Allocated_ >= block.Len);
  17. Allocated_ -= block.Len;
  18. Alloc_->Release(block);
  19. }
  20. private:
  21. IAllocator* Alloc_;
  22. size_t Allocated_ = 0;
  23. const size_t Limit_;
  24. };
  25. }
  26. namespace NYql {
  27. std::unique_ptr<IAllocator> MakeLimitingAllocator(size_t limit, IAllocator* underlying) {
  28. return std::make_unique<TLimitingAllocator>(limit, underlying);
  29. }
  30. }