Skip to content

Commit 65b12d4

Browse files
committed
Support encoding subclasses of dict
1 parent 8b52453 commit 65b12d4

File tree

3 files changed

+27
-5
lines changed

3 files changed

+27
-5
lines changed

README.rst

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,12 @@ Usage
3232
with open("debian-8.3.0-amd64-netinst.iso.torrent", "rb") as f:
3333
torrent = bdecode(f.read())
3434
print(torrent['announce'])
35+
36+
ChangeLog
37+
----------
38+
39+
Version 1.1.0
40+
~~~~~~~~~~~~~~~
41+
42+
+ Use OrderedDict instaed of dict
43+
+ Support encoding subclasses of dict

bencoder.pyx

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,18 @@ def bdecode(bytes x):
9494
return r
9595

9696

97+
def encode(v, r):
98+
tp = type(v)
99+
if tp in encode_func:
100+
return encode_func[tp](v, r)
101+
else:
102+
for tp, func in encode_func.items():
103+
if isinstance(v, tp):
104+
return func(v, r)
105+
raise BTFailure("Unknown Type: %s" % tp)
106+
107+
108+
97109
def encode_int(int x, list r):
98110
r.extend((b'i', str(x).encode(), b'e'))
99111

@@ -114,19 +126,19 @@ def encode_string(x, list r):
114126
def encode_list(x, list r):
115127
r.append(b'l')
116128
for i in x:
117-
encode_func[type(i)](i, r)
129+
encode(i, r)
118130
r.append(b'e')
119131

120132

121-
def encode_dict(dict x, list r):
133+
def encode_dict(x, list r):
122134
r.append(b'd')
123135
item_list = list(x.items())
124136
item_list.sort()
125137
for k, v in item_list:
126138
if isinstance(k, str):
127139
k = k.encode()
128140
r.extend((str(len(k)).encode(), b':', k))
129-
encode_func[type(v)](v, r)
141+
encode(v, r)
130142
r.append(b'e')
131143

132144

@@ -137,11 +149,12 @@ encode_func = {
137149
list: encode_list,
138150
tuple: encode_list,
139151
dict: encode_dict,
152+
OrderedDict: encode_dict,
140153
bool: encode_bool,
141154
}
142155

143156

144157
def bencode(x):
145158
r = []
146-
encode_func[type(x)](x, r)
159+
encode(x, r)
147160
return b''.join(r)

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
setup(
1212
name='bencoder.pyx',
13-
version='1.0.0',
13+
version='1.1.0',
1414
description='Yet another bencode implementation in Cython',
1515
long_description=open('README.rst', 'r').read(),
1616
author='whtsky',

0 commit comments

Comments
 (0)