Class: Concurrent::RingBuffer
- Inherits:
-
Object
- Object
- Concurrent::RingBuffer
- Defined in:
- lib/concurrent/collection/ring_buffer.rb
Overview
non-thread safe buffer
Instance Method Summary collapse
-
#capacity ⇒ Integer
The capacity of the buffer.
-
#count ⇒ Integer
The number of elements currently in the buffer.
-
#empty? ⇒ Boolean
True if buffer is empty, false otherwise.
-
#full? ⇒ Boolean
True if buffer is full, false otherwise.
-
#initialize(capacity) ⇒ RingBuffer
constructor
A new instance of RingBuffer.
-
#offer(value) ⇒ Boolean
True if value has been inserted, false otherwise.
-
#peek ⇒ Object
The first available value and without removing it from the buffer.
-
#poll ⇒ Object
The first available value and removes it from the buffer.
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
#capacity ⇒ Integer
Returns the capacity of the buffer.
14 15 16 |
# File 'lib/concurrent/collection/ring_buffer.rb', line 14 def capacity @buffer.size end |
#count ⇒ Integer
Returns 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.
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.
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.
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 |
#peek ⇒ Object
Returns 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 |
#poll ⇒ Object
Returns 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 |