Metadata-Version: 2.4
Name: bencode-rs
Version: 0.1.0
Classifier: Development Status :: 2 - Pre-Alpha
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: Implementation :: CPython
License-File: LICENSE
Summary: a bencode parser build with pyo3
Keywords: bittorrent,bencode,p2p
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Homepage, https://github.com/trim21/bencode-rs

# A bencode serialize/deserialize library written in Rust with pyo3

## install

```shell
pip install bencode-rs
```

## basic usage

```python
import bencode_rs

assert bencode_rs.bdecode(b"d4:spaml1:a1:bee") == {b"spam": [b"a", b"b"]}

assert bencode_rs.bencode({'hello': 'world'}) == b'd5:hello5:worlde'
```

## Notice

### Decoding

| bencode type | python type |
| :----------: | :---------: |
|   integer    |    `int`    |
|    string    |   `bytes`   |
|    array     |   `list`    |
|  dictionary  |   `dict`    |

bencode has no string type, only bytes.
so we decode bencode bytes to python `bytes`, since it may not be a utf-8 string.

### Encoding

|            python type            | bencode type |
| :-------------------------------: | :----------: |
|              `bool`               | integer 0/1  |
|       `int`, `enum.IntEnum`       |   integer    |
|       `str`, `enum.StrEnum`       |    string    |
| `bytes`, `bytearray`,`memoryview` |    string    |
|   `list`, `tuple`, `NamedTuple`   |    array     |
|       `dict`, `OrderedDict`       |  dictionary  |
|            dataclasses            |  dictionary  |

Also, we encode python `True` as int `1` and `False` as int 0.

### Relaxed decoding

`bdecode` rejects dict keys that are not sorted or that are duplicated, as the spec requires.
Some trackers do not follow that rule, so `bdecode_relax` accepts such dicts:

```python
import bencode_rs

# `complete` is not sorted after `peers`
bencode_rs.bdecode_relax(b"d5:peersi1e8:completei0ee") == {
    b"peers": 1,
    b"complete": 0,
}
# the last duplicated key wins
bencode_rs.bdecode_relax(b"d1:ai1e1:ai2ee") == {b"a": 2}
```

Everything else is still validated, `bdecode_relax` only relaxes dict key ordering and uniqueness.
Don't use it to parse torrent files, duplicated keys make the info hash unstable.

