# The contents of this file are subject to the BitTorrent Open Source License# Version 1.1 (the License). You may not copy or use this file, in either# source code or executable form, except in compliance with the License. You# may obtain a copy of the License at http://www.bittorrent.com/license/.## Software distributed under the License is distributed on an AS IS basis,# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License# for the specific language governing rights and limitations under the# License.# Written by Petru Palerdef decode_int(x, f):f += 1newf = x.index('e', f)n = int(x[f:newf])if x[f] == '-':if x[f + 1] == '0':raise ValueErrorelif x[f] == '0' and newf != f+1:raise ValueErrorreturn (n, newf+1)def decode_string(x, f):colon = x.index(':', f)n = int(x[f:colon])if x[f] == '0' and colon != f+1:raise ValueErrorcolon += 1return (x[colon:colon+n], colon+n)def decode_list(x, f):r, f = [], f+1while x[f] != 'e':v, f = decode_func[x[f]](x, f)r.append(v)return (r, f + 1)def decode_dict(x, f):r, f = {}, f+1while x[f] != 'e':k, f = decode_string(x, f)r[k], f = decode_func[x[f]](x, f)return (r, f + 1)decode_func = {}decode_func['l'] = decode_listdecode_func['d'] = decode_dictdecode_func['i'] = decode_intdecode_func['0'] = decode_stringdecode_func['1'] = decode_stringdecode_func['2'] = decode_stringdecode_func['3'] = decode_stringdecode_func['4'] = decode_stringdecode_func['5'] = decode_stringdecode_func['6'] = decode_stringdecode_func['7'] = decode_stringdecode_func['8'] = decode_stringdecode_func['9'] = decode_stringdef bdecode(x):try:r, l = decode_func[x[0]](x, 0)except (IndexError, KeyError, ValueError):raise Exception("not a valid bencoded string")#if l != len(x):# raise Exception("invalid bencoded value (data after valid prefix)")return rfrom types import StringType, IntType, LongType, DictType, ListType, TupleTypeclass Bencached(object):__slots__ = ['bencoded']def __init__(self, s):self.bencoded = sdef encode_bencached(x,r):r.append(x.bencoded)def encode_int(x, r):r.extend(('i', str(x), 'e'))def encode_bool(x, r):if x:encode_int(1, r)else:encode_int(0, r)def encode_string(x, r):r.extend((str(len(x)), ':', x))def encode_list(x, r):r.append('l')for i in x:encode_func[type(i)](i, r)r.append('e')def encode_dict(x,r):r.append('d')ilist = x.items()ilist.sort()for k, v in ilist:r.extend((str(len(k)), ':', k))encode_func[type(v)](v, r)r.append('e')encode_func = {}encode_func[Bencached] = encode_bencachedencode_func[IntType] = encode_intencode_func[LongType] = encode_intencode_func[StringType] = encode_stringencode_func[ListType] = encode_listencode_func[TupleType] = encode_listencode_func[DictType] = encode_dicttry:from types import BooleanTypeencode_func[BooleanType] = encode_boolexcept ImportError:passdef bencode(x):r = []encode_func[type(x)](x, r)return ''.join(r)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。
1. 开源生态
2. 协作、人、软件
3. 评估模型