length.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #pragma once
  2. #include "input.h"
  3. #include "output.h"
  4. #include <util/generic/utility.h>
  5. /**
  6. * Proxy input stream that can read a limited number of characters from a slave
  7. * stream.
  8. *
  9. * This can be useful for breaking up the slave stream into small chunks and
  10. * treat these as separate streams.
  11. */
  12. class TLengthLimitedInput: public IInputStream {
  13. public:
  14. inline TLengthLimitedInput(IInputStream* slave, ui64 length) noexcept
  15. : Slave_(slave)
  16. , Length_(length)
  17. {
  18. }
  19. ~TLengthLimitedInput() override = default;
  20. inline ui64 Left() const noexcept {
  21. return Length_;
  22. }
  23. private:
  24. size_t DoRead(void* buf, size_t len) override;
  25. size_t DoSkip(size_t len) override;
  26. private:
  27. IInputStream* Slave_;
  28. ui64 Length_;
  29. };
  30. /**
  31. * Proxy input stream that counts the number of characters read.
  32. */
  33. class TCountingInput: public IInputStream {
  34. public:
  35. inline TCountingInput(IInputStream* slave) noexcept
  36. : Slave_(slave)
  37. , Count_()
  38. {
  39. }
  40. ~TCountingInput() override = default;
  41. /**
  42. * \returns The total number of characters read from
  43. * this stream.
  44. */
  45. inline ui64 Counter() const noexcept {
  46. return Count_;
  47. }
  48. private:
  49. size_t DoRead(void* buf, size_t len) override;
  50. size_t DoSkip(size_t len) override;
  51. size_t DoReadTo(TString& st, char ch) override;
  52. ui64 DoReadAll(IOutputStream& out) override;
  53. private:
  54. IInputStream* Slave_;
  55. ui64 Count_;
  56. };
  57. /**
  58. * Proxy output stream that counts the number of characters written.
  59. */
  60. class TCountingOutput: public IOutputStream {
  61. public:
  62. inline TCountingOutput(IOutputStream* slave) noexcept
  63. : Slave_(slave)
  64. , Count_()
  65. {
  66. }
  67. ~TCountingOutput() override = default;
  68. TCountingOutput(TCountingOutput&&) noexcept = default;
  69. TCountingOutput& operator=(TCountingOutput&&) noexcept = default;
  70. /**
  71. * \returns The total number of characters written
  72. * into this stream.
  73. */
  74. inline ui64 Counter() const noexcept {
  75. return Count_;
  76. }
  77. private:
  78. void DoWrite(const void* buf, size_t len) override;
  79. private:
  80. IOutputStream* Slave_;
  81. ui64 Count_;
  82. };