aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/IO/ConcatReadBuffer.h
blob: 3f44181a6e99ead610e67c93e23a7932d900cd7e (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
#pragma once

#include <vector>

#include <IO/ReadBuffer.h>


namespace DB
{

/// Reads from the concatenation of multiple ReadBuffer's
class ConcatReadBuffer : public ReadBuffer
{
public:
    using Buffers = std::vector<std::unique_ptr<ReadBuffer>>;

    ConcatReadBuffer() : ReadBuffer(nullptr, 0), current(buffers.end())
    {
    }

    explicit ConcatReadBuffer(Buffers && buffers_) : ReadBuffer(nullptr, 0), buffers(std::move(buffers_)), current(buffers.begin())
    {
        assert(!buffers.empty());
    }

    ConcatReadBuffer(std::unique_ptr<ReadBuffer> buf1, std::unique_ptr<ReadBuffer> buf2) : ConcatReadBuffer()
    {
        appendBuffer(std::move(buf1));
        appendBuffer(std::move(buf2));
    }

    ConcatReadBuffer(ReadBuffer & buf1, ReadBuffer & buf2) : ConcatReadBuffer()
    {
        appendBuffer(wrapReadBufferReference(buf1));
        appendBuffer(wrapReadBufferReference(buf2));
    }

    void appendBuffer(std::unique_ptr<ReadBuffer> buffer)
    {
        assert(!count());
        buffers.push_back(std::move(buffer));
        current = buffers.begin();
    }

protected:
    Buffers buffers;
    Buffers::iterator current;

    bool nextImpl() override
    {
        if (buffers.end() == current)
            return false;

        /// First reading
        if (working_buffer.empty())
        {
            if ((*current)->hasPendingData())
            {
                working_buffer = Buffer((*current)->position(), (*current)->buffer().end());
                return true;
            }
        }
        else
            (*current)->position() = position();

        if (!(*current)->next())
        {
            ++current;
            if (buffers.end() == current)
                return false;

            /// We skip the filled up buffers; if the buffer is not filled in, but the cursor is at the end, then read the next piece of data.
            while ((*current)->eof())
            {
                ++current;
                if (buffers.end() == current)
                    return false;
            }
        }

        working_buffer = Buffer((*current)->position(), (*current)->buffer().end());
        return true;
    }
};

}