bcoder 1.0__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.

Potentially problematic release.


This version of bcoder might be problematic. Click here for more details.

bcoder/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ from .decoder import BDecoder
2
+ from .encoder import BEncoder
3
+
4
+
5
+ __all__ = [
6
+ "BDecoder",
7
+ "BEncoder",
8
+ ]
bcoder/decoder.py ADDED
@@ -0,0 +1,98 @@
1
+ from enum import Enum
2
+ from typing import Callable, Union
3
+
4
+ from .errors import DecodeError
5
+
6
+ BDecodeType = Union[
7
+ dict[bytes, "BDecodeType"],
8
+ bytes,
9
+ list["BDecodeType"],
10
+ int,
11
+ ]
12
+
13
+
14
+ class DecodeType(Enum):
15
+ DICTIONARY = b"d"
16
+ STRING = b"1234567890"
17
+ LIST = b"l"
18
+ INTEGER = b"i"
19
+
20
+ @classmethod
21
+ def from_code(cls, code: int) -> "DecodeType":
22
+ return next(filter(lambda m: code in m.value, cls))
23
+
24
+
25
+ class BDecoder:
26
+ def __init__(self):
27
+ self._data = None
28
+ self._i = None
29
+
30
+ self._decoders = {
31
+ DecodeType.DICTIONARY: self._decode_dict,
32
+ DecodeType.STRING: self._decode_str,
33
+ DecodeType.LIST: self._decode_list,
34
+ DecodeType.INTEGER: self._decode_int,
35
+ }
36
+
37
+ def decode(self, data: bytes) -> BDecodeType:
38
+ self._data = data
39
+ self._i = 0
40
+
41
+ return self._get_decoder()()
42
+
43
+ def _get_decoder(self) -> Callable[["BDecoder"], BDecodeType]:
44
+ return self._decoders[DecodeType.from_code(self._data[self._i])]
45
+
46
+ def _decode_dict(self) -> dict[bytes, BDecodeType]:
47
+ result = {}
48
+
49
+ self._i += 1
50
+
51
+ while self._data[self._i] != ord("e"):
52
+ key = self._decode_str()
53
+ result[key] = self._get_decoder()()
54
+
55
+ self._i += 1
56
+
57
+ return result
58
+
59
+ def _decode_str(self) -> bytes:
60
+ if self._data[self._i] == ord("0") and self._data[self._i + 1] != ord(":"):
61
+ raise DecodeError(f"Invalid leading '0' value for str in {self._i} position")
62
+
63
+ colon = self._data.index(b":", self._i)
64
+ length = int(self._data[self._i: colon])
65
+
66
+ start = colon + 1
67
+ end = start + length
68
+
69
+ self._i = end
70
+
71
+ return self._data[start:end]
72
+
73
+ def _decode_list(self) -> list[BDecodeType]:
74
+ result = []
75
+
76
+ self._i += 1
77
+
78
+ while self._data[self._i] != ord("e"):
79
+ result.append(self._get_decoder()())
80
+
81
+ self._i += 1
82
+
83
+ return result
84
+
85
+ def _decode_int(self) -> int:
86
+ self._i += 1
87
+
88
+ if self._data[self._i] == ord("-") and self._data[self._i + 1] == ord("0"):
89
+ raise DecodeError(f"Invalid '-0' value for int in {self._i} position")
90
+ if self._data[self._i] == ord("0") and self._data[self._i + 1] != ord("e"):
91
+ raise DecodeError(f"Invalid leading '0' value for int in {self._i} position")
92
+
93
+ start = self._i
94
+ end = self._data.index(b"e", self._i)
95
+
96
+ self._i = end + 1
97
+
98
+ return int(self._data[start:end])
bcoder/encoder.py ADDED
@@ -0,0 +1,71 @@
1
+ from enum import Enum
2
+ from typing import Callable, Union
3
+
4
+ BEncodeType = Union[
5
+ dict[Union[str, bytes], "BEncodeType"],
6
+ str,
7
+ list["BEncodeType"],
8
+ int,
9
+ bytes,
10
+ ]
11
+
12
+
13
+ class EncodeType(Enum):
14
+ DICTIONARY = dict
15
+ STRING = str
16
+ LIST = list
17
+ INTEGER = int
18
+ BYTES = bytes
19
+
20
+ @classmethod
21
+ def from_value(cls, value: BEncodeType) -> "EncodeType":
22
+ return next(filter(lambda m: isinstance(value, m.value), cls))
23
+
24
+
25
+ class BEncoder:
26
+ def __init__(self, encoding: str = "utf-8"):
27
+ self._encoding = encoding
28
+
29
+ self._encoders = {
30
+ EncodeType.DICTIONARY: self._encode_dict,
31
+ EncodeType.STRING: self._encode_str,
32
+ EncodeType.LIST: self._encode_list,
33
+ EncodeType.INTEGER: self._encode_int,
34
+ EncodeType.BYTES: self._encode_bytes,
35
+ }
36
+
37
+ def encode(self, data: BEncodeType) -> bytes:
38
+ return self._get_encoder(data)(data)
39
+
40
+ def _get_encoder(self, value: BEncodeType) -> Callable[["BEncoder", BEncodeType], bytes]:
41
+ return self._encoders[EncodeType.from_value(value)]
42
+
43
+ def _encode_dict(self, d: dict[str, BEncodeType]) -> bytes:
44
+ encoded_dict = b"".join(
45
+ self._get_encoder(k)(k) + self._get_encoder(v)(v)
46
+ for k, v in d.items()
47
+ )
48
+
49
+ return b"d" + encoded_dict + b"e"
50
+
51
+ def _encode_str(self, s: str) -> bytes:
52
+ length = str(len(s)).encode(self._encoding)
53
+ encoded_str = s.encode(self._encoding)
54
+
55
+ return length + b":" + encoded_str
56
+
57
+ def _encode_list(self, l: list) -> bytes:
58
+ encoded_values = b"".join(
59
+ self._get_encoder(v)(v)
60
+ for v in l
61
+ )
62
+
63
+ return b"l" + encoded_values + b"e"
64
+
65
+ def _encode_int(self, i: int) -> bytes:
66
+ return b"i" + str(i).encode(self._encoding) + b"e"
67
+
68
+ def _encode_bytes(self, b: bytes) -> bytes:
69
+ length = str(len(b)).encode(self._encoding)
70
+
71
+ return length + b":" + b
bcoder/errors.py ADDED
@@ -0,0 +1,2 @@
1
+ class DecodeError(ValueError):
2
+ pass
@@ -0,0 +1,7 @@
1
+ Copyright (c) 2025 Mykola Bezrukyi
2
+
3
+ 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:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ 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.
@@ -0,0 +1,67 @@
1
+ Metadata-Version: 2.2
2
+ Name: bcoder
3
+ Version: 1.0
4
+ Summary: Tool to decode and encode .torrent files
5
+ Author-email: Mykola Bezrukyi <kolya.bezrukiy.03@gmail.com>
6
+ License: Copyright (c) 2025 Mykola Bezrukyi
7
+
8
+ 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:
9
+
10
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
11
+
12
+ 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.
13
+
14
+ Requires-Python: >=3.13
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+
18
+ # bcoder
19
+
20
+ ### About
21
+
22
+ ---
23
+
24
+ A Python package to handle bencoded values, a serialization format commonly used in `.torrent` files within
25
+ the <u>BitTorrent</u> protocol.
26
+
27
+ ### Usage
28
+
29
+ ---
30
+
31
+ There are __2__ types of classes:
32
+ - `BDecoder` - handle decoding of bencoded data to common Python types
33
+ - `BEncoder` - handle encoding of common Python types to `bytes` type
34
+
35
+ Example of `BDecoder` usage:
36
+ ```python
37
+ from bcoder import BDecoder
38
+
39
+ decoder = BDecoder()
40
+
41
+ with open("file.torrent", "rb") as file:
42
+ data = file.read()
43
+
44
+ decoded = decoder.decode(data)
45
+ ```
46
+
47
+ Example of `BEncoder` usage:
48
+ ```python
49
+ from bcoder import BEncoder
50
+
51
+ encoder = BEncoder()
52
+
53
+ data = {
54
+ b"announce-list": [
55
+ ["udp:..."],
56
+ ["udp:..."],
57
+ ],
58
+ "info": {
59
+ "piece": b"xfsasf",
60
+ "piece length": 123,
61
+ },
62
+ }
63
+
64
+ encoded = encoder.encode(data)
65
+ ```
66
+
67
+ __NOTE__: `BEncoder` can handle mixed types of Python strings - `bytes` and `str`.
@@ -0,0 +1,9 @@
1
+ bcoder/__init__.py,sha256=YhoSA1fEI8h_bS5RaaSTzBs-k0NyX74CapqS3Tx9KSY,108
2
+ bcoder/decoder.py,sha256=1HLnbIBNmJkLo2ucz03NJOEZEf0hogPzatxlXlwLoSo,2512
3
+ bcoder/encoder.py,sha256=_wSgHp0Gdp7Ge652qOSGnbxS5pq693HpGvjZG_7k-oA,1957
4
+ bcoder/errors.py,sha256=f_TLCf8wYOHxzKEa85-N1k9NHMk9pGhFut8FzpICr1c,40
5
+ bcoder-1.0.dist-info/LICENSE,sha256=ZrFAe1-xWQ3Sg7hEdYw9wVMIv7LnAcUL55OyqZxATB8,1059
6
+ bcoder-1.0.dist-info/METADATA,sha256=LzZH5dwCyN9G5bKAeZdOUz-fWNtxnMj3ctBJ29AU7VM,2292
7
+ bcoder-1.0.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
8
+ bcoder-1.0.dist-info/top_level.txt,sha256=u-ORiwqxmd9H_2ZxoVU2WY6AIDJ2adI5KxA734GIceY,7
9
+ bcoder-1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.8.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ bcoder