class Nokogiri::HTML4::EncodingReader

def self.detect_encoding(chunk)

def self.detect_encoding(chunk)
  (m = chunk.match(/\A(<\?xml[ \t\r\n][^>]*>)/)) &&
    (return Nokogiri.XML(m[1]).encoding)
  if Nokogiri.jruby?
    (m = chunk.match(/(<meta\s)(.*)(charset\s*=\s*([\w-]+))(.*)/i)) &&
      (return m[4])
    catch(:encoding_found) do
      Nokogiri::HTML4::SAX::Parser.new(JumpSAXHandler.new(:encoding_found)).parse(chunk)
      nil
    end
  else
    handler = SAXHandler.new
    parser = Nokogiri::HTML4::SAX::PushParser.new(handler)
    begin
      parser << chunk
    rescue
      Nokogiri::SyntaxError
    end
    handler.encoding
  end
end