Bittorrent的编码模块的ruby代码
程序员文章站
2022-07-01 13:54:08
...
最近看了看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"))