Skip to content

Commit 490f33a

Browse files
committed
Fixed an issue handling bytes on Python 2
1 parent b871198 commit 490f33a

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

bencode/__init__.py

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -76,14 +76,15 @@ def decode_string(x, f, try_decode_utf8=True, force_decode_utf8=False):
7676

7777
colon += 1
7878
s = x[colon:colon + n]
79+
7980
if try_decode_utf8:
8081
try:
81-
s = s.decode('utf-8')
82+
return s.decode('utf-8'), colon + n
8283
except UnicodeDecodeError:
8384
if force_decode_utf8:
8485
raise
8586

86-
return s, colon + n
87+
return bytes(s), colon + n
8788

8889

8990
def decode_list(x, f):
@@ -196,15 +197,19 @@ def encode_bool(x, r):
196197
encode_int(0, r)
197198

198199

199-
def encode_string(x, r):
200-
s = x.encode('utf-8')
201-
r.extend((str(len(s)).encode('utf-8'), b':', s))
202-
203-
204200
def encode_bytes(x, r):
205201
r.extend((str(len(x)).encode('utf-8'), b':', x))
206202

207203

204+
def encode_string(x, r):
205+
try:
206+
s = x.encode('utf-8')
207+
except UnicodeDecodeError:
208+
return encode_bytes(x, r)
209+
210+
r.extend((str(len(s)).encode('utf-8'), b':', s))
211+
212+
208213
def encode_list(x, r):
209214
r.append(b'l')
210215

0 commit comments

Comments
 (0)