Commit c0141cea authored by David Owens II's avatar David Owens II

Added option to stop overwrites in the buffer.

parent 429d5aec
......@@ -13,31 +13,42 @@ import Foundation
class RingBuffer<ElementType> {
let capacity: Int
var buffer: [ElementType?]
let overwrite: Bool
private var start: Int = 0
private var end: Int = 0
private var start: Int! = nil
private var end: Int! = nil
init(capacity: Int) {
init(capacity: Int, overwrite: Bool = true) {
precondition(capacity > 1, "The capacity of the buffer must be greater than one.")
self.overwrite = overwrite
self.capacity = capacity
buffer = [ElementType?](count: capacity, repeatedValue: nil)
}
/**
* Inserts an element into the buffer. When the capacity has been met,
* the oldest item is overwritten.
* the oldest item is overwritten if `overwrite` was set to `true`.
*/
func insert(element: ElementType) {
buffer[end] = element
if start == 0 && end == 0 {
if start == nil {
buffer[0] = element
start = 0
end = 1
}
else {
end = (end + 1) % capacity
if end == start {
start += 1
if overwrite {
buffer[end] = element
end = (end + 1) % capacity
if end == start {
start = start + 1
}
}
else {
if start != end {
buffer[end] = element
end = (end + 1) % capacity
}
}
}
}
......@@ -46,13 +57,13 @@ class RingBuffer<ElementType> {
* Removes the oldest item in the buffer.
*/
func remove() -> ElementType? {
if start == nil || end == nil { return nil }
let element = buffer[start]
buffer[start] = nil
if start != end {
start = (start + 1) % capacity
}
start = (start + 1) % capacity
return element
}
......
......@@ -22,7 +22,8 @@ class RingBufferTests: Test {
let tests = [
testBasicInit,
testInsertion,
testRemove
testRemove,
testNoOverwrite
]
for test in tests {
......@@ -81,4 +82,28 @@ class RingBufferTests: Test {
try test.assert(buffer[1] == 101)
try test.assert(buffer[2] == nil)
}
func testNoOverwrite() throws {
let buffer = RingBuffer<Int>(capacity: 3, overwrite: false)
try test.assert(buffer.capacity == 3)
buffer.insert(100)
buffer.insert(101)
buffer.insert(102)
buffer.insert(103)
try test.assert(buffer[0] == 100)
try test.assert(buffer[1] == 101)
try test.assert(buffer[2] == 102)
try test.assert(buffer.remove() == 100)
try test.assert(buffer[0] == nil)
try test.assert(buffer[1] == 101)
try test.assert(buffer[2] == 102)
buffer.insert(103)
try test.assert(buffer[0] == 103)
try test.assert(buffer[1] == 101)
try test.assert(buffer[2] == 102)
}
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment