Skip to content

Instantly share code, notes, and snippets.

@Reltre
Last active January 24, 2016 03:56
Show Gist options
  • Save Reltre/30f4a509ea7b754658c7 to your computer and use it in GitHub Desktop.
Save Reltre/30f4a509ea7b754658c7 to your computer and use it in GitHub Desktop.
Procedural Version of Circular Buffer
class CircularBuffer
class BufferEmptyException < IOError; end
class BufferFullException < IOError; end
attr_reader :data
def initialize(size)
@data = Array.new(size)
@read_index = 0
@write_index = 0
end
def read
raise BufferEmptyException if buffer_empty?
@read_index = 0 if @read_index == data.size
value = data[@read_index]
data[@read_index] = nil
@read_index += 1
value
end
def write(element)
insert(element) { raise BufferFullException }
end
def write!(element)
insert(element) { @read_index += 1 }
end
def clear
data.fill(nil)
end
private
def insert(element, &block)
return unless element
block.call if buffer_full?
@write_index = 0 if @write_index == data.size
data[@write_index] = element
@write_index += 1
end
def buffer_empty?
data.compact.empty?
end
def buffer_full?
data.none?(&:nil?)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment