Class: Concurrent::RingBuffer

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

Overview

non-thread safe buffer

Instance Method Summary collapse

Constructor Details

#initialize(capacity) ⇒ RingBuffer

Returns a new instance of RingBuffer.



6
7
8
9
10
# File 'lib/concurrent/collection/ring_buffer.rb', line 6

def initialize(capacity)
  @buffer = Array.new(capacity)
  @first = @last = 0
  @count = 0
end

Instance Method Details

#capacityInteger

Returns the capacity of the buffer.

Returns:

  • (Integer)

    the capacity of the buffer



14
15
16
# File 'lib/concurrent/collection/ring_buffer.rb', line 14

def capacity
  @buffer.size
end

#countInteger

Returns the number of elements currently in the buffer.

Returns:

  • (Integer)

    the number of elements currently in the buffer



19
20
21
# File 'lib/concurrent/collection/ring_buffer.rb', line 19

def count
  @count
end

#empty?Boolean

Returns true if buffer is empty, false otherwise.

Returns:

  • (Boolean)

    true if buffer is empty, false otherwise



24
25
26
# File 'lib/concurrent/collection/ring_buffer.rb', line 24

def empty?
  @count == 0
end

#full?Boolean

Returns true if buffer is full, false otherwise.

Returns:

  • (Boolean)

    true if buffer is full, false otherwise



29
30
31
# File 'lib/concurrent/collection/ring_buffer.rb', line 29

def full?
  @count == capacity
end

#offer(value) ⇒ Boolean

Returns true if value has been inserted, false otherwise.

Parameters:

  • value (Object)

Returns:

  • (Boolean)

    true if value has been inserted, false otherwise



35
36
37
38
39
40
41
42
# File 'lib/concurrent/collection/ring_buffer.rb', line 35

def offer(value)
  return false if full?

  @buffer[@last] = value
  @last = (@last + 1) % @buffer.size
  @count += 1
  true
end

#peekObject

Returns the first available value and without removing it from the buffer. If buffer is empty returns nil.

Returns:

  • (Object)

    the first available value and without removing it from the buffer. If buffer is empty returns nil



54
55
56
# File 'lib/concurrent/collection/ring_buffer.rb', line 54

def peek
  @buffer[@first]
end

#pollObject

Returns the first available value and removes it from the buffer. If buffer is empty returns nil.

Returns:

  • (Object)

    the first available value and removes it from the buffer. If buffer is empty returns nil



45
46
47
48
49
50
51
# File 'lib/concurrent/collection/ring_buffer.rb', line 45

def poll
  result = @buffer[@first]
  @buffer[@first] = nil
  @first = (@first + 1) % @buffer.size
  @count -= 1
  result
end