#!/usr/bin/ruby -I. -w

require "xmlparser"
require "xmlscan/parser"
require "nqxml/streamingparser"
require "rexml/document"
require "rexml/streamlistener"


require "benchmark"
include Benchmark

## for xmlparser
class SampleXMLParser < XMLParser
  def startElement(*args)
    $count += 1
  end
end

## for nqxml

## for xmlscan
class LooseNSVisitor
  include XMLScan::XMLNamespaceVisitor
  def on_start_element_ns(*args)
    $count += 1
  end
  def on_start_element(*args)
    $count += 1
  end
  def parse_error(path, lineno, msg);end
  def wellformed_error(path, lineno, msg);end
  def ns_error(path, lineno, msg);end
end

## for rexml
class REXMLListener
  include REXML::StreamListener
  def tag_start(name, attrs)
    $count += 1
  end
end
rexmllistener = REXMLListener.new()

#n=400
n=10
bm(25) do |test|
  File.open("w3cindex.html") do |source|
#  File.open("project.xml") do |source|

    print "-"*70,"\n"
    print "Parse File object:\n"
    test.report("XMLParser"){
      n.times {
	$count = 0
	SampleXMLParser.new.parse(source)
	p $count if $DEBUG
	source.rewind
      }
    }
    test.report("XMLScan::XMLParser"){
      n.times {
	$count = 0
	XMLScan::XMLParser.new(LooseNSVisitor.new).parse(source)
	p $count if $DEBUG
	source.rewind
      }
    }
    test.report("XMLScan::XMLNSParser"){
      n.times {
	$count = 0
	XMLScan::XMLNamespaceParser.new(LooseNSVisitor.new).parse(source)
	p $count if $DEBUG
	source.rewind
      }
    }
    test.report("NQXML::StrmParser"){
      n.times {
	$count = 0
	p = NQXML::StreamingParser.new(source)
	p.each{|elem|
	  if elem.type == NQXML::Tag && !elem.isTagEnd
	    $count += 1
	  end
	}
	p $count if $DEBUG
	source.rewind
      }
    }
    test.report("REXML::StreamListener"){
      n.times {
	$count = 0
	s = REXML::SourceFactory.create_from(source)
	REXML::Document.parse_stream(s, rexmllistener)
	p $count if $DEBUG
	source.rewind
      }
    }

    print "-"*70,"\n"
    print "Parse String object:\n"
    source = source.read()

    test.report("XMLParser"){
      n.times{
	$count = 0
	SampleXMLParser.new.parse(source)
	p $count if $DEBUG
      }
    }
    test.report("XMLScan::XMLParser"){
      n.times {
	$count = 0
	XMLScan::XMLParser.new(LooseNSVisitor.new).parse(source)
	p $count  if $DEBUG
      }
    }
    test.report("XMLScan::XMLNSParser"){
      n.times {
	$count = 0
	XMLScan::XMLNamespaceParser.new(LooseNSVisitor.new).parse(source)
	p $count if $DEBUG
      }
    }
    test.report("NQXML::StrmParser"){
      n.times {
	$count = 0
	p = NQXML::StreamingParser.new(source)
	p.each{|elem|
	  if elem.type == NQXML::Tag && !elem.isTagEnd
	    $count += 1
	  end
	}
	p $count if $DEBUG
      }
    }
    test.report("REXML::StreamListener"){
      n.times {
	$count = 0
	s = REXML::SourceFactory.create_from(source)
	REXML::Document.parse_stream(s, rexmllistener)
	p $count if $DEBUG
      }
    }
    print "-"*70,"\n"
  end
end
