#
# version.rb
#
#   Copyright (c) 2000,2001 Minero Aoki <aamine@dp.u-netsurf.ne.jp>
#
#   This program is free software.
#   You can distribute/modify this program under the terms of
#   the GNU General Public License version 2 or later.
#

require 'amstd/must'


class VersionNumber

  include Comparable

  VERSION_EXP = /\d+(?:\.\d+)*/

  def initialize( arg, *nums )
    if String === arg then
      unless m = VERSION_EXP.match( arg ) then
        raise ArgumentError, "wrong version string format '#{arg}'"
      end
      @num = m[0].split('.').collect {|i| i.to_i }
    else
      @num = nums || []
      @num.unshift arg
    end
  end

  def dup
    type.new *@nums
  end

  def ==( other )
    @num == other.to_a
  end

  alias eql? ==

  def hash
    @num.hash
  end

  def to_s
    @num.join '.'
  end

  def to_a
    @num.dup
  end

  def inspect
    "\#<#{type} #{to_s}>"
  end


  def []( i )
    @num[i]
  end

  def []=( idx, n )
    idx.downto(1) do |i|
      @num[i] ||= 0
    end
    @num[idx] = n
  end

  def major
    @num[0]
  end

  def major=( i )
    @num[0] = i
  end

  def minor
    @num[1]
  end

  def minor=( i )
    self[1] = i
  end

  def teeny
    @num[2]
  end

  def teeny=( i )
    self[2] = i
  end

  def <=>( other )
    return false unless VersionNumber === other

    n = @num
    ret = nil
    other.instance_eval { ret = (n <=> @num) }
    ret
  end

end
