util_stream_io.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #pragma once
  2. #include "bin_saver.h"
  3. #include <util/stream/input.h>
  4. #include <util/stream/output.h>
  5. #include <util/stream/file.h>
  6. class TYaStreamInput: public IBinaryStream {
  7. IInputStream& Stream;
  8. int WriteImpl(const void*, int) override {
  9. Y_ASSERT(0);
  10. return 0;
  11. }
  12. int ReadImpl(void* userBuffer, int size) override {
  13. return (int)Stream.Read(userBuffer, (size_t)size);
  14. }
  15. bool IsValid() const override {
  16. return true;
  17. }
  18. bool IsFailed() const override {
  19. return false;
  20. }
  21. public:
  22. TYaStreamInput(IInputStream& stream)
  23. : Stream(stream)
  24. {
  25. }
  26. };
  27. template <class T>
  28. inline void SerializeFromStream(IInputStream& stream, T& c) {
  29. TYaStreamInput f(stream);
  30. {
  31. IBinSaver bs(f, true);
  32. bs.Add(1, &c);
  33. }
  34. }
  35. template <class T>
  36. inline void SerializeFromFile(const TString& fileName, T& c) {
  37. TIFStream in(fileName);
  38. SerializeFromStream(in, c);
  39. }
  40. class TYaStreamOutput: public IBinaryStream {
  41. IOutputStream& Stream;
  42. int WriteImpl(const void* what, int size) override {
  43. Stream.Write(what, (size_t)size);
  44. return size;
  45. }
  46. int ReadImpl(void*, int) override {
  47. Y_ASSERT(0);
  48. return 0;
  49. }
  50. bool IsValid() const override {
  51. return true;
  52. }
  53. bool IsFailed() const override {
  54. return false;
  55. }
  56. public:
  57. TYaStreamOutput(IOutputStream& stream)
  58. : Stream(stream)
  59. {
  60. }
  61. };
  62. template <class T>
  63. inline void SerializeToArcadiaStream(IOutputStream& stream, T& c) {
  64. TYaStreamOutput f(stream);
  65. {
  66. IBinSaver bs(f, false);
  67. bs.Add(1, &c);
  68. }
  69. }
  70. template <class T>
  71. inline void SerializeToFile(const TString& fileName, T& c) {
  72. TOFStream out(fileName);
  73. SerializeToArcadiaStream(out, c);
  74. }