bcoder 2.0__py3-none-any.whl → 3.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.
bcoder/__init__.py CHANGED
@@ -1,8 +1,85 @@
1
- from .decoder import BDecoder
2
- from .encoder import BEncoder
1
+ import re
3
2
 
3
+ _INTEGER = re.compile(rb"i(0|-?[1-9][0-9]*)e")
4
+ _STRING_LENGTH = re.compile(rb"(0|[1-9][0-9]*):")
4
5
 
5
- __all__ = [
6
- "BDecoder",
7
- "BEncoder",
8
- ]
6
+ type Value = int | bytes | list[Value] | dict[bytes, Value]
7
+
8
+
9
+ class DecodeError(ValueError):
10
+ pass
11
+
12
+
13
+ def encode(value: Value) -> bytes:
14
+ match value:
15
+ case bytes():
16
+ return b"%d:%b" % (len(value), value)
17
+ case list():
18
+ return b"l" + b"".join(map(encode, value)) + b"e"
19
+ case dict():
20
+ if not all(isinstance(key, bytes) for key in value):
21
+ raise TypeError("dict keys must be bytes")
22
+
23
+ pairs = (encode(key) + encode(item) for key, item in sorted(value.items()))
24
+
25
+ return b"d" + b"".join(pairs) + b"e"
26
+ case int() if not isinstance(value, bool):
27
+ return b"i%de" % value
28
+ case _:
29
+ raise TypeError(f"cannot encode {type(value).__name__}")
30
+
31
+
32
+ def decode(data: bytes) -> Value:
33
+ value, end = _decode_value(data, 0)
34
+
35
+ if end != len(data):
36
+ raise DecodeError(f"trailing data at position {end}")
37
+
38
+ return value
39
+
40
+
41
+ def _decode_value(data: bytes, position: int) -> tuple[Value, int]:
42
+ match data[position : position + 1]:
43
+ case b"i":
44
+ integer = _INTEGER.match(data, position)
45
+
46
+ if not integer:
47
+ raise DecodeError(f"invalid integer at position {position}")
48
+
49
+ return int(integer[1]), integer.end()
50
+ case b"l":
51
+ items = []
52
+ position += 1
53
+
54
+ while data[position : position + 1] != b"e":
55
+ item, position = _decode_value(data, position)
56
+ items.append(item)
57
+
58
+ return items, position + 1
59
+ case b"d":
60
+ entries = {}
61
+ position += 1
62
+
63
+ while data[position : position + 1] != b"e":
64
+ key, position = _decode_string(data, position)
65
+ entries[key], position = _decode_value(data, position)
66
+
67
+ return entries, position + 1
68
+ case digit if digit.isdigit():
69
+ return _decode_string(data, position)
70
+ case _:
71
+ raise DecodeError(f"invalid value at position {position}")
72
+
73
+
74
+ def _decode_string(data: bytes, position: int) -> tuple[bytes, int]:
75
+ length = _STRING_LENGTH.match(data, position)
76
+
77
+ if not length:
78
+ raise DecodeError(f"invalid string at position {position}")
79
+
80
+ end = length.end() + int(length[1])
81
+
82
+ if end > len(data):
83
+ raise DecodeError(f"truncated string at position {position}")
84
+
85
+ return data[length.end() : end], end
@@ -0,0 +1,27 @@
1
+ Metadata-Version: 2.4
2
+ Name: bcoder
3
+ Version: 3.0
4
+ Summary: Tool to decode and encode .torrent files
5
+ Author: Mykola Bezrukyi
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.12
9
+ Project-URL: Homepage, https://github.com/mbezrukyi/bcoder
10
+ Description-Content-Type: text/markdown
11
+
12
+ # bcoder
13
+
14
+ Encode and decode [bencode](https://www.bittorrent.org/beps/bep_0003.html#bencoding), the format of `.torrent` files.
15
+
16
+ ```
17
+ pip install bcoder
18
+ ```
19
+
20
+ ```python
21
+ import bcoder
22
+
23
+ bcoder.encode({b"spam": [b"eggs", 42]}) # b"d4:spaml4:eggsi42eee"
24
+ bcoder.decode(b"d4:spaml4:eggsi42eee") # {b"spam": [b"eggs", 42]}
25
+ ```
26
+
27
+ Values are `int`, `bytes`, `list` and `dict` with `bytes` keys. `encode` raises `TypeError` for anything else. `decode` raises `bcoder.DecodeError` for malformed data.
@@ -0,0 +1,5 @@
1
+ bcoder/__init__.py,sha256=R33NIGWQKHNdiodSqY_9F0kf9vpp588olcWro9-8LSY,2528
2
+ bcoder-3.0.dist-info/licenses/LICENSE,sha256=ZrFAe1-xWQ3Sg7hEdYw9wVMIv7LnAcUL55OyqZxATB8,1059
3
+ bcoder-3.0.dist-info/WHEEL,sha256=G_-rrEibZr7OEM7zdH1dSO6s-VdjfnS5PA4CLAdI9Vw,80
4
+ bcoder-3.0.dist-info/METADATA,sha256=f4f1BYUFz6yx9s4CnqX4cmnzaFUkkaWqmeTLW_Y_LDw,781
5
+ bcoder-3.0.dist-info/RECORD,,
@@ -1,5 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (82.0.1)
2
+ Generator: uv 0.13.9
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
-
bcoder/decoder.py DELETED
@@ -1,86 +0,0 @@
1
- from enum import Enum
2
- from typing import 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._decoders = {
28
- DecodeType.DICTIONARY: self._decode_dict,
29
- DecodeType.STRING: self._decode_str,
30
- DecodeType.LIST: self._decode_list,
31
- DecodeType.INTEGER: self._decode_int,
32
- }
33
-
34
- def decode(self, data: bytes) -> BDecodeType:
35
- value, _ = self._decode(data, 0)
36
-
37
- return value
38
-
39
- def _decode(self, data: bytes, i: int) -> tuple[BDecodeType, int]:
40
- return self._decoders[DecodeType.from_code(data[i])](data, i)
41
-
42
- def _decode_dict(self, data: bytes, i: int) -> tuple[dict[bytes, BDecodeType], int]:
43
- result = {}
44
-
45
- i += 1
46
-
47
- while data[i] != ord("e"):
48
- key, i = self._decode_str(data, i)
49
- result[key], i = self._decode(data, i)
50
-
51
- return result, i + 1
52
-
53
- def _decode_str(self, data: bytes, i: int) -> tuple[bytes, int]:
54
- if data[i] == ord("0") and data[i + 1] != ord(":"):
55
- raise DecodeError(f"Invalid leading '0' value for str in {i} position")
56
-
57
- colon = data.index(b":", i)
58
- length = int(data[i:colon])
59
-
60
- start = colon + 1
61
- end = start + length
62
-
63
- return data[start:end], end
64
-
65
- def _decode_list(self, data: bytes, i: int) -> tuple[list[BDecodeType], int]:
66
- result = []
67
-
68
- i += 1
69
-
70
- while data[i] != ord("e"):
71
- value, i = self._decode(data, i)
72
- result.append(value)
73
-
74
- return result, i + 1
75
-
76
- def _decode_int(self, data: bytes, i: int) -> tuple[int, int]:
77
- i += 1
78
-
79
- if data[i] == ord("-") and data[i + 1] == ord("0"):
80
- raise DecodeError(f"Invalid '-0' value for int in {i} position")
81
- if data[i] == ord("0") and data[i + 1] != ord("e"):
82
- raise DecodeError(f"Invalid leading '0' value for int in {i} position")
83
-
84
- end = data.index(b"e", i)
85
-
86
- return int(data[i:end]), end + 1
bcoder/encoder.py DELETED
@@ -1,57 +0,0 @@
1
- from enum import Enum
2
- from typing import Callable, Union
3
-
4
- BEncodeType = Union[
5
- dict[bytes, "BEncodeType"],
6
- list["BEncodeType"],
7
- int,
8
- bytes,
9
- ]
10
-
11
-
12
- class EncodeType(Enum):
13
- DICTIONARY = dict
14
- LIST = list
15
- INTEGER = int
16
- BYTES = bytes
17
-
18
- @classmethod
19
- def from_value(cls, value: BEncodeType) -> "EncodeType":
20
- return next(filter(lambda m: isinstance(value, m.value), cls))
21
-
22
-
23
- class BEncoder:
24
- def __init__(self):
25
- self._encoders = {
26
- EncodeType.DICTIONARY: self._encode_dict,
27
- EncodeType.LIST: self._encode_list,
28
- EncodeType.INTEGER: self._encode_int,
29
- EncodeType.BYTES: self._encode_bytes,
30
- }
31
-
32
- def encode(self, data: BEncodeType) -> bytes:
33
- return self._get_encoder(data)(data)
34
-
35
- def _get_encoder(self, value: BEncodeType) -> Callable[["BEncoder", BEncodeType], bytes]:
36
- return self._encoders[EncodeType.from_value(value)]
37
-
38
- def _encode_dict(self, d: dict[bytes, BEncodeType]) -> bytes:
39
- encoded_dict = b"".join(
40
- self._encode_bytes(k) + self._get_encoder(v)(v)
41
- for k, v in sorted(d.items())
42
- )
43
-
44
- return b"d" + encoded_dict + b"e"
45
-
46
- def _encode_list(self, l: list) -> bytes:
47
- encoded_values = b"".join(
48
- self._get_encoder(v)(v)
49
- for v in l
50
- )
51
- return b"l" + encoded_values + b"e"
52
-
53
- def _encode_int(self, i: int) -> bytes:
54
- return b"i" + str(i).encode() + b"e"
55
-
56
- def _encode_bytes(self, b: bytes) -> bytes:
57
- return str(len(b)).encode() + b":" + b
bcoder/errors.py DELETED
@@ -1,2 +0,0 @@
1
- class DecodeError(ValueError):
2
- pass
@@ -1,69 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: bcoder
3
- Version: 2.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
- Project-URL: Homepage, https://github.com/mbezrukyi/bcoder
15
- Requires-Python: >=3.13
16
- Description-Content-Type: text/markdown
17
- License-File: LICENSE
18
- Dynamic: license-file
19
-
20
- # bcoder
21
-
22
- ### About
23
-
24
- ---
25
-
26
- A Python package to handle bencoded values, a serialization format commonly used in `.torrent` files within
27
- the <u>BitTorrent</u> protocol.
28
-
29
- ### Usage
30
-
31
- ---
32
-
33
- There are __2__ types of classes:
34
- - `BDecoder` - handle decoding of bencoded data to common Python types
35
- - `BEncoder` - handle encoding of common Python types to `bytes` type
36
-
37
- Example of `BDecoder` usage:
38
- ```python
39
- from bcoder import BDecoder
40
-
41
- decoder = BDecoder()
42
-
43
- with open("file.torrent", "rb") as file:
44
- data = file.read()
45
-
46
- decoded = decoder.decode(data)
47
- ```
48
-
49
- Example of `BEncoder` usage:
50
- ```python
51
- from bcoder import BEncoder
52
-
53
- encoder = BEncoder()
54
-
55
- data = {
56
- b"announce-list": [
57
- [b"udp:..."],
58
- [b"udp:..."],
59
- ],
60
- b"info": {
61
- b"piece": b"xfsasf",
62
- b"piece length": 123,
63
- },
64
- }
65
-
66
- encoded = encoder.encode(data)
67
- ```
68
-
69
- __NOTE__: `BEncoder` is spec-strict (BEP 3). Only `bytes`, `int`, `list`, and `dict` with `bytes` keys are accepted. Pass `str` through `.encode("utf-8")` yourself if you need to encode text.
@@ -1,9 +0,0 @@
1
- bcoder/__init__.py,sha256=YhoSA1fEI8h_bS5RaaSTzBs-k0NyX74CapqS3Tx9KSY,108
2
- bcoder/decoder.py,sha256=6UQr7BLr3idzhCGW3IpS5Wsus7QxY9LsOxlguWTnrmQ,2331
3
- bcoder/encoder.py,sha256=9jS8TwT-IGO42ojLhrat68Ypuc856HSrfU06BZE43WY,1576
4
- bcoder/errors.py,sha256=f_TLCf8wYOHxzKEa85-N1k9NHMk9pGhFut8FzpICr1c,40
5
- bcoder-2.0.dist-info/licenses/LICENSE,sha256=ZrFAe1-xWQ3Sg7hEdYw9wVMIv7LnAcUL55OyqZxATB8,1059
6
- bcoder-2.0.dist-info/METADATA,sha256=-i-8cL5j3SqNUb5ucoiSzhEjNNSypBsIVuaSTiOZ1RM,2487
7
- bcoder-2.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
8
- bcoder-2.0.dist-info/top_level.txt,sha256=u-ORiwqxmd9H_2ZxoVU2WY6AIDJ2adI5KxA734GIceY,7
9
- bcoder-2.0.dist-info/RECORD,,
@@ -1 +0,0 @@
1
- bcoder