aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/clickhouse/src/Formats/ProtobufWriter.h
blob: 4fd10ba09bd7c84728a302fff405b3b469182e83 (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
#pragma once

#include "clickhouse_config.h"

#if USE_PROTOBUF
#   include <Core/Types.h>
#   include <Common/PODArray.h>


namespace DB
{
class WriteBuffer;

/// Utility class for writing in the Protobuf format.
/// Knows nothing about protobuf schemas, just provides useful functions to serialize data.
class ProtobufWriter
{
public:
    explicit ProtobufWriter(WriteBuffer & out_);
    ~ProtobufWriter();

    void startMessage();
    void endMessage(bool with_length_delimiter);

    void startNestedMessage();
    void endNestedMessage(int field_number, bool is_group, bool skip_if_empty);

    void writeInt(int field_number, Int64 value);
    void writeUInt(int field_number, UInt64 value);
    void writeSInt(int field_number, Int64 value);
    template <typename T>
    void writeFixed(int field_number, T value);
    void writeString(int field_number, std::string_view str);

    void startRepeatedPack();
    void endRepeatedPack(int field_number, bool skip_if_empty);

private:
    struct Piece
    {
        size_t start;
        size_t end;
        Piece(size_t start_, size_t end_) : start(start_), end(end_) {}
        Piece() = default;
    };

    struct NestedInfo
    {
        size_t num_pieces_at_start;
        size_t num_bytes_skipped_at_start;
        NestedInfo(size_t num_pieces_at_start_, size_t num_bytes_skipped_at_start_)
            : num_pieces_at_start(num_pieces_at_start_), num_bytes_skipped_at_start(num_bytes_skipped_at_start_)
        {
        }
    };

    WriteBuffer & out;
    PODArray<UInt8> buffer;
    std::vector<Piece> pieces;
    size_t current_piece_start = 0;
    size_t num_bytes_skipped = 0;
    std::vector<NestedInfo> nested_infos;
    bool in_repeated_pack = false;
};

}
#endif