Class: Helpers::RingBuffer

Inherits:
Object
  • Object
show all
Defined in:
lib/helpers/ring_buffer.rb

Instance Method Summary collapse

Constructor Details

#initialize(size) ⇒ RingBuffer

Returns a new instance of RingBuffer.



3
4
5
6
7
8
9
# File 'lib/helpers/ring_buffer.rb', line 3

def initialize(size)
  @size = size
  @start = 0
  @count = 0
  @buffer = Array.new(size)
  @mutex = Mutex.new
end

Instance Method Details

#clearObject



49
50
51
52
53
# File 'lib/helpers/ring_buffer.rb', line 49

def clear
  @buffer = Array.new(@size)
  @start = 0
  @count = 0
end

#empty?Boolean

Returns:

  • (Boolean)


15
16
17
# File 'lib/helpers/ring_buffer.rb', line 15

def empty?
  @count == 0
end

#flushObject



39
40
41
42
43
44
45
46
47
# File 'lib/helpers/ring_buffer.rb', line 39

def flush
  values = []
  @mutex.synchronize do
    until empty?
      values << remove_element
    end
  end
  values
end

#full?Boolean

Returns:

  • (Boolean)


11
12
13
# File 'lib/helpers/ring_buffer.rb', line 11

def full?
  @count == @size
end

#push(value) ⇒ Object Also known as: <<



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/helpers/ring_buffer.rb', line 19

def push(value)
  @mutex.synchronize do
    stop = (@start + @count) % @size
    @buffer[stop] = value
    if full?
      @start = (@start + 1) % @size
    else
      @count += 1
    end
    value
  end
end

#shiftObject



33
34
35
36
37
# File 'lib/helpers/ring_buffer.rb', line 33

def shift
  @mutex.synchronize do
    remove_element
  end
end