# -*- ruby -*-

if( !Enumerable.instance_methods(false).include?("all?") )
  module Enumerable
    def all?
      each{|v|
	unless( yield(v) )
	  return false
	end
      }
      return true
    end

    def any?
      each{|v|
	if( yield(v) )
	  return true
	end
      }
      return false
    end
  end
end

module XTemplate
  class SanitizedString < String
    def self.[](*objs)
      SanitizedString.new(objs.flatten.collect{|obj|obj.to_s}.join)
    end

    def to_s
      self
    end
  end

  class XArray < Array
  end

  module Util
    PredefinedEntity = {
      '&lt;' => '<',
      '&gt;' => '>',
      '&amp;' => '&',
      '&quot;' => '"',
      '&apos;' => "'",
    }
    RevPredefinedEntity = PredefinedEntity.invert
    PredefinedEntities = PredefinedEntity.keys
    PredefinedEntitiesRegex = Regexp.new("(#{PredefinedEntities.join('|')})")
    PredefinedStrings  = PredefinedEntity.values
    PredefinedStringsRegex = Regexp.new("[#{PredefinedStrings.join}]")
    EntityAmp = '&'
    SanitizedAmp = '&amp;'

    # sanitize() is also implemented in xtemplate_ext.so.
    def sanitize(obj)
      if( obj.is_a?(SanitizedString) )
	obj
      else
	str = obj.to_s.gsub(EntityAmp, SanitizedAmp).gsub(PredefinedStringsRegex){|s|
	  if( s == EntityAmp )
	    s
	  else
	    RevPredefinedEntity[s]
	  end
	}
	SanitizedString.new(str)
      end
    end

    # unsanitize() is also implemented in xtemplate_ext.so.
    def unsanitize(str)
      if( str.is_a?(SanitizedString) )
	str = str.gsub(PredefinedEntitiesRegex){|s|
	  PredefinedEntity[s]
	}
	String.new(str)
      else
	str
      end
    end
  end
end
