#
# LimitedArray.rb
#
#   $Author: hiroya $
#   $Date: 2000/11/23 01:53:10 $
#   Copyright (C) 2000 Hiroya KUBO
#

=begin
 * class LimitedArray is subclass of Array which is automatically maintained in the max size.
 * class LimitedArrayWithCursor is subclass of LimitedArray which has a indexing cursor and 
         an offset for index.

usage:
  a = LimitedArrayWithCursor.new
  a.set([1,2,3])
  a.setMaxSize(5)
  a.push("a")
  a.push("b")
  a.push("c")

  a.moveCursorToEnd

  print a.getValue,"\n"
  a.backwardCursor
  print a.getValue,"\n"
  a.backwardCursor
  print a.getValue,"\n"
  a.backwardCursor
  print a.getValue,"\n"
  a.backwardCursor
  print a.getValue,"\n"

=end

# -----------------------------------

class LimitedArray < Array
  def initialize
    super
    @max_size = nil
  end

  def set(array)
    for i in array
      push(i)
    end
  end

  def setMaxSize(max_size)
    @max_size = max_size
  end

  def getMaxSize
    return @max_size
  end

  def push(arg)
    super(arg)
    if(@max_size != nil && @max_size < size)
      self.shift
    end
  end

  def unshift(arg)
    super(arg)
    if(@max_size != nil && @max_size < size)
      self.pop
    end
  end
end

class LimitedArrayWithCursor < LimitedArray
  def new
    @cursor_pos = nil
    @offset = 0
    super
  end

  def unshift(arg)
    if(@offset != nil)
      @offset = @offset - 1
    end
    return super(arg)
  end

  def shift
    if(@offset != nil)
      @offset = @offset + 1
    end
    return super
  end

  def setCursor(cursor)
    if(@cursor_pos != nil && @cursor_pos < size)
      @cursor_pos = cursor
    end
  end

  def moveCursor(n = size-1)
    if(@cursor_pos != nil &&
       0 <= @cursor_pos + n && @cursor_pos + n <= size - 1)
      @cursor_pos += n
    end
  end

  def moveCursorToEnd
    @cursor_pos = size-1
  end

  def getCursor
    return @cursor_pos
  end

  def getOffset
    return @offset
  end

  def setOffset(offset)
    @offset = offset
  end

  def getOffsetedCursor
    tmp = 0
    if(@cursor_pos != nil )
      tmp += @cursor_pos
    end
    if(@offset != nil)
      tmp += @offset
    end
    return tmp
  end

  def getPointedValue
    if(@cursor_pos != nil)
      return self[@cursor_pos]
    else
      return nil
    end
  end

end



syntax highlighted by Code2HTML, v. 0.9.1