Sha256: c7474ff308a9534e7f0cd3633afdf20f9240a76661bf9d5ecc031ec9ce4ab4a3

Contents?: true

Size: 1.22 KB

Versions: 1

Compression:

Stored size: 1.22 KB

Contents

module SqsPoller
  module Common
    class RingBuffer

      def initialize(size)
        @size = size
        @start = 0
        @count = 0
        @buffer = Array.new(size)
        @mutex = Mutex.new
      end

      def full?
        @count == @size
      end

      def count
        @count
      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
          until 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
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
fourkites-sqspoller-v2-1.0.0 lib/sqspoller/common/ring_buffer.rb