Class: Concurrent::Channel::RingBuffer
- Inherits:
-
Object
- Object
- Concurrent::Channel::RingBuffer
- Defined in:
- lib/concurrent/channel/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.
10 11 12 13 14 |
# File 'lib/concurrent/channel/ring_buffer.rb', line 10 def initialize(capacity) @buffer = Array.new(capacity) @first = @last = 0 @count = 0 end |
Instance Method Details
#capacity ⇒ Integer
Returns the capacity of the buffer.
18 19 20 |
# File 'lib/concurrent/channel/ring_buffer.rb', line 18 def capacity @buffer.size end |
#count ⇒ Integer
Returns the number of elements currently in the buffer.
23 24 25 |
# File 'lib/concurrent/channel/ring_buffer.rb', line 23 def count @count end |
#empty? ⇒ Boolean
Returns true if buffer is empty, false otherwise.
28 29 30 |
# File 'lib/concurrent/channel/ring_buffer.rb', line 28 def empty? @count == 0 end |
#full? ⇒ Boolean
Returns true if buffer is full, false otherwise.
33 34 35 |
# File 'lib/concurrent/channel/ring_buffer.rb', line 33 def full? @count == capacity end |
#offer(value) ⇒ Boolean
Returns true if value has been inserted, false otherwise.
39 40 41 42 43 44 45 46 |
# File 'lib/concurrent/channel/ring_buffer.rb', line 39 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.
59 60 61 |
# File 'lib/concurrent/channel/ring_buffer.rb', line 59 def peek @buffer[@first] end |
#poll ⇒ Object
Returns the first available value and removes it from the buffer. If buffer is empty returns nil.
49 50 51 52 53 54 55 |
# File 'lib/concurrent/channel/ring_buffer.rb', line 49 def poll result = @buffer[@first] @buffer[@first] = nil @first = (@first + 1) % @buffer.size @count -= 1 result end |