File: varint.pyx

package info (click to toggle)
python-clickhouse-driver 0.2.5-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,516 kB
  • sloc: python: 10,950; pascal: 42; makefile: 31; sh: 3
file content (68 lines) | stat: -rw-r--r-- 1,743 bytes parent folder | download | duplicates (3)
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
from cpython cimport PyBytes_FromStringAndSize


def make_varint(unsigned long long number):
    """
    Writes integer of variable length using LEB128.
    """
    cdef unsigned char to_write, i = 0
    # unsigned PY_LONG_LONG checks integer on function call and
    # raises OverflowError if integer overflows unsigned PY_LONG_LONG.
    # Long enough for handling unsigned PY_LONG_LONG.
    cdef unsigned char num_buf[32]

    while True:
        to_write = number & 0x7f
        number >>= 7
        if number:
            num_buf[i] = to_write | 0x80
            i += 1
        else:
            num_buf[i] = to_write
            i += 1
            break

    return PyBytes_FromStringAndSize(<char *>num_buf, i)


def write_varint(unsigned long long number, buf):
    """
    Writes integer of variable length using LEB128.
    """
    cdef unsigned char to_write, i = 0
    # unsigned PY_LONG_LONG checks integer on function call and
    # raises OverflowError if integer overflows unsigned PY_LONG_LONG.
    # Long enough for handling unsigned PY_LONG_LONG.
    cdef unsigned char num_buf[32]

    while True:
        to_write = number & 0x7f
        number >>= 7
        if number:
            num_buf[i] = to_write | 0x80
            i += 1
        else:
            num_buf[i] = to_write
            i += 1
            break

    buf.write(PyBytes_FromStringAndSize(<char *>num_buf, i))


def read_varint(f):
    """
    Reads integer of variable length using LEB128.
    """
    cdef unsigned char shift = 0
    cdef unsigned long long i, result = 0

    read_one = f.read_one

    while True:
        i = read_one()
        result |= (i & 0x7f) << shift
        shift += 7
        if i < 0x80:
            break

    return result