# Copyright (C) 2003-2005 Kouichirou Eto, All rights reserved.

require "md5"
$LOAD_PATH.unshift("../../compat") unless $LOAD_PATH.include?("../../compat")
require "base64"

class String
  if !method_defined?(:xchomp)
    def xchomp
      self.chomp("\n").chomp("\r")
    end
  end

  def chompp!
    self.sub!(/[\n\r]+\z/, "")
  end

  def chompp
    self.sub(/[\n\r]+\z/, "")
  end

  def normalize_eol
    self.xchomp+"\n"
  end

  def sub_str(pattern, replace)
    sub(Regexp.new(Regexp.escape(pattern)), replace)
  end

  def md5
    MD5.digest(self)
  end

  def md5hex
    MD5.hexdigest(self)
  end

  def base64
    Base64.encode64(self).chomp
  end
end

if $0 == __FILE__
  require "test/unit"
  $debug = true
end

if $debug
  class TC_UtilString < Test::Unit::TestCase
    def test_string
      # test_xchomp
      assert_equal("", "".xchomp)
      assert_equal("", "\n".xchomp)
      assert_equal("", "\r".xchomp)
      assert_equal("\n", "\n\r".xchomp)

      #test_chompp
      assert_equal("", "\n\r".chompp)
      str = "\n\r"
      str.chompp!
      assert_equal("", str)

      #test_normalize_eol
      assert_equal("\n", "".normalize_eol)
      assert_equal("\n", "\n".normalize_eol)

      #test_sub_str
      assert_equal("a:b", "a*b".sub_str("*", ":"))

      # test_md5
      assert_instance_of(String, "t".md5)
      assert_equal(16, "t".md5.length)
      assert_equal("\343X\357\244\211\365\200b\361\r\3271ked\236", "t".md5)
      assert_instance_of(String, "t".md5hex)
      assert_equal(32, "t".md5hex.length)
      assert_equal("e358efa489f58062f10dd7316b65649e", "t".md5hex)
      assert_equal("dA==", "t".base64)
    end
  end
end
