Permalink
Switch branches/tags
Nothing to show
Find file
Fetching contributors…
Cannot retrieve contributors at this time
56 lines (42 sloc) 1.05 KB
class RLE
HEADER = 'E'
RAW_HEADER = 'R'
def self.encode(str)
ret = ''
# THIS REGEX IS PAINFUL
while str =~ /(.)(\1{10}+\1+)/
before = $`
match = $1 + $2
after = $'
if before.length > 0
ret += [RAW_HEADER, before.length, before].pack("ANA#{before.length}")
end
ret += [HEADER, match.length, $1].pack("ANA1")
str = after
end
if str.length > 0
ret += [RAW_HEADER, str.length, str].pack("ANA#{str.length}")
end
ret
end
def self.decode(str)
ret = ''
while [HEADER, RAW_HEADER].include?(str[0])
header, length = str.unpack('AN')
case header
when HEADER
rest, str = str.unpack("ANAA*")[2, 3]
rest *= length
when RAW_HEADER
rest, str = str.unpack("ANA#{length}A*")[2, 3]
else
puts "ERROR: Invalid header '#{header}'"
exit 1
end
# FIXME: HACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACKHACK
rest = rest.ljust(length, ' ')
ret += rest
end
ret
end
end