chunked_output_stream.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #pragma once
  2. #include "blob.h"
  3. #include <library/cpp/yt/memory/ref.h>
  4. #include <util/stream/zerocopy_output.h>
  5. #include <util/generic/size_literals.h>
  6. namespace NYT {
  7. ////////////////////////////////////////////////////////////////////////////////
  8. struct TDefaultChunkedOutputStreamTag
  9. { };
  10. class TChunkedOutputStream
  11. : public IZeroCopyOutput
  12. {
  13. public:
  14. explicit TChunkedOutputStream(
  15. TRefCountedTypeCookie tagCookie = GetRefCountedTypeCookie<TDefaultChunkedOutputStreamTag>(),
  16. size_t initialReserveSize = 4_KB,
  17. size_t maxReserveSize = 64_KB);
  18. TChunkedOutputStream(TChunkedOutputStream&&) = default;
  19. TChunkedOutputStream& operator=(TChunkedOutputStream&&) = default;
  20. //! Returns a sequence of written chunks.
  21. //! The stream is no longer usable after this call.
  22. std::vector<TSharedRef> Finish();
  23. //! Returns the number of bytes actually written.
  24. size_t GetSize() const;
  25. //! Returns the number of bytes actually written plus unused capacity in the
  26. //! last chunk.
  27. size_t GetCapacity() const;
  28. //! Returns a pointer to a contiguous memory block of a given #size.
  29. //! Do not forget to call #Advance after use.
  30. char* Preallocate(size_t size);
  31. //! Marks #size bytes (which were previously preallocated) as used.
  32. void Advance(size_t size);
  33. private:
  34. size_t MaxReserveSize_;
  35. size_t CurrentReserveSize_;
  36. size_t FinishedSize_ = 0;
  37. TBlob CurrentChunk_;
  38. std::vector<TSharedRef> FinishedChunks_;
  39. void ReserveNewChunk(size_t spaceRequired);
  40. void DoWrite(const void* buf, size_t len) override;
  41. size_t DoNext(void** ptr) override;
  42. void DoUndo(size_t len) override;
  43. };
  44. ////////////////////////////////////////////////////////////////////////////////
  45. } // namespace NYT