protobin 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
protobin/__init__.py ADDED
@@ -0,0 +1 @@
1
+ from .protocol import Protocol
protobin/errors.py ADDED
@@ -0,0 +1,10 @@
1
+
2
+
3
+ class ParserError(Exception):
4
+
5
+ def __init__(self, message):
6
+ self._message = message
7
+ super().__init__()
8
+
9
+ def get_message(self):
10
+ return self._message
protobin/fields.py ADDED
@@ -0,0 +1,382 @@
1
+ import enum
2
+ import datetime
3
+ import math
4
+ from typing import Union, List
5
+
6
+ from protobin.errors import ParserError
7
+
8
+
9
+ class FieldEnum(enum.StrEnum):
10
+ ARRAY = 'array'
11
+ BITS = 'bits'
12
+ BOOL = 'bool'
13
+ CHAR = 'char'
14
+ DATE = 'date'
15
+ DATETIME = 'datetime'
16
+ FLAGS = 'flags'
17
+ FLOAT = 'float'
18
+ SIGNED = 'signed'
19
+ STRING = 'string'
20
+ TIME = 'time'
21
+ TIMESTAMP = 'timestamp'
22
+ UNSIGNED = 'unsigned'
23
+
24
+
25
+ class FieldBase:
26
+ bytes: int | None
27
+ key: Union[str, List[str]]
28
+ type: FieldEnum
29
+
30
+ def __init__(self, js):
31
+ self.type = js['type']
32
+ self.key = js.get('key')
33
+ self.bytes = js.get('bytes')
34
+
35
+ def decode(self, binary):
36
+ self.ensure_length(binary)
37
+ a, b = self.split(binary)
38
+ val = self.from_binary(a)
39
+ return val, b
40
+
41
+ def encode(self, data):
42
+ val = data.get(self.key)
43
+ return self.to_binary(val)
44
+
45
+ def ensure_length(self, binary):
46
+ if self.bytes:
47
+ if len(binary) < self.bytes:
48
+ raise ParserError('Binary has not enough data')
49
+
50
+ def from_binary(self, binary):
51
+ raise NotImplementedError()
52
+
53
+ @staticmethod
54
+ def to_int(n):
55
+ lo = n % 16
56
+ hi = n // 16
57
+ return hi * 10 + lo
58
+
59
+ @staticmethod
60
+ def get_nible(binary):
61
+ hexa = ord(binary[0:1])
62
+ lo = hexa % 16
63
+ hi = hexa // 16
64
+ nible = hi * 10 + lo
65
+ return nible, binary[1:]
66
+
67
+ def to_binary(self, val):
68
+ raise NotImplementedError()
69
+
70
+ def to_nible(self, n):
71
+ tens = int(n / 10)
72
+ units = n % 10
73
+ return int(tens * 16 + units)
74
+
75
+ def split(self, binary):
76
+ if self.bytes:
77
+ return binary[:self.bytes], binary[self.bytes:]
78
+ self.bytes = binary[0]
79
+ return binary[1:self.bytes + 1], binary[self.bytes + 1:]
80
+
81
+ def to_dict(self):
82
+ return {
83
+ 'key': self.key,
84
+ 'bytes': self.bytes,
85
+ 'type': self.type
86
+ }
87
+
88
+
89
+ class FieldArray(FieldBase):
90
+ length: int
91
+
92
+ def __init__(self, js):
93
+ super().__init__(js)
94
+ self.array = js['array']
95
+
96
+ def decode(self, binary):
97
+ self.length = binary[0]
98
+ binary = binary[1:]
99
+ val, binary = self.from_binary(binary)
100
+ return val, binary
101
+
102
+ def to_dict(self):
103
+ d = super().to_dict()
104
+ d['array'] = self.array
105
+ return d
106
+
107
+ def to_binary(self, val):
108
+ binary = b''
109
+ length = len(val)
110
+ binary += length.to_bytes(1, 'big')
111
+ for i in range(length):
112
+ fields = [FIELD_MAP[f['type']](f) for f in self.array]
113
+ for f in fields:
114
+ binary += f.encode(val[i])
115
+ return binary
116
+
117
+ def from_binary(self, binary):
118
+ lista = []
119
+ for i in range(self.length):
120
+ data = {}
121
+ fields = [FIELD_MAP[f['type']](f) for f in self.array]
122
+ for f in fields:
123
+ val, binary = f.decode(binary)
124
+ data[f.key] = val
125
+ lista.append(data)
126
+ return lista, binary
127
+
128
+
129
+ class FieldBits(FieldBase):
130
+ length: int
131
+
132
+ def __init__(self, js):
133
+ super().__init__(js)
134
+ self.length = js.get('length', 0)
135
+ self.bytes = math.ceil(self.length / 8)
136
+
137
+ def split(self, binary):
138
+ if not self.length:
139
+ self.length = binary[0]
140
+ self.bytes = math.ceil(self.length / 8)
141
+ return binary[1:self.bytes + 1], binary[self.bytes + 1:]
142
+
143
+ def to_binary(self, val: List[bool]):
144
+ if len(val) == 0:
145
+ return b'\x00'
146
+ binary = b''
147
+ if len(val) % 8:
148
+ bits = '0' * (8 - (len(val) % 8))
149
+ else:
150
+ bits = ''
151
+ for b in val:
152
+ bits += '1' if b else '0'
153
+ length = int(len(bits) / 8)
154
+ binary += len(val).to_bytes(1, 'big', signed=False)
155
+ binary += int(bits, 2).to_bytes(length, 'big', signed=False)
156
+ return binary
157
+
158
+ def from_binary(self, binary):
159
+ numero = int.from_bytes(binary, 'big', signed=False)
160
+ bits = bin(numero)[2:]
161
+ val = [False] * 8
162
+ for b in bits:
163
+ val.append(b == '1')
164
+ val = val[-self.length:]
165
+ return val
166
+
167
+
168
+ class FieldBool(FieldBase):
169
+
170
+ bytes = 1
171
+
172
+ def to_binary(self, val):
173
+ return val.to_bytes(1, 'big', signed=False)
174
+
175
+ def from_binary(self, binary):
176
+ return bool(int.from_bytes(binary, 'big', signed=False))
177
+
178
+
179
+ class FieldChar(FieldBase):
180
+ bytes = 1
181
+
182
+ def to_binary(self, val):
183
+ if val is None:
184
+ return b''
185
+ return val.encode('utf')
186
+
187
+ def from_binary(self, binary):
188
+ return binary[:self.bytes].decode('utf')
189
+
190
+
191
+ class FieldDate(FieldBase):
192
+
193
+ def __init__(self, js):
194
+ super().__init__(js)
195
+ self.bytes = 3
196
+
197
+ def to_binary(self, val: datetime.datetime | str):
198
+ if isinstance(val, str):
199
+ val = datetime.datetime.strptime(val, '%Y-%m-%d').date()
200
+ return bytes([
201
+ self.to_nible(val.day),
202
+ self.to_nible(val.month),
203
+ self.to_nible(val.year - 2000)
204
+ ])
205
+
206
+ def from_binary(self, binary):
207
+ d, binary = self.get_nible(binary)
208
+ m, binary = self.get_nible(binary)
209
+ y, binary = self.get_nible(binary)
210
+ return datetime.datetime(2000 + y, m, d).date()
211
+
212
+
213
+ class FieldDateTime(FieldBase):
214
+
215
+ def __init__(self, js):
216
+ super().__init__(js)
217
+ self.bytes = 6
218
+
219
+ def to_binary(self, val: datetime.datetime | str):
220
+ if isinstance(val, str):
221
+ val = datetime.datetime.strptime(val, '%Y-%m-%d %H:%M:%S').date()
222
+ return bytes([
223
+ self.to_nible(val.day),
224
+ self.to_nible(val.month),
225
+ self.to_nible(val.year - 2000),
226
+ self.to_nible(val.hour),
227
+ self.to_nible(val.minute),
228
+ self.to_nible(val.second)
229
+ ])
230
+
231
+ def from_binary(self, binary):
232
+ d, binary = self.get_nible(binary)
233
+ m, binary = self.get_nible(binary)
234
+ y, binary = self.get_nible(binary)
235
+ H, binary = self.get_nible(binary)
236
+ M, binary = self.get_nible(binary)
237
+ S, binary = self.get_nible(binary)
238
+ return datetime.datetime(2000 + y, m, d, H, M, S)
239
+
240
+
241
+ class FieldFlags(FieldBase):
242
+ keys: List[str]
243
+
244
+ def __init__(self, js):
245
+ super().__init__(js)
246
+ self.keys = js.get('keys')
247
+ self.length = len(self.keys)
248
+ self.bytes = math.ceil(self.length / 8)
249
+
250
+ def encode(self, data):
251
+ return self.to_binary(data)
252
+
253
+ def from_binary(self, binary):
254
+ numero = int.from_bytes(binary[:self.bytes], 'big', signed=False)
255
+ bits = bin(numero)[2:]
256
+ flags = [False] * 8
257
+ for b in bits:
258
+ flags.append(b == '1')
259
+ val = {}
260
+ order = -len(self.keys)
261
+ for k in self.keys:
262
+ val[k] = flags[order]
263
+ order += 1
264
+ return val
265
+
266
+ def to_binary(self, data):
267
+ bits = '0' * (8 - (len(self.keys) % 8))
268
+ for k in self.keys:
269
+ bits += '1' if data[k] else '0'
270
+ return int(bits, 2).to_bytes(self.bytes, 'big', signed=False)
271
+
272
+
273
+ class FieldFloat(FieldBase):
274
+
275
+ def __init__(self, js):
276
+ super().__init__(js)
277
+ self.decimales = js['decimales']
278
+
279
+ def from_binary(self, binary):
280
+ val = int.from_bytes(binary[:self.bytes], 'big', signed=True)
281
+ return val / (10 ** self.decimales)
282
+
283
+ def to_binary(self, val):
284
+ return int(round(val * (10 ** self.decimales))).to_bytes(self.bytes, 'big', signed=True)
285
+
286
+ def to_dict(self):
287
+ d = super().to_dict()
288
+ d['decimales'] = self.decimales
289
+ return d
290
+
291
+
292
+ class FieldSigned(FieldBase):
293
+
294
+ def to_binary(self, val):
295
+ if val is None:
296
+ val = 0
297
+ maximo = 256 ** self.bytes / 2 - 1
298
+ minimo = - maximo - 1
299
+ val = max(min(val, maximo), minimo)
300
+ return int(val).to_bytes(self.bytes, 'big', signed=True)
301
+
302
+ def from_binary(self, binary):
303
+ return int.from_bytes(binary, 'big', signed=True)
304
+
305
+
306
+ class FieldString(FieldBase):
307
+
308
+ def to_binary(self, val):
309
+ if self.bytes == 0:
310
+ utf = str(val).encode('utf')[:255]
311
+ return len(utf).to_bytes(1, 'big') + utf
312
+
313
+ def from_binary(self, binary):
314
+ if self.bytes == 0:
315
+ self.bytes = int.from_bytes(binary[:1], 'big', signed=False)
316
+ binary = binary[1:]
317
+ return binary[:self.bytes].decode('utf')
318
+
319
+
320
+ class FieldTime(FieldBase):
321
+
322
+ bytes = 2
323
+
324
+ def to_binary(self, val: datetime.datetime | str):
325
+ if isinstance(val, str):
326
+ val = datetime.datetime.strptime(val, '%H:%M').date()
327
+ return bytes([
328
+ self.to_nible(val.hour),
329
+ self.to_nible(val.minute)
330
+ ])
331
+
332
+ def from_binary(self, binary):
333
+ H, binary = self.get_nible(binary)
334
+ M, binary = self.get_nible(binary)
335
+ return datetime.time(H, M)
336
+
337
+
338
+ class FieldTimestamp(FieldBase):
339
+
340
+ def __init__(self, js):
341
+ super().__init__(js)
342
+ self.bytes = 8
343
+
344
+ def to_binary(self, val: datetime.datetime | str):
345
+ timestamp = val.timestamp() * 1000000
346
+ return int(timestamp).to_bytes(8, 'big', signed=False)
347
+
348
+ def from_binary(self, binary):
349
+ d = int.from_bytes(binary, 'big')
350
+ return datetime.datetime.fromtimestamp(d / 1000000)
351
+
352
+
353
+ class FieldUnsigned(FieldBase):
354
+
355
+ def to_binary(self, val):
356
+ if val is None:
357
+ val = 0
358
+ max_value = 256 ** self.bytes - 1
359
+ val = min(val, max_value)
360
+ if val < 0:
361
+ raise ValueError('Negative values not allowed')
362
+ return int(val).to_bytes(self.bytes, 'big', signed=False)
363
+
364
+ def from_binary(self, binary):
365
+ return int.from_bytes(binary[:self.bytes], 'big', signed=False)
366
+
367
+
368
+ FIELD_MAP = {
369
+ 'array': FieldArray,
370
+ 'bits': FieldBits,
371
+ 'bool': FieldBool,
372
+ 'char': FieldChar,
373
+ 'date': FieldDate,
374
+ 'datetime': FieldDateTime,
375
+ 'flags': FieldFlags,
376
+ 'float': FieldFloat,
377
+ 'signed': FieldSigned,
378
+ 'string': FieldString,
379
+ 'time': FieldTime,
380
+ 'timestamp': FieldTimestamp,
381
+ 'unsigned': FieldUnsigned,
382
+ }
protobin/protocol.py ADDED
@@ -0,0 +1,53 @@
1
+ import json
2
+
3
+ from protobin.fields import FieldBase, FIELD_MAP
4
+
5
+
6
+ class Format:
7
+
8
+ fields: [FieldBase]
9
+
10
+ def __init__(self, fields: [object]):
11
+ self.fields = []
12
+ for f in fields:
13
+ self.fields.append(FIELD_MAP[f['type']](f))
14
+
15
+ def encode(self, data):
16
+ binary = b''
17
+ for f in self.fields:
18
+ binary += f.encode(data)
19
+ return binary
20
+
21
+ def decode(self, binary):
22
+ data = {}
23
+ for f in self.fields:
24
+ val, binary = f.decode(binary)
25
+ if f.key:
26
+ data[f.key] = val
27
+ else:
28
+ for k in f.keys:
29
+ data[k] = val[k]
30
+ return data
31
+
32
+ def to_dict(self):
33
+ return [f.to_dict() for f in self.fields]
34
+
35
+
36
+ class Protocol:
37
+
38
+ def __init__(self, file=None, js=None):
39
+ if file:
40
+ with open(file, 'r') as f:
41
+ js = json.loads(f.read())
42
+ self.formats = {}
43
+ for k in js.keys():
44
+ self.formats[k] = Format(js[k])
45
+
46
+ def temp_format(self, k):
47
+ return self.formats[k].to_dict()
48
+
49
+ def encode(self, data, format):
50
+ return self.formats[format].encode(data)
51
+
52
+ def decode(self, binary, format):
53
+ return self.formats[format].decode(binary)
@@ -0,0 +1,51 @@
1
+ Metadata-Version: 2.3
2
+ Name: protobin
3
+ Version: 0.0.1
4
+ Summary: Python library for encode and decode data in protobin format
5
+ Project-URL: Homepage, https://github.com/drmelectronic/protobin-python
6
+ Project-URL: Bug Tracker, https://github.com/drmelectronic/protobin-python/issues
7
+ Author-email: Daniel Robles <drm.electronic@gmail.com>
8
+ License: MIT License
9
+
10
+ Copyright (c) [Año] [Tu Nombre]
11
+
12
+ Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ of this software and associated documentation files (the "Software"), to deal
14
+ in the Software without restriction, including without limitation the rights
15
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
+ copies of the Software, and to permit persons to whom the Software is
17
+ furnished to do so, subject to the following conditions:
18
+
19
+ The above copyright notice and this permission notice shall be included in all
20
+ copies or substantial portions of the Software.
21
+
22
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
+ SOFTWARE. 1
29
+ 1. en.wikipedia.org
30
+ en.wikipedia.org
31
+ License-File: LICENSE.txt
32
+ Classifier: License :: OSI Approved :: MIT License
33
+ Classifier: Operating System :: OS Independent
34
+ Classifier: Programming Language :: Python :: 3
35
+ Requires-Python: >=3.9
36
+ Description-Content-Type: text/markdown
37
+
38
+ # protobin-python
39
+
40
+ **protobin-python** es una biblioteca Python diseñada para facilitar la interacción con el formato de transferencia de datos Protobin en modo binario. Esta biblioteca proporciona una interfaz sencilla y eficiente para:
41
+
42
+ * **Serializar** objetos Python en datos Protobin.
43
+ * **Deserializar** datos Protobin en objetos Python.
44
+ * **Validar** la integridad de los datos Protobin.
45
+
46
+ ## Instalación
47
+
48
+ Para instalar `protobin-python`, puedes utilizar pip:
49
+
50
+ ```bash
51
+ pip install protobin-python
@@ -0,0 +1,8 @@
1
+ protobin/__init__.py,sha256=T4NlE7q7WcEfHWfNGNEfLZ1lRFMDXRZNP0RgSPxZuF8,30
2
+ protobin/errors.py,sha256=YGdDNIYUDsqFGMjxvfJbRQ3SRkHuEFqN3TC1uFPfWcc,182
3
+ protobin/fields.py,sha256=Wx-lwNAffeoT6-iWiSScfZpVpbJjXdBkRBKU7FYlLKc,10069
4
+ protobin/protocol.py,sha256=uH78IlOlJE8tzacZ6w0XFHvap0k7zFoVmLqGEkj3zyI,1258
5
+ protobin-0.0.1.dist-info/METADATA,sha256=y54S64BJ7zyMQ1ZesHbUOgGlerldoxcxYz8Wd_efqPs,2365
6
+ protobin-0.0.1.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
7
+ protobin-0.0.1.dist-info/licenses/LICENSE.txt,sha256=R7QvoV5O-yUlJWKMB_L3sYxF8QBURvZglGBf3rZ1s5s,1109
8
+ protobin-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.25.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,23 @@
1
+ MIT License
2
+
3
+ Copyright (c) [Año] [Tu Nombre]
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE. 1
22
+ 1. en.wikipedia.org
23
+ en.wikipedia.org