~chiefnoah/pybare

ref: 1d7d484e76af17353032d95fff1e1638b3badb04 pybare/bare/types.py -rw-r--r-- 10.1 KiB
1d7d484eNoah Pederson Rename fields, add tests, fix bugs [see ext.] 9 months ago
                                                                                
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
from .encoder import (
    Field,
    BareType,
    _write_string,
    _write_varint,
    _read_string,
    _read_varint,
)
import typing
import struct
from enum import IntEnum

ValidationMessage = typing.Tuple[bool, str]


class Simple(Field):
    _fmt = None
    _bytesize = 0

    def _pack(self, fp: typing.BinaryIO, value=None):
        if value is None:
            value = self._value
        fp.write(struct.pack(self.__class__._fmt, value))

    def _unpack(self, fp: typing.BinaryIO):
        buf = fp.read(self._bytesize)
        return self.__class__(value=(struct.unpack(self._fmt, buf)[0]))


class U8(Simple):

    _type = BareType.U8
    _default = 0
    _fmt = "<B"
    _bytesize = 1

    def validate(self, value) -> ValidationMessage:
        if not isinstance(value, int):
            return False, f"type: {type(value)} must be <int>"
        if value < 0 or value > 0xFFFF:
            return (
                False,
                f"value: {value} is outside of valid range for this type: {self.__class__._type}",
            )
        return True, None


class U16(Simple):
    _type = BareType.U16
    _default = 0
    _fmt = "<H"
    _bytesize = 2

    def validate(self, value) -> ValidationMessage:
        if not isinstance(value, int):
            return False, f"type: {type(value)} must be <int>"
        if value < 0 or value > 0xFFFFFFFF:
            return (
                False,
                f"value: {value} is outside of valid range for this type: {self.__class__._type}",
            )
        return True, None


class U32(Simple):
    _type = BareType.U32
    _default = 0
    _fmt = "<I"
    _bytesize = 4

    def validate(self, value) -> ValidationMessage:
        if not isinstance(value, int):
            return False, f"type: {type(value)} must be <int>"
        if value < 0 or value > 0xFFFFFFFF:
            return (
                False,
                f"value: {value} is outside of valid range for this type: {self.__class__._type}",
            )
        return True, None


class U64(Simple):

    _type = BareType.U64
    _default = 0
    _fmt = "<Q"
    _bytesize = 8

    def validate(self, value) -> ValidationMessage:
        if not isinstance(value, int):
            return False, f"type: {type(value)} must be <int>"
        if value < 0 or value > 0xFFFFFFFFFFFFFFFF:
            return (
                False,
                f"value: {value} is outside of valid range for this type: {self.__class__._type}",
            )
        return True, None


class I8(Simple):
    _type = BareType.I8
    _default = 0
    _fmt = "<b"
    _bytesize = 1

    def validate(self, value) -> ValidationMessage:
        if not isinstance(value, int):
            return False, f"type: {type(value)} must be <int>"
        if value < -128 or value > 127:
            return (
                False,
                f"value: {value} is outside of valid range for this type: {self.__class__._type}",
            )
        return True, None


class I16(Simple):
    _type = BareType.I16
    _default = 0
    _fmt = "<h"
    _bytesize = 2

    @classmethod
    def validate(self, value) -> ValidationMessage:
        if not isinstance(value, int):
            return False, f"type: {type(value)} must be <int>"
        if value < -32768 or value > 32767:
            return (
                False,
                f"value: {value} is outside of valid range for this type: {self.__class__._type}",
            )
        return True, None


class I32(Simple):
    _type = BareType.I32
    _default = 0
    _fmt = "<i"
    _bytesize = 4

    def validate(self, value) -> ValidationMessage:
        if not isinstance(value, int):
            return False, f"type: {type(value)} must be <int>"
        if value < -2147483648 or value > 2147483647:
            return (
                False,
                f"value: {value} is outside of valid range for this type: {self.__class__._type}",
            )
        return True, None


class I64(Simple):
    _type = BareType.I64
    _default = 0
    _fmt = "<q"
    _bytesize = 8

    def validate(self, value) -> ValidationMessage:
        if not isinstance(value, int):
            return False, f"type: {type(value)} must be <int>"
        if value < -9223372036854775808 or value > 9223372036854775807:
            return (
                False,
                f"value: {value} is outside of valid range for this type: {self.__class__._type}",
            )
        return True, None


class F32(Simple):
    _type = BareType.F32
    _default = 0.0
    _fmt = "<f"
    _bytesize = 4

    def validate(self, value) -> ValidationMessage:
        if not isinstance(value, float):
            return False, f"type: {type(value)} must be <int>"
        return True, None


class F64(Simple):
    _type = BareType.F32
    _default = 0.0
    _fmt = "<d"
    _bytesize = 8

    def validate(self, value) -> ValidationMessage:
        if not isinstance(value, float):
            return False, f"type: {type(value)} must be <int>"
        return True, None


