output.h 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #pragma once
  2. #include "buffer.h"
  3. #include <util/generic/ptr.h>
  4. #include <util/generic/strbuf.h>
  5. #include <util/system/types.h>
  6. #include <util/system/yassert.h>
  7. #include <cstddef>
  8. #include <cstdio>
  9. #include <cstring>
  10. #include <memory>
  11. //! \brief Output stream adaptor interface.
  12. //!
  13. //! Represents a model of an optionally-buffered writer.
  14. namespace NYsonPull {
  15. namespace NOutput {
  16. class IStream {
  17. output_buffer buffer_;
  18. public:
  19. virtual ~IStream() = default;
  20. output_buffer& buffer() noexcept {
  21. return buffer_;
  22. }
  23. const output_buffer& buffer() const noexcept {
  24. return buffer_;
  25. }
  26. void flush_buffer(TStringBuf extra = {}) {
  27. if (!extra.empty() || !buffer_.is_empty()) {
  28. do_flush_buffer(extra);
  29. }
  30. while (!buffer_.is_empty()) {
  31. do_flush_buffer({});
  32. }
  33. }
  34. protected:
  35. //! \brief Flush data to underlying stream.
  36. //!
  37. //! The implementation is to flush the buffer contents AND
  38. //! extra argument to underlying stream.
  39. //!
  40. //! This way, at zero buffer size this interface implements an unbuffered
  41. //! stream (with an added cost of a virtual call per each write).
  42. //!
  43. //! Write is assumed to always succeed unless it throws an exception.
  44. virtual void do_flush_buffer(TStringBuf extra) = 0;
  45. };
  46. //! \brief Write data to C FILE* object.
  47. THolder<IStream> FromStdioFile(FILE* file, size_t buffer_size = 0);
  48. //! \brief Write data to POSIX file descriptor
  49. THolder<IStream> FromPosixFd(int fd, size_t buffer_size = 65536);
  50. THolder<IStream> FromOutputStream(IOutputStream* output, size_t buffer_size = 65536);
  51. THolder<IStream> FromString(TString* output, size_t buffer_size = 1024);
  52. }
  53. }