rapidjson_helpers.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #pragma once
  2. #include <util/generic/strbuf.h>
  3. #include <util/stream/input.h>
  4. namespace NJson {
  5. struct TReadOnlyStreamBase {
  6. using Ch = char;
  7. Ch* PutBegin() {
  8. Y_ASSERT(false);
  9. return nullptr;
  10. }
  11. void Put(Ch) {
  12. Y_ASSERT(false);
  13. }
  14. void Flush() {
  15. Y_ASSERT(false);
  16. }
  17. size_t PutEnd(Ch*) {
  18. Y_ASSERT(false);
  19. return 0;
  20. }
  21. };
  22. struct TInputStreamWrapper : TReadOnlyStreamBase {
  23. Ch Peek() const {
  24. if (!Eof) {
  25. if (Pos >= Sz) {
  26. if (Sz < BUF_SIZE) {
  27. Sz += Helper.Read(Buf + Sz, BUF_SIZE - Sz);
  28. } else {
  29. Sz = Helper.Read(Buf, BUF_SIZE);
  30. Pos = 0;
  31. }
  32. }
  33. if (Pos < Sz) {
  34. return Buf[Pos];
  35. }
  36. }
  37. Eof = true;
  38. return 0;
  39. }
  40. Ch Take() {
  41. auto c = Peek();
  42. ++Pos;
  43. ++Count;
  44. return c;
  45. }
  46. size_t Tell() const {
  47. return Count;
  48. }
  49. TInputStreamWrapper(IInputStream& helper)
  50. : Helper(helper)
  51. , Eof(false)
  52. , Sz(0)
  53. , Pos(0)
  54. , Count(0)
  55. {
  56. }
  57. static const size_t BUF_SIZE = 1 << 12;
  58. IInputStream& Helper;
  59. mutable char Buf[BUF_SIZE];
  60. mutable bool Eof;
  61. mutable size_t Sz;
  62. mutable size_t Pos;
  63. size_t Count;
  64. };
  65. struct TStringBufStreamWrapper : TReadOnlyStreamBase {
  66. Ch Peek() const {
  67. return Pos < Data.size() ? Data[Pos] : 0;
  68. }
  69. Ch Take() {
  70. auto c = Peek();
  71. ++Pos;
  72. return c;
  73. }
  74. size_t Tell() const {
  75. return Pos;
  76. }
  77. TStringBufStreamWrapper(TStringBuf data)
  78. : Data(data)
  79. , Pos(0)
  80. {
  81. }
  82. TStringBuf Data;
  83. size_t Pos;
  84. };
  85. }