aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/json/rapidjson_helpers.h
blob: 6adad9b32fc567d4297b9c62aa9c6ec6bbcb9296 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#pragma once

#include <util/generic/strbuf.h>
#include <util/stream/input.h>

namespace NJson {
    struct TReadOnlyStreamBase {
        using Ch = char;

        Ch* PutBegin() {
            Y_ASSERT(false);
            return nullptr;
        }

        void Put(Ch) {
            Y_ASSERT(false);
        }

        void Flush() {
            Y_ASSERT(false);
        }

        size_t PutEnd(Ch*) {
            Y_ASSERT(false);
            return 0;
        }
    };

    struct TInputStreamWrapper : TReadOnlyStreamBase { 
        Ch Peek() const {
            if (!Eof) {
                if (Pos >= Sz) {
                    if (Sz < BUF_SIZE) {
                        Sz += Helper.Read(Buf + Sz, BUF_SIZE - Sz);
                    } else {
                        Sz = Helper.Read(Buf, BUF_SIZE);
                        Pos = 0;
                    }
                }

                if (Pos < Sz) {
                    return Buf[Pos];
                }
            }

            Eof = true;
            return 0;
        }

        Ch Take() {
            auto c = Peek();
            ++Pos;
            ++Count;
            return c;
        }

        size_t Tell() const {
            return Count;
        }

        TInputStreamWrapper(IInputStream& helper)
            : Helper(helper)
            , Eof(false)
            , Sz(0)
            , Pos(0)
            , Count(0)
        {
        }

        static const size_t BUF_SIZE = 1 << 12;

        IInputStream& Helper;
        mutable char Buf[BUF_SIZE];
        mutable bool Eof;
        mutable size_t Sz;
        mutable size_t Pos;
        size_t Count;
    };

    struct TStringBufStreamWrapper : TReadOnlyStreamBase { 
        Ch Peek() const {
            return Pos < Data.size() ? Data[Pos] : 0;
        }

        Ch Take() {
            auto c = Peek();
            ++Pos;
            return c;
        }

        size_t Tell() const {
            return Pos;
        }

        TStringBufStreamWrapper(TStringBuf data)
            : Data(data)
            , Pos(0)
        {
        }

        TStringBuf Data;
        size_t Pos;
    };
}