17
17
from io import StringIO
18
18
19
19
import sys
20
+ from io import BytesIO
21
+ import array
20
22
21
23
# Some code so we can use different features without worrying about versions.
22
24
PY2 = sys .version_info [0 ] == 2
@@ -42,11 +44,11 @@ def _read_int(s, terminator=None, init_data=None):
42
44
break
43
45
else :
44
46
int_chrs .append (c )
45
- return int ('' .join (int_chrs ))
47
+ return int (b '' .join (int_chrs ))
46
48
47
49
48
50
def _read_bytes (s , n ):
49
- data = StringIO ( '' )
51
+ data = BytesIO ( )
50
52
cnt = 0
51
53
while cnt < n :
52
54
m = s .read (n - cnt )
@@ -85,17 +87,17 @@ def _read_map(s):
85
87
return dict (zip (i , i ))
86
88
87
89
88
- _read_fns = {"i" : _read_int ,
89
- "l" : _read_list ,
90
- "d" : _read_map ,
91
- "e" : lambda _ : None ,
90
+ _read_fns = {b "i" : _read_int ,
91
+ b "l" : _read_list ,
92
+ b "d" : _read_map ,
93
+ b "e" : lambda _ : None ,
92
94
# EOF
93
95
None : lambda _ : None }
94
96
95
97
96
98
def _read_datum (s ):
97
99
delim = _read_delimiter (s )
98
- if delim is not '' :
100
+ if delim is not b '' :
99
101
return _read_fns .get (delim , lambda s : _read_bytes (s , delim ))(s )
100
102
101
103
@@ -104,32 +106,32 @@ def _write_datum(x, out):
104
106
# x = x.encode("UTF-8")
105
107
# TODO revisit encodings, this is surely not right. Python
106
108
# (2.x, anyway) conflates bytes and strings, but 3.x does not...
107
- out .write (str (len (x ) ))
108
- out .write (":" )
109
- out .write (x )
109
+ out .write (str (len (x . encode ( 'utf-8' ))). encode ( 'utf-8' ))
110
+ out .write (b ":" )
111
+ out .write (x . encode ( 'utf-8' ) )
110
112
elif isinstance (x , int ):
111
- out .write ("i" )
112
- out .write (str (x ))
113
- out .write ("e" )
113
+ out .write (b "i" )
114
+ out .write (str (x ). encode ( 'utf-8' ) )
115
+ out .write (b "e" )
114
116
elif isinstance (x , (list , tuple )):
115
- out .write ("l" )
117
+ out .write (b "l" )
116
118
for v in x :
117
119
_write_datum (v , out )
118
- out .write ("e" )
120
+ out .write (b "e" )
119
121
elif isinstance (x , dict ):
120
- out .write ("d" )
122
+ out .write (b "d" )
121
123
for k , v in x .items ():
122
124
_write_datum (k , out )
123
125
_write_datum (v , out )
124
- out .write ("e" )
126
+ out .write (b "e" )
125
127
out .flush ()
126
128
127
129
128
130
def encode (v ):
129
131
"bencodes the given value, may be a string, integer, list, or dict."
130
- s = StringIO ()
132
+ s = BytesIO ()
131
133
_write_datum (v , s )
132
- return s .getvalue ()
134
+ return s .getvalue (). decode ( 'utf-8' )
133
135
134
136
135
137
def decode_file (file ):
@@ -142,7 +144,7 @@ def decode_file(file):
142
144
143
145
def decode (string ):
144
146
"Generator that yields decoded values from the input string."
145
- return decode_file (StringIO (string ))
147
+ return decode_file (BytesIO (string . encode ( 'utf-8' ) ))
146
148
147
149
148
150
class BencodeIO (object ):
0 commit comments