Class: FFWD::CircularBuffer

Inherits:
Object
  • Object
show all
Defined in:
lib/ffwd/circular_buffer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(capacity) ⇒ CircularBuffer

Returns a new instance of CircularBuffer.



22
23
24
25
26
27
# File 'lib/ffwd/circular_buffer.rb', line 22

def initialize capacity
  @capacity = capacity
  @first = nil
  @last = nil
  @size = 0
end

Instance Attribute Details

#bufferObject (readonly)

Returns the value of attribute buffer.



20
21
22
# File 'lib/ffwd/circular_buffer.rb', line 20

def buffer
  @buffer
end

#capacityObject (readonly)

Returns the value of attribute capacity.



20
21
22
# File 'lib/ffwd/circular_buffer.rb', line 20

def capacity
  @capacity
end

#sizeObject (readonly)

Returns the value of attribute size.



20
21
22
# File 'lib/ffwd/circular_buffer.rb', line 20

def size
  @size
end

Instance Method Details

#<<(item) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/ffwd/circular_buffer.rb', line 53

def << item
  node = Node.new(item, nil)

  if @last.nil?
    @first = @last = node
  else
    @last = @last.next = node
  end

  if @size >= @capacity
    @first = @first.next
  else
    @size += 1
  end
end

#clearObject



29
30
31
32
33
# File 'lib/ffwd/circular_buffer.rb', line 29

def clear
  @first = nil
  @last = nil
  @size = 0
end

#eachObject



69
70
71
72
73
74
75
76
# File 'lib/ffwd/circular_buffer.rb', line 69

def each
  current = @first

  while not current.nil?
    yield current.value
    current = current.next
  end
end

#empty?Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/ffwd/circular_buffer.rb', line 35

def empty?
  size == 0
end

#peekObject



39
40
41
42
# File 'lib/ffwd/circular_buffer.rb', line 39

def peek
  return nil if @first.nil?
  @first.value
end

#shiftObject



44
45
46
47
48
49
50
51
# File 'lib/ffwd/circular_buffer.rb', line 44

def shift
  return nil if @first.nil?
  value = @first.value
  @first = @first.next
  @last = nil if @first.nil?
  @size -= 1
  value
end