aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/yson/varint.cpp
blob: d538ee3cffa303d0810a921b259673e855bd71ee (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
#include "varint.h"

#include "zigzag.h"

#include <util/generic/yexception.h>

namespace NYson {
    ////////////////////////////////////////////////////////////////////////////////

    int WriteVarUInt64(IOutputStream* output, ui64 value) {
        bool stop = false;
        int bytesWritten = 0;
        while (!stop) {
            ++bytesWritten;
            ui8 byte = static_cast<ui8>(value | 0x80);
            value >>= 7;
            if (value == 0) {
                stop = true;
                byte &= 0x7F;
            }
            output->Write(byte);
        }
        return bytesWritten;
    }

    int WriteVarInt32(IOutputStream* output, i32 value) {
        return WriteVarUInt64(output, static_cast<ui64>(ZigZagEncode32(value)));
    }

    int WriteVarInt64(IOutputStream* output, i64 value) {
        return WriteVarUInt64(output, static_cast<ui64>(ZigZagEncode64(value)));
    }

    int ReadVarUInt64(IInputStream* input, ui64* value) {
        size_t count = 0;
        ui64 result = 0;

        ui8 byte = 0;
        do {
            if (7 * count > 8 * sizeof(ui64)) {
                ythrow yexception() << "The data is too long to read ui64";
            }
            if (input->Read(&byte, 1) != 1) {
                ythrow yexception() << "The data is too long to read ui64";
            }
            result |= (static_cast<ui64>(byte & 0x7F)) << (7 * count);
            ++count;
        } while (byte & 0x80);

        *value = result;
        return count;
    }

    int ReadVarInt32(IInputStream* input, i32* value) {
        ui64 varInt;
        int bytesRead = ReadVarUInt64(input, &varInt);
        if (varInt > Max<ui32>()) {
            ythrow yexception() << "The data is too long to read ui64";
        }
        *value = ZigZagDecode32(static_cast<ui32>(varInt));
        return bytesRead;
    }

    int ReadVarInt64(IInputStream* input, i64* value) {
        ui64 varInt;
        int bytesRead = ReadVarUInt64(input, &varInt);
        *value = ZigZagDecode64(varInt);
        return bytesRead;
    }

} // namespace NYson