Skip to content

Instantly share code, notes, and snippets.

@nkokkos
Last active June 28, 2023 10:55
Show Gist options
  • Save nkokkos/10f30e93101412b70782c7d4b9c43e39 to your computer and use it in GitHub Desktop.
Save nkokkos/10f30e93101412b70782c7d4b9c43e39 to your computer and use it in GitHub Desktop.
# RingBuffer class:
# https://github.com/celluloid/celluloid/blob/master/lib/celluloid/logging/ring_buffer.rb
# added the moving average method
class RingBuffer
attr_reader :buffer
def initialize(size)
@size = size
@start = 0
@count = 0
@buffer = Array.new(size)
@mutex = Mutex.new
end
def full?
@count == @size
end
# calculates the mean average of all the values in the buffer provided that
# the buffer is already full
def average
if self.full?
@buffer.inject{ |sum, el| sum + el }.to_f / @size
end
end
def empty?
@count == 0
end
def push(value)
@mutex.synchronize do
stop = (@start + @count) % @size
@buffer[stop] = value
if full?
@start = (@start + 1) % @size
else
@count += 1
end
value
end
end
alias :<< :push
def shift
@mutex.synchronize do
remove_element
end
end
def flush
values = []
@mutex.synchronize do
while !empty?
values << remove_element
end
end
values
end
def clear
@buffer = Array.new(@size)
@start = 0
@count = 0
end
private
def remove_element
return nil if empty?
value, @buffer[@start] = @buffer[@start], nil
@start = (@start + 1) % @size
@count -= 1
value
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment