aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/clickhouse/client/base/coded.cpp
blob: 5a5d56d1588c3b0eea482f99d5320d1c19f8854c (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
#include "coded.h"

#include <memory.h>

namespace NClickHouse {
    static const int MAX_VARINT_BYTES = 10;

    TCodedInputStream::TCodedInputStream(IZeroCopyInput* input)
        : Input_(input)
    {
    }

    bool TCodedInputStream::ReadRaw(void* buffer, size_t size) {
        ui8* p = static_cast<ui8*>(buffer);

        while (size > 0) {
            const void* ptr;

            if (size_t len = Input_->Next(&ptr, size)) {
                memcpy(p, ptr, len);

                p += len;
                size -= len;
            } else {
                break;
            }
        }

        return size == 0;
    }

    bool TCodedInputStream::Skip(size_t count) {
        while (count > 0) {
            const void* ptr;
            size_t len = Input_->Next(&ptr, count);

            if (len == 0) {
                return false;
            }

            count -= len;
        }

        return true;
    }

    bool TCodedInputStream::ReadVarint64(ui64* value) {
        *value = 0;

        for (size_t i = 0; i < 9; ++i) {
            ui8 byte;

            if (!Input_->Read(&byte, sizeof(byte))) {
                return false;
            } else {
                *value |= (byte & 0x7F) << (7 * i);

                if (!(byte & 0x80)) {
                    return true;
                }
            }
        }

        // TODO skip invalid
        return false;
    }

    TCodedOutputStream::TCodedOutputStream(IOutputStream* output)
        : Output_(output)
    {
    }

    void TCodedOutputStream::Flush() {
        Output_->Flush();
    }

    void TCodedOutputStream::WriteRaw(const void* buffer, int size) {
        Output_->Write(buffer, size);
    }

    void TCodedOutputStream::WriteVarint64(ui64 value) {
        ui8 bytes[MAX_VARINT_BYTES];
        int size = 0;

        for (size_t i = 0; i < 9; ++i) {
            ui8 byte = value & 0x7F;
            if (value > 0x7F)
                byte |= 0x80;

            bytes[size++] = byte;

            value >>= 7;
            if (!value) {
                break;
            }
        }

        WriteRaw(bytes, size);
    }

}