class Bool(Simple):
    _type = BareType.Bool
    _default = False
    _fmt = "<?"
    _bytesize = 1

    def validate(self, value) -> ValidationMessage:
        if not isinstance(value, bool):
            return False, f"type: {type(value)} must be <int>"
        return True, None


class Void(Field):
    _type = BareType.Void
    _default = None
    _fmt = None
    _bytesize = 0

    def _pack(self, fp: typing.BinaryIO, value=None):
        pass  # NO OP

    def _unpack(self, fp: typing.BinaryIO):
        return self.__class__(value=None)

    def validate(self, value):
        if value is not None:
            return False, f"type: {type(value)} must be <None>"
        return True, None


class Int(Field):

    _type = BareType.INT
    _default = 0

    def validate(self, value) -> ValidationMessage:
        if not isinstance(value, int):
            return False, f"type: {type(value)} must be <int>"
        return True, None

    def _pack(self, fp: typing.BinaryIO, value=None):
        if value is None:
            value = self._value
        _write_varint(fp, value, signed=True)

    def _unpack(self, fp: typing.BinaryIO) -> "Int":
        val = _read_varint(fp, signed=True)
        return self.__class__(value=val)

class UInt(Field):

    _type = BareType.UINT
    _default = 0

    def validate(self, value) -> ValidationMessage:
        if not isinstance(value, int):
            return False, f"type: {type(value)} must be <int>"
        if value < 0:
            return False, f"value: {value} is outside of valid range for this type: {self.__class__._type}",
        return True, None

    def _pack(self, fp: typing.BinaryIO, value=None):
        if value is None:
            value = self._value
        _write_varint(fp, value, signed=False)

    def _unpack(self, fp: typing.BinaryIO) -> "UInt":
        val = _read_varint(fp, signed=False)
        return self.__class__(value=val)


class Str(Field):

    _type = BareType.String
    _default = ""

    def validate(self, value) -> ValidationMessage:
        if not isinstance(value, str):
            return False, f"type: {type(value)} must be <str>"
        return True, None

    def _pack(self, fp: typing.BinaryIO, value=None):
        if value is None:
            value = self._value
        _write_string(fp, value)

    def _unpack(self, fp: typing.BinaryIO) -> "Str":
        val = _read_string(fp)
        return self.__class__(value=val)


class Data(Field):
    _type = BareType.Data
    _default = bytes()

    def validate(self, value) -> ValidationMessage:
        try:
            value.decode()
            return True, None
        except (UnicodeDecodeError, AttributeError):
            return False, f"type: {type(value)} is not valid for Data type"

    def _pack(self, fp: typing.BinaryIO, value=None):
        if value is None:
            value = self._value
        length = len(value)
        if isinstance(value, str):
            value = value.encode("utf-8")
        _write_varint(fp, val=length, signed=False)
        fp.write(fp.write(struct.pack(f"<{len(value)}s", value)))

    def _unpack(self, fp: typing.BinaryIO) -> "Data":
        length = _read_varint(fp, signed=False)
        val = struct.unpack("<{length}s", fp)[0]
        return self.__class__(value=val)


class DataFixed(Field):
    _type = BareType.DataFixed
    _length = 0
    _default = bytes(_length)

    def __init__(self, length=0, value=None):
        if length == 0 and self.__class__._length > 0:
            self._length = self.__class__._length
        else:
            self._length = length
        if value is not None:
            self._value = value
        else:
            self._value = self.__class__._default

    def validate(self, value) -> ValidationMessage:
        try:
            value.decode()
        except (UnicodeDecodeError, AttributeError):
            return False, f"type: {type(value)} is not valid for Data type"
        if len(value) != self._length:
            return (
                False,
                f"Length of data {len(value)} not equal to fixed length {self._length}",
            )

    def _pack(self, fp: typing.BinaryIO, value=None):
        if value is None:
            value = self._value
        fp.write(struct.pack(f"<{self._length}s", value))

    def _unpack(self, fp: typing.BinaryIO, length=None) -> "DataFixed":
        if length is None:
            length = self._length
        val = struct.unpack(f"<{length}s", fp)[0]
        return self.__class__(value=val)

class Enum(UInt):

    def __init__(self, enum, *args, **kwargs):
        self._enum = enum
        super().__init__(*args, **kwargs)

    def validate(self, value):
        if not isinstance(value, int):
            return False, f"type: {type(value)} is not valid for Enum, must be <int>"
        if value < 0:
            return False, f"value is not a valid value for Enum {self.__class__.__name__}"
        values = set(item.value for item in self._enum.__members__.values())
        if value not in values:
            return False, f"value {value} is not a valid Enum type for {self.__class__.__name__}"
        return True, None

    def _unpack(self, fp: typing.BinaryIO) -> 'UInt':
        val = _read_varint(fp, signed=False)
        return self.__class__(self._enum, val)