def shorten(addr)
if (!addr.kind_of? String)
raise ArgumentError, "Expected String, but #{addr.class} provided."
end
validate_ip_str(addr, 6)
if (addr =~ /::/)
return(addr)
end
fields = addr.split(":")
if (fields.last() =~ /\./ )
ipv4_mapped = fields.pop()
end
start_field,end_field = nil,nil
start_end = []
consecutive,longest = 0,0
(0..(fields.length-1)).each do |x|
fields[x] = fields[x].to_i(16)
if (fields[x] == 0)
if (!start_field)
start_field = x
end_field = x
else
end_field = x
end
consecutive += 1
else
if (start_field)
if (consecutive > longest)
longest = consecutive
start_end = [start_field,end_field]
start_field,end_field = nil,nil
end
consecutive = 0
end
end
fields[x] = fields[x].to_s(16)
end
if (consecutive > longest)
longest = consecutive
else
start_field = start_end[0]
end_field = start_end[1]
end
if (longest > 1)
fields[start_field] = ''
start_field += 1
fields.slice!(start_field..end_field)
end
fields.push(ipv4_mapped) if (ipv4_mapped)
short = fields.join(':')
short << ':' if (short =~ /:$/)
return(short)
end