module HexDump

def self.regex_quote_n(raw)

raw must be in BINARY encoding in 1.9
def self.regex_quote_n(raw)
  Regexp.quote(raw)
end

def self.regex_quote_n(raw)

def self.regex_quote_n(raw)
  Regexp.quote(raw, 'n')
end

def encode(str)

str must be in BINARY encoding in 1.9
def encode(str)
  offset = 0
  result = []
  while raw = str.slice(offset, 16) and raw.length > 0
    # data field
    data = ''
    for v in raw.unpack('N* a*')
f v.kind_of? Integer
 data << sprintf("%08x ", v)
lse
 v.each_byte {|c| data << sprintf("%02x", c) }
nd
    end
    # text field
    text = raw.tr("\000-\037\177-\377", ".")
    result << sprintf("%08x  %-36s  %s", offset, data, text)
    offset += 16
    # omit duplicate line
    if /^(#{regex_quote_n(raw)})+/n =~ str[offset .. -1]
esult << sprintf("%08x  ...", offset)
ffset += $&.length
 should print at the end
f offset == str.length
 result << sprintf("%08x  %-36s  %s", offset-16, data, text)
nd
    end
  end
  result
end