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.

Revisions

  1. nkokkos revised this gist Jun 28, 2023. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion ring_buffer.rb
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,5 @@
    # RingBuffer class:
    # https://github.com/celluloid/celluloid/blob/5f41eb6f62f4a18ba40872c5b1b17ef0ce3eded6/lib/celluloid/logging/ring_buffer.rb
    # https://github.com/celluloid/celluloid/blob/master/lib/celluloid/logging/ring_buffer.rb
    # added the moving average method

    class RingBuffer
  2. nkokkos created this gist Jun 28, 2023.
    78 changes: 78 additions & 0 deletions ring_buffer.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,78 @@
    # RingBuffer class:
    # https://github.com/celluloid/celluloid/blob/5f41eb6f62f4a18ba40872c5b1b17ef0ce3eded6/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