Skip to content

Instantly share code, notes, and snippets.

@gavinmcgimpsey
Created January 22, 2016 02:43
Show Gist options
  • Save gavinmcgimpsey/ecf9d636dc073136039d to your computer and use it in GitHub Desktop.
Save gavinmcgimpsey/ecf9d636dc073136039d to your computer and use it in GitHub Desktop.

Revisions

  1. gavinmcgimpsey created this gist Jan 22, 2016.
    34 changes: 34 additions & 0 deletions circular_buffer.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    class CircularBuffer
    def initialize(length)
    @buffer = []
    @length = length
    end

    def read
    fail BufferEmptyException.new if @buffer.empty?
    @buffer.shift
    end

    def write(obj)
    return if obj.nil?
    fail BufferFullException.new if full?
    @buffer.push(obj)
    end

    def write!(obj)
    return if obj.nil?
    read if full?
    write(obj)
    end

    def clear
    @buffer = []
    end

    def full?
    @buffer.length == @length
    end

    class BufferEmptyException < RuntimeError; end
    class BufferFullException < RuntimeError; end
    end