Last active
January 24, 2016 03:56
-
-
Save Reltre/30f4a509ea7b754658c7 to your computer and use it in GitHub Desktop.
Procedural Version of Circular Buffer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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