Skip to content

Instantly share code, notes, and snippets.

@holdenhinkle
Last active March 12, 2016 16:23
Show Gist options
  • Save holdenhinkle/d16fdc1f5cfd6da617c9 to your computer and use it in GitHub Desktop.
Save holdenhinkle/d16fdc1f5cfd6da617c9 to your computer and use it in GitHub Desktop.
class CircularBuffer
attr_accessor :buffer, :read_index, :write_index
def initialize(length)
@buffer = Array.new(length)
@read_index = 0
@write_index = 0
end
def read
raise BufferEmptyException if buffer_empty?
element = buffer[read_index]
buffer[read_index] = nil
self.read_index = circulate_index(read_index)
element
end
def write(element)
return if element.nil?
raise BufferFullException if buffer_full?
buffer[write_index] = element
self.write_index = circulate_index(write_index)
end
def write!(element)
return if element.nil?
read if buffer_full?
write(element)
end
def clear
initialize(buffer.length)
end
private
def circulate_index(index)
index == buffer.length - 1 ? 0 : index.next
end
def buffer_full?
buffer.all?
end
def buffer_empty?
buffer.all? { |element| element.nil? }
end
class BufferEmptyException < Exception; end
class BufferFullException < Exception; end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment