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



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



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

def capacity
  @buffer.size
end

#countInteger



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

def count
  @count
end

#empty?Boolean



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

def empty?
  @count == 0
end

#full?Boolean



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

def full?
  @count == capacity
end

#offer(value) ⇒ Boolean



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



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

def peek
  @buffer[@first]
end

#pollObject



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