Bittorrent的编码模块的ruby代码

最近看了看bt的源码,随手写了些ruby的代码:

def encode(x)
case x.class.to_s
when "Float"
encode_num(x)
when "Fixnum"
encode_num(x)
when "Bignum"
encode_num(x)
when "String"
encode_string(x)
when "Array"
encode_list(x)
when "Hash"
encode_hash(x)
else
"unknown"
end
end
def encode_num(x)
"i#{x.to_s}e"
end
def encode_string(x)
"#{x.size}:#{x}"
end
def encode_list(x)
str="l"
x.each do |temp|
str+=encode(temp)
end
str+="e"
end
def encode_hash(x)
str="d"
x.each do |key,val|
str+=encode(key)
str+=encode(val)
end
str+="e"
end
puts encode("abcd") # returns "4:abcd"
puts encode(1000) # returns "i1000e"
puts encode([1,2,3]) # returns "li1ei2ei3ee"
puts encode({"key" => "value"}) # returns "d3:key5:valuee"



def decode(io)
c = io.getc
case c.chr
when 'i'
i = ''
while c = io.getc
if c.chr == 'e'
if i.match(/^(0|-?[1-9][0-9]*)$/)
return i.to_i
end
else
i += c.chr
end
end
when '0'..'9'
n = c.chr
while b = io.getc
case b.chr
when '0'..'9'
n += b.chr
when ':'
strlen = n.to_i
str = io.read(strlen)
if str.length == strlen
return str
end
end
end
when 'l'
list = []
while item = decode(io)
list.push(item)
end
return list
when 'd'
dict = {}
while key = decode(io)
val = decode(io)
dict[key] = val
end
return dict
when 'e'
return false
end
end
puts decode(StringIO.new("4:abcd"))
puts decode(StringIO.new("i1000e"))
puts decode(StringIO.new("li1ei2ei3ee"))
puts decode(StringIO.new("d3:key5:valuee"))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值