-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencoder.py
More file actions
615 lines (450 loc) · 20.2 KB
/
encoder.py
File metadata and controls
615 lines (450 loc) · 20.2 KB
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
# NEED TO CATCH ALL NON INTS (NOT REALLY IMP)
# INT KEYS FOR DICTIONARY NEEDS TO BE CHECKED
import asyncio
import sys
from collections import defaultdict
from typing import Dict, List, Tuple
from headers import *
# A custom Exception class used as an early exit for the match case statement in python
class _MyBreak(Exception): pass
class Example00:
def __init__(self):
self.integer = 0
class Example01:
def __init__(self):
self.string = "hello"
class Example02:
def __init__(self):
self.list = [1, 1, 1, 1, 1]
class Example03:
def __init__(self):
self.list = ['1', '2', '3', '4', '5']
class Example04:
def __init__(self):
self.list = ["apple", "banana", "cherry", "date", "elderberry"]
class Example05:
def __init__(self):
self.list = ['a', 'b', 'c', 'd', 'e']
class Example06:
def __init__(self):
self.list = ['-1', '-2.5033', '3.05e10', '4.11', '-5.655']
class Example07:
def __init__(self):
self.list = [-1, -2.5033, 3.05e10, 4.11, -5.655, 0.12412, -0.221]
class Example08:
def __init__(self):
self.list = [-1, 'a', 3.05e10, "abd", -5.655, "11.5", -0.221]
# class Example09:
# def __init__(self):
# self.dict = { 10: 11, 12: 13, 14: 14 }
class Example0:
def __init__(self):
self.details = { "nom": "abc", "roll": 15, "age": 1 }
self.values = [ {"a":"b", "n":"x"}, 121, "abr", { "axr": [-1, 'a', 3.05e10, "abd", -5.655, "11.5", -0.221], "l": "candy" } ]
self.values2 = [ {"a": {"a": "b"}, "n":"x"}, [-1, 'a', 3.05e10, "abd", -5.655, "11.5", -0.221], "abr", { "axr": [22, 13, 14], "l": "candy" } ]
self.name = "xyz"
self.age = 12
def __repr__(self):
return str(self.__dict__)
class Example10:
def __init__(self):
self.details = { "nom": {"a":"b", "n": [11, 13, 14]}, "roll": {"bb": 1, "axr": [-1, 'a', 3.05e10, "abd", -5.655, "11.5", -0.221] }, "age": 19 }
def __repr__(self):
return str(self.__dict__)
class Example1:
def __init__(self):
self.details = { "nom": {"a":"b", "n":[11, 13, 14]}, "roll": {"bb":1, "axr": [-1, 'a', 3.05e10, "abd", -5.655, "11.5", -0.221] }, "age": 19 }
self.values0 = [ {"a":"b", "n":"x"}, [-1, 'a', 3.05e10, "abd", -5.655, "11.5", -0.221], "abr", { "r": "candy" , "l": "candy" } ]
self.values1 = [ {"a":"b"}, "abr", { "r": "candy" , "l": "candy" } ]
self.values2 = { "nom": {"a":"b", "n":[{"a":"b"}, {"c":"d"}, 15]}, "roll": {"bb": {"p":"q"}, "axr": ["11", "12", "13"] }, "age": 35 }
def __repr__(self):
return str(self.__dict__)
class Example2:
def __init__(self):
self.details = { "nom": {"a":"b", "n":[11, 13, 14]}, "roll": {"bb":1, "axr": [-1, 'a', 3.05e10, "abd", -5.655, "11.5", -0.221] }, "age": 19 }
self.values0 = [ {"a":"b", "n":"x"}, [-1, 'a', 3.05e10, "abd", -5.655, "11.5", -0.221], "abr", { "r": "candy" , "l": "candy" } ]
def __repr__(self):
return str(self.__dict__)
class Graph0:
def __init__(self):
self.graph = { "a": Example0(),
"b": ["a", "d"],
"c": [ Example1(), Example0(), "b" ],
"d": ["k"],
"k": ["d"]
}
def __repr__(self):
return str(self.__dict__)
class Graph1:
def __init__(self):
self.graph = { "a": [ Example0(), Example1(), Example0() ],
"b": ["a", Example0(), "d"],
"c": [ Example0(), "a", "b" ],
"d": [Example1()],
"k": ["d"]
}
def __repr__(self):
return str(self.__dict__)
class SimpleGraph:
def __init__(self):
self.graph = { "a": "b", "b": "c", "c": "d", "l": [ { "a" : { "b" : Example0() } } ] }
def __repr__(self):
return str(self.__dict__)
class GrimRepr:
def __init__(self):
self.fog = [ Graph0(), SimpleGraph(), Graph1(), Graph0() ]
def __repr__(self):
return str(self.__dict__)
class BEncoderOperation(BEncoder):
def __init__(self):
super().__init__()
async def encode_int(self, data: int) -> Tuple[BInteger, str]:
"""
Abstract base class to encode integer data into bencoding format.
Args:
data (int): Integer data.
Returns:
A BInteger object.
data (str): The remaining data.
Errors:
ValueError: If the data is invalid.
"""
start_index = 0
end_index = start_index + 1
try:
while data[end_index].isdigit() or data[end_index] == '.' \
or data[end_index] == 'e' or data[end_index] == '-':
end_index += 1
except IndexError as e:
print("Error Encode Int: Invalid data", str(e))
raise ValueError("Invalid data")
try:
output = data[start_index:end_index]
except ValueError as e:
print("Error Encode Int: ", str(e))
raise ValueError("Invalid data")
data = data[end_index:]
return BInteger(output), data
async def encode_string(self, data: str) -> Tuple[BString, str]:
"""
Method to encode string data into bencoding format.
Args:
data (str): String data.
Returns:
A BString object.
data (str): The remaining data.
Errors:
ValueError: If the data is invalid
"""
start_index = 0
data = data[1:]
try:
end_index = data.find("'")
except IndexError as e:
print("Error Encode String: Invalid data", str(e))
raise ValueError("Invalid data")
try:
output = data[start_index:end_index]
except ValueError as e:
print("Error Encode String: ", str(e))
raise ValueError("Invalid data")
data = data[end_index + 1:]
return BString(output), data
async def encode_list(self, data: str) -> Tuple[BList, str]:
"""
Method to bencode a python list into its constituent components, and recursively encode them too.
Args:
data (str): The string representation of the list to be encoded.
Returns:
Tuple[BList, str]: A tuple containing the bencoded list and the remaining string.
data (str): The remaining data.
Errors:
ValueError: If the data is invalid.
"""
rlist = BList([])
if data[0] == '[':
data = data[1:]
else:
raise ValueError("Invalid data")
while data:
try:
split = next( i for i, c in enumerate(data) if c in {'\'', ':'," ",' ', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '{', '}', '[', ']', ','})
except StopIteration as e:
# print("LSPLIT Error Parse List: Invalid data", str(e))
break
# print(f"LSPLIT: {split} {data[split]}")
try:
match data[split]:
case '\'' | '"':
# Doing this to ensure that end of string of the entire structure is handled
if data[0] != ']':
if split == len(data):
data = ""
raise _MyBreak()
value, data = await self.encode_string(data)
rlist.append_list(value)
case '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9':
value, data = await self.encode_int(data)
rlist.append_list(value)
case '-':
if len(data) == 1:
value, data = await self.encode_string(data)
elif len(data) >= 1:
value, data = await self.encode_int(data)
rlist.append_list(value)
case '{':
value, data = await self.encode_dictionary(data)
rlist.append_list(value)
case '[':
value, data = await self.encode_list(data)
rlist.append_list(value)
case ',' | ' ' | " " | ':':
# There is no comma, space or colon seperator in bencoding, but in python we need to handle it here,
# and ignore it
data = data[split+1:]
case ']':
if len(data) > 1:
if data[0] == ']':
data = data[1:]
# print("Clean Parse List!")
# print("Lrem data:", str(data))
return rlist, data
else:
data = ""
return rlist, data
case _:
# print(f"LNOMATCH:{data[split]}")
raise ValueError("LNO MATCH Error Parse List: Invalid data")
break
except _MyBreak:
pass
return rlist, data
async def encode_dictionary(self, data: str) -> Tuple[BDictionary, str]:
"""
Method to bencode a python dictionary into its constituent components, and recursively encode them too.
Args:
data (str): The string representation of the dictionary to be encoded.
Returns:
Tuple[BDictionary, str]: A tuple containing the bencoded dictionary and the remaining string.
data (str): The remaining data.
Errors:
ValueError: If the data is invalid.
"""
rdict = BDictionary({})
if data[0] == '{':
data = data[1:]
else:
raise ValueError("Invalid data")
while data:
try:
split = next(i for i, c in enumerate(data) if c in {'\'', ':'," ",' ', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '{', '}', '[', ']', ','})
except StopIteration as e:
print("DSPLIT: Error Parse Dictionary: Invalid data", str(e))
break
# print(f"DSPLIT: {split} {data[split]}")
try:
match data[split]:
case '\'' | '"':
# Doing this to ensure that end of string of the entire structure is handled
if data[0]!= '}':
if split == len(data):
data = ""
raise _MyBreak()
# Here we need to ensure that we can catch int keys,
# and convert them to string keys.
inner_split = data.find(":")
key_string = data[split:inner_split]
# print("key_string: ", key_string)
if key_string.isdigit():
key, _ = await self.encode_int(key_string)
else:
key, _ = await self.encode_string(key_string)
data = data[inner_split+1:]
# print("key: ", key, type(key))
# print("data: ", data)
# Check for duplicate keys is not required as we are using a python dictionary.
# Clean the data till you hit a string value, trim the leading and trailing spaces
data = data.strip()
# print("key: ", key)
# print("remaining data:", data)
# Check if the value of the dictionary is NOT a string, if not, then break and use the other parse functions
if data[0] in {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '{', '['}:
# print("DVAL BREAK HAPPENED")
raise _MyBreak()
# print("remaining data:", data)
value, data = await self.encode_string(data)
rdict.append_dictionary(key, value)
# print("RDICT:", rdict, "remaining data:", data)
case '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9':
value, data = await self.encode_int(data)
rdict.append_dictionary(key, value)
case '-':
if len(data) == 1:
value, data = await self.encode_string(data)
elif len(data) >= 1:
value, data = await self.encode_int(data)
rdict.append_dictionary(key, value)
case '{':
value, data = await self.encode_dictionary(data)
rdict.append_dictionary(key, value)
case '[':
value, data = await self.encode_list(data)
rdict.append_dictionary(key, value)
case ',' | ' ' | " " | ':':
# There is no comma, space or colon seperator in bencoding, but in python we need to handle it here,
# and ignore it
data = data[split+1:]
case '}':
if len(data) > 1:
if data[0] == '}':
data = data[1:]
# print("Clean Parse Dictionary!")
# print("Drem data:", str(data))
return rdict, data
else:
data = ""
return rdict, data
case _:
# print(f"DNOMATCH:{data[split]}")
raise ValueError("DNO MATCH: Error Parse Dictionary: Invalid data")
break
except _MyBreak:
pass
return rdict, data
async def encode(self, data: str) -> BDictionary:
"""
Abstract base class to encode __dict__ representation of data into bencoding format.
Args:
data (str): __dict__ representation of data.
Returns:
A BDictionary object.
Errors:
ValueError: If the data is invalid.
"""
try:
output, remaining_data = await self.encode_dictionary(data)
if len(remaining_data) > 0:
print("Remaining Data: ", str(remaining_data))
else:
print("Clean Encode of Entire Data!")
except ValueError as e:
print("Error Parse: ", str(e))
raise ValueError("Invalid data")
return output
async def tests():
encoder = BEncoderOperation()
# PASS: Integer test
# example00 = str(Example00().__dict__)
# print(example00)
# encoded = await encoder.encode(example00)
# print("output:", encoded)
# # PASS: Dict Test
# example01 = str(Example01().__dict__)
# print(example01)
# encoded = await encoder.encode(example01)
# print("output:", encoded)
# # PASS: List test with integer values
# example02 = str(Example02().__dict__)
# print(example02)
# encoded = await encoder.encode(example02)
# print("output:", encoded)
# # PASS: List test with string integer values
# example03 = str(Example03().__dict__)
# print(example03)
# encoded = await encoder.encode(example03)
# print("output:", encoded)
# # PASS: List test with str values
# example04 = str(Example04().__dict__)
# print(example04)
# encoded = await encoder.encode(example04)
# print("output:", encoded)
# # PASS: List test with char values
# example05 = str(Example05().__dict__)
# print(example05)
# encoded = await encoder.encode(example05)
# print("output:", encoded)
# # PASS: List test with mixed values
# example06 = str(Example06().__dict__)
# print(example06)
# encoded = await encoder.encode(example06)
# print("output:", encoded)
# # PASS: List test with mixed float values
# example07 = str(Example07().__dict__)
# print(example07)
# encoded = await encoder.encode(example07)
# print("output:", encoded)
# # PASS: List test with mixed values
# example08 = str(Example08().__dict__)
# print(example08)
# encoded = await encoder.encode(example08)
# print("output:", encoded)
# # PASS: Mixed datastructure x0
# example1 = str(Example1().__dict__)
# print(example1)
# encoded = await encoder.encode(example1)
# print("output:", encoded)
# # PASS: Mixed datastructure x1
# example10 = str(Example10().__dict__)
# print(example10)
# encoded = await encoder.encode(example10)
# print("output:", encoded)
# PASS: Mixed datastructure x2
# example2 = str(Example2().__dict__)
# print(example2)
# encoded = await encoder.encode(example2)
# print("output:", encoded)
# # PASS: Graph data structure 0
# graph0 = str(Graph0().__dict__)
# print(graph0)
# encoded = await encoder.encode(graph0)
# print("output:", encoded)
# # PASS: Graph data structure 1
# graph1 = str(Graph1().__dict__)
# print(graph1)
# encoded = await encoder.encode(graph1)
# print("output:", encoded)
# # PASS: GRIM REPR :E
# grim_repr = str(GrimRepr().__dict__)
# print(grim_repr)
# encoded_grim = await encoder.encode(grim_repr)
# print("output:", encoded_grim)
class BencoderAPI:
"""
API for encoding data into bencoding format.
"""
@staticmethod
async def encode(data: str) -> str:
"""
Create a BEncoderOperation object and encode the data.
"""
encoder = BEncoderOperation()
encoded = await encoder.encode(data)
return str(encoded)
async def task_run(filename):
"""
Task to read data from a file.
"""
with open(filename, 'r') as file:
data = file.read()
encoder = BEncoderOperation()
encoded = await encoder.encode(data)
return encoded, filename
async def main():
if len(sys.argv) < 2:
print("Usage: python3 encoder.py <filename>")
sys.exit(1)
filenames = sys.argv[1:]
wait_list = []
for filename in filenames:
async with asyncio.TaskGroup() as task_group:
task = task_group.create_task(task_run(filename))
wait_list.append(task)
for task in asyncio.as_completed(wait_list):
output, filename = await task
print(f"Filename: {filename}")
print(f"Output: {str(output)}")
return 0
if __name__ == "__main__":
# asyncio.run(tests())
asyncio.run(main())
sys.exit(0)