chunked_memory_pool_output.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #include "chunked_memory_pool_output.h"
  2. #include "chunked_memory_pool.h"
  3. #include <library/cpp/yt/memory/ref.h>
  4. namespace NYT {
  5. ////////////////////////////////////////////////////////////////////////////////
  6. TChunkedMemoryPoolOutput::TChunkedMemoryPoolOutput(TChunkedMemoryPool* pool, size_t chunkSize)
  7. : Pool_(pool)
  8. , ChunkSize_(chunkSize)
  9. { }
  10. size_t TChunkedMemoryPoolOutput::DoNext(void** ptr)
  11. {
  12. // Check if the current chunk is exhausted.
  13. if (Current_ == End_) {
  14. // Emplace the (whole) last chunk, if any.
  15. if (Begin_) {
  16. Refs_.emplace_back(Begin_, Current_);
  17. }
  18. // Allocate a new chunk.
  19. // Use |AllocateAligned| to get a chance to free some memory afterwards.
  20. // Tune the number of bytes requested from the pool to try avoid allocations.
  21. auto spareSize = Pool_->GetCurrentChunkSpareSize();
  22. auto allocationSize = (spareSize == 0 ? ChunkSize_ : std::min(ChunkSize_, spareSize));
  23. Begin_ = Pool_->AllocateAligned(allocationSize, /* align */ 1);
  24. Current_ = Begin_;
  25. End_ = Begin_ + allocationSize;
  26. }
  27. // Return the unused part of the current chunk.
  28. // This could be the whole chunk allocated above.
  29. *ptr = Current_;
  30. auto size = End_ - Current_;
  31. Current_ = End_;
  32. return size;
  33. }
  34. void TChunkedMemoryPoolOutput::DoUndo(size_t size)
  35. {
  36. // Just rewind the current pointer.
  37. Current_ -= size;
  38. YT_VERIFY(Current_ >= Begin_);
  39. }
  40. std::vector<TMutableRef> TChunkedMemoryPoolOutput::Finish()
  41. {
  42. // Emplace the used part of the last chunk, if any.
  43. if (Begin_) {
  44. Refs_.emplace_back(Begin_, Current_);
  45. }
  46. // Try to free the unused part of the last chunk, if possible.
  47. if (Current_ < End_) {
  48. Pool_->Free(Current_, End_);
  49. }
  50. return std::move(Refs_);
  51. }
  52. ////////////////////////////////////////////////////////////////////////////////
  53. } // namespace NYT