1414
1515__version__ = ' 1.2.0'
1616
17- import array
1817
1918try :
2019 from collections import OrderedDict
@@ -101,7 +100,7 @@ def bdecode(bytes x):
101100 raise BTFailure(" invalid bencoded value (data after valid prefix)" )
102101 return r
103102
104- def encode (v , r ):
103+ cdef encode(v, list r):
105104 tp = type (v)
106105 if tp in encode_func:
107106 return encode_func[tp](v, r)
@@ -114,47 +113,47 @@ def encode(v, r):
114113 )
115114
116115
117- def encode_int (long x , r ):
118- r.fromstring (b' i' )
119- r.fromstring (str (x).encode())
120- r.fromstring (b' e' )
116+ cdef encode_int(long x, list r):
117+ r.append (b' i' )
118+ r.append (str (x).encode())
119+ r.append (b' e' )
121120
122121
123- def encode_long (x , r ):
124- r.fromstring (b' i' )
125- r.fromstring (str (x).encode())
126- r.fromstring (b' e' )
122+ cdef encode_long(x, list r):
123+ r.append (b' i' )
124+ r.append (str (x).encode())
125+ r.append (b' e' )
127126
128127
129- def encode_bytes (bytes x , r ):
130- r.fromstring (str (len (x)).encode())
131- r.fromstring (b' :' )
132- r.fromstring (x)
128+ cdef encode_bytes(bytes x, list r):
129+ r.append (str (len (x)).encode())
130+ r.append (b' :' )
131+ r.append (x)
133132
134133
135- def encode_string (str x , r ):
136- r.fromstring (str (len (x)).encode())
137- r.fromstring (b' :' )
138- r.fromstring (x.encode())
134+ cdef encode_string(str x, list r):
135+ r.append (str (len (x)).encode())
136+ r.append (b' :' )
137+ r.append (x.encode())
139138
140139
141- def encode_list (x , r ):
142- r.fromstring (b' l' )
140+ cdef encode_list(x, list r):
141+ r.append (b' l' )
143142 for i in x:
144143 encode(i, r)
145- r.fromstring (b' e' )
144+ r.append (b' e' )
146145
147146
148- def encode_dict (x , r ):
149- r.fromstring (b' d' )
147+ cdef encode_dict(x, list r):
148+ r.append (b' d' )
150149 item_list = list (x.items())
151150 item_list.sort()
152151 for k, v in item_list:
153152 if isinstance (k, str ):
154153 k = k.encode()
155154 encode_bytes(k, r)
156155 encode(v, r)
157- r.fromstring (b' e' )
156+ r.append (b' e' )
158157
159158
160159encode_func = {
@@ -171,6 +170,6 @@ encode_func = {
171170
172171
173172def bencode (x ):
174- r = array.array(ARRAY_TYPECODE)
173+ r = []
175174 encode(x, r)
176- return r.tostring( )
175+ return b ' ' .join(r )
0 commit comments