File size: 5,011 Bytes
44bafb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
"""
MIT License

Copyright (c) 2024-present Simon Sawicki <contact@grub4k.xyz>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

https://github.com/Grub4K/qpb
"""

import ast
import base64
import contextlib
import enum
import io
import struct
from collections import defaultdict


def decode_protobuf(value):
    data = base64.b64decode(value)
    decoded = _decode(data)
    return decoded


def encode_protobuf(value):
    try:
        data = ast.literal_eval(value.strip())
        # data = ast.literal_eval(" ".join(value))
        result = _encode(data)
        encoded = base64.b64encode(result).decode()
        return encoded
    except SyntaxError:
        raise SyntaxError(f"invalid input: {value}")


class WireType(enum.IntEnum):
    VARINT = 0
    I64 = 1
    LEN = 2
    SGROUP = 3
    EGROUP = 4
    I32 = 5


_float_struct = struct.Struct(b"<f")
_double_struct = struct.Struct(b"<d")


def _encode(data) -> bytes:
    if not isinstance(data, dict):
        message = "type to encode has to be a dict"
        raise TypeError(message)

    return b"".join(_encode_record(value, wire_id) for wire_id, value in data.items())


def _decode(data):
    reader = data if isinstance(data, io.BufferedIOBase) else io.BytesIO(data)
    result = defaultdict(list)

    record = _read_record(reader)
    while record:
        key, value = record
        result[key].append(value)
        record = _read_record(reader)

    for key, values in result.items():
        for index, value in enumerate(values):
            if not isinstance(value, bytes):
                continue
            with contextlib.suppress(Exception):
                values[index] = _decode(value)
        if len(values) == 1:
            result[key] = values[0]

    return dict(result)


def _read_record(reader: io.BufferedIOBase):
    tag = _read_tag(reader)
    if tag is None:
        return None
    wire_id, wire_type = tag
    if wire_type == WireType.VARINT:
        value = _read_varint(reader)
    elif wire_type == WireType.I64:
        value = reader.read(8)
    elif wire_type == WireType.I32:
        value = reader.read(4)
    elif wire_type == WireType.LEN:
        value = reader.read(_read_varint(reader))
    else:
        message = "Unknown wire type"
        raise TypeError(message)

    return wire_id, value


def _encode_record(data, wire_id) -> bytes:
    if isinstance(data, int):
        if data < 0:
            data = _signed_to_zigzag(data)
        return _encode_tag(wire_id, WireType.VARINT) + _encode_varint(data)

    if isinstance(data, list):
        encoded = b"".join(map(_encode_record, data))
    elif isinstance(data, dict):
        encoded = _encode(data)
    elif isinstance(data, str):
        encoded = data.encode()
    elif isinstance(data, bytes):
        encoded = data
    else:
        message = f"Unencodable type: {type(data)}"
        raise TypeError(message)

    return _encode_tag(wire_id, WireType.LEN) + _encode_varint(len(encoded)) + encoded


def _read_varint(reader: io.BufferedIOBase):
    shift = 0
    data = 0

    byte = 0b1000_0000
    while byte & 0b1000_0000:
        result = reader.read(1)
        if not result:
            return None
        (byte,) = result
        data |= (byte & 0b0111_1111) << shift
        shift += 7

    return data


def _encode_varint(value: int) -> bytes:
    data_length = (value.bit_length() + 6) // 7 or 1
    data = bytearray(data_length)
    for index in range(data_length - 1):
        data[index] = value & 0b0111_1111 | 0b1000_0000
        value >>= 7

    data[-1] = value
    return bytes(data)


def _read_tag(reader: io.BufferedIOBase):
    value = _read_varint(reader)
    if value is None:
        return None
    return value >> 3, WireType(value & 0b111)


def _encode_tag(wire_id, wire_type: WireType) -> bytes:
    if wire_id is None:
        return b""
    return _encode_varint((wire_id << 3) | wire_type)


def _signed_to_zigzag(value: int):
    result = value << 1
    if value < 0:
        result = -result - 1
    return result