zerocopy.h 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #pragma once
  2. #include <util/system/yassert.h>
  3. #include <util/system/defaults.h>
  4. #include <util/generic/ylimits.h>
  5. #include "input.h"
  6. class IOutputStream;
  7. /**
  8. * @addtogroup Streams
  9. * @{
  10. */
  11. /**
  12. * Input stream with direct access to the input buffer.
  13. *
  14. * Derived classes must implement `DoNext` method.
  15. */
  16. class IZeroCopyInput: public IInputStream {
  17. public:
  18. IZeroCopyInput() noexcept = default;
  19. ~IZeroCopyInput() override;
  20. IZeroCopyInput(IZeroCopyInput&&) noexcept = default;
  21. IZeroCopyInput& operator=(IZeroCopyInput&&) noexcept = default;
  22. /**
  23. * Returns the next data chunk from this input stream.
  24. *
  25. * Note that this function is not guaranteed to return the requested number
  26. * of bytes, even if they are in fact available in the stream.
  27. *
  28. * @param ptr[out] Pointer to the start of the data chunk.
  29. * @param len[in] Maximal size of the data chunk to be returned, in bytes.
  30. * @returns Size of the returned data chunk, in bytes.
  31. * Return value of zero signals end of stream.
  32. */
  33. template <class T>
  34. inline size_t Next(T** ptr, size_t len) {
  35. Y_ASSERT(ptr);
  36. return DoNext((const void**)ptr, len);
  37. }
  38. template <class T>
  39. inline size_t Next(T** ptr) {
  40. return Next(ptr, Max<size_t>());
  41. }
  42. protected:
  43. size_t DoRead(void* buf, size_t len) override;
  44. size_t DoSkip(size_t len) override;
  45. ui64 DoReadAll(IOutputStream& out) override;
  46. virtual size_t DoNext(const void** ptr, size_t len) = 0;
  47. };
  48. /**
  49. * Input stream with direct access to the input buffer and ability to undo read
  50. *
  51. * Derived classes must implement `DoUndo` method.
  52. */
  53. class IZeroCopyInputFastReadTo: public IZeroCopyInput {
  54. public:
  55. IZeroCopyInputFastReadTo() noexcept = default;
  56. ~IZeroCopyInputFastReadTo() override;
  57. IZeroCopyInputFastReadTo(IZeroCopyInputFastReadTo&&) noexcept = default;
  58. IZeroCopyInputFastReadTo& operator=(IZeroCopyInputFastReadTo&&) noexcept = default;
  59. protected:
  60. size_t DoReadTo(TString& st, char ch) override;
  61. private:
  62. /**
  63. * Undo read.
  64. *
  65. * Note that this function not check if you try undo more that read. In fact Undo used for undo read in last chunk.
  66. *
  67. * @param len[in] Bytes to undo.
  68. */
  69. inline void Undo(size_t len) {
  70. if (len) {
  71. DoUndo(len);
  72. }
  73. }
  74. virtual void DoUndo(size_t len) = 0;
  75. };
  76. /** @} */