Class: SamsaraSDK::RingBuffer

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

Overview

Thread-safe ring-buffer data queue tailored for Samsara Client.

Instance Method Summary collapse

Constructor Details

#initialize(size) ⇒ RingBuffer

initialize.

Parameters:

  • size (Integer)

    Storage size.



8
9
10
11
12
13
14
# File 'lib/samsara_sdk/ring_buffer.rb', line 8

def initialize(size)
  @size = size
  @low = -1
  @high = -1
  @buffer = Array.new(size)
  @mutex = Mutex.new
end

Instance Method Details

#countInteger

Get current number of items in buffer.

Returns:

  • (Integer)

    number of pushed elements.



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

def count
  @high - @low
end

#empty?Boolean

Is buffer empty?

Returns:

  • (Boolean)

    Empty or not.



33
34
35
# File 'lib/samsara_sdk/ring_buffer.rb', line 33

def empty?
  count.zero?
end

#flush {|data| ... } ⇒ Array<Object>

Extract all existing elements out of buffer.

Yields:

  • (data)

    Block that processes data and returns success of the processing.

Yield Parameters:

  • data (Array<Object>)

    Buffer data.

Yield Returns:

  • (Boolean)

    Result of data processing. True if success, false otherwise.

Returns:

  • (Array<Object>)

    All buffer’s elements in FIFO order.



58
59
60
61
62
63
# File 'lib/samsara_sdk/ring_buffer.rb', line 58

def flush
  data, at_mark = take_snapshot
  success = block_given? ? yield(data) : TRUE
  delete at_mark if success
  data
end

#full?Boolean

Is buffer full?

Returns:

  • (Boolean)

    Full or not.



26
27
28
# File 'lib/samsara_sdk/ring_buffer.rb', line 26

def full?
  count == @size
end

#push(value) ⇒ Object Also known as: <<

Puts element into buffer.

Returns:

  • (Object)

    Element that has been put into buffer.



40
41
42
43
44
45
46
47
48
# File 'lib/samsara_sdk/ring_buffer.rb', line 40

def push(value)
  @mutex.synchronize do
    return if @size.zero?
    @high += 1
    @low += 1 if count > @size
    @buffer[high_position] = value
    value
  end
end