Skip to content

Instantly share code, notes, and snippets.

@Reltre
Last active January 24, 2016 04:03
Show Gist options
  • Save Reltre/e19fac81c6a1debc161c to your computer and use it in GitHub Desktop.
Save Reltre/e19fac81c6a1debc161c to your computer and use it in GitHub Desktop.
Object Oriented Circular Buffer
class CircularBuffer
class BufferEmptyException < IOError; end
class BufferFullException < IOError; end
attr_reader :data
def initialize(size)
@data = Array.new(size)
@reader = BufferReader.new
@writer = BufferWriter.new
end
def read
raise BufferEmptyException if buffer_empty?
@reader.read(data)
end
def write(element)
return unless element
raise BufferFullException if buffer_full?
@writer.reset if @writer.index == data.size
@writer.write(data, element)
end
def write!(element)
return unless element
@reader.increment_index if buffer_full?
@writer.write(data, element)
end
def clear
data.fill(nil)
end
private
def buffer_empty?
data.compact.empty?
end
def buffer_full?
data.none?(&:nil?)
end
end
class BufferWriter
attr_reader :index
def initialize
reset
end
def write(data, element)
@index = 0 if @index == data.size
data[@index] = element
@index += 1
end
def reset
@index = 0
end
end
class BufferReader
def initialize
@index = 0
end
def read(data)
@index = 0 if @index == data.size
value = data[@index]
data[@index] = nil
increment_index
value
end
def increment_index
@index += 1
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment