# $Id: string.rb,v 1.8 2002/10/16 16:13:54 knu Exp $

require 'features/ruby18/base'

class String
  alias __ruby16_aref []
  alias __ruby16_aset []=
  alias __ruby16_chomp chomp
  alias __ruby16_chomp! chomp!
  alias __ruby16_slice slice
  alias __ruby16_slice! slice!
  alias __ruby16_to_i to_i

  class << self
    alias __ruby16_new new

    def new(*x)
      x.empty? ? "" : __ruby16_new(*x)
    end
  end

  def [](*x)
    x[0].is_a?(Regexp) or return __ruby16_aref(*x)

    case x.size
    when 1
      nth = 0
    when 2
      nth = x[1]
    else
      raise ArgumentError, "wrong number of arguments(#{x.size} for 1)"
    end

    m = x[0].match(self) and return m[nth]

    nil
  end

  def []=(*x)
    x[0].is_a?(Regexp) or return __ruby16_aset(*x)

    case x.size
    when 2
      nth = 0
      str = x[1]
    when 3
      nth = x[1]
      str = x[2]
    else
      raise ArgumentError, "wrong number of arguments(#{x.size} for 2)"
    end

    m = x[0].match(self) or
      raise IndexError, 'regexp not matched'

    self[m.begin(nth)...m.end(nth)] = str
  end

  def casecmp(other)
    return self.downcase <=> other.downcase
  end

  def chomp(rs=$/)
    s = dup
    s.chomp!(rs)
    s
  end

  def chomp!(rs=$/)
    if "\n" == rs
      sub!(/\r\n?\z|\n\z/, '')
    else
      __ruby16_chomp!(rs)
    end
  end

  def insert(i, s)
    self[i,0] = s
    self
  end

  def lstrip
    s = dup
    s.lstrip!
    s
  end

  def lstrip!
    self.sub!(/\A\s+/, '')
  end

  def match(re)
    if re.is_a?(String)
      re = Regexp.new(re)
    elsif re.respond_to?(:to_str)
      re = Regexp.new(re.to_str)
    end

    re.match(self)
  end

  def rstrip
    s = dup
    s.rstrip!
    s
  end

  def rstrip!
    self.sub!(/\s+\z/, '')
  end

  def slice(*x)
    self[*x]
  end

  def slice!(*x)
    x[0].is_a?(Regexp) or return __ruby16_slice!(*x)

    case x.size
    when 1
      nth = 0
    when 2
      nth = x[1]
    else
      raise ArgumentError, "wrong number of arguments(#{x.size} for 1)"
    end

    m = x[0].match(self) or return nil

    __ruby16_slice!(m.begin(nth)...m.end(nth))
  end

  def to_i(base = 10)
    case base
    when 10
      __ruby16_to_i()
    when 16
      hex
    when 8
      oct
    when 2
      m = /\A(?:0b)?([01_]+)/.match(self) or return 0
      eval('0b' << m[1].delete('_'))
    when Integer
      raise ArgumentError, "illegal radix #{base}"
    else
      raise TypeError, "illegal radix #{base}"
    end
  end
end
