Class: Concurrent::Channel::RingBuffer

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

Overview

non-thread safe buffer

Instance Method Summary collapse

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

#capacityInteger

Returns the capacity of the buffer.

Returns:

  • (Integer)

    the capacity of the buffer



18
19
20
# File 'lib/concurrent/channel/ring_buffer.rb', line 18

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



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.

Returns:

  • (Boolean)

    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.

Returns:

  • (Boolean)

    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.

Parameters:

  • value (Object)

Returns:

  • (Boolean)

    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

#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



59
60
61
# File 'lib/concurrent/channel/ring_buffer.rb', line 59

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



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