Skip to content

Instantly share code, notes, and snippets.

@AtharvaVaidya
Created August 30, 2019 23:51
Show Gist options
  • Save AtharvaVaidya/d1aa562bf76f97178a008d8e2209891f to your computer and use it in GitHub Desktop.
Save AtharvaVaidya/d1aa562bf76f97178a008d8e2209891f to your computer and use it in GitHub Desktop.
class RingBuffer<T>
{
private(set) var array: [T?]
private var readIndex = 0
private var writeIndex = 0
public var isFull: Bool
{
return array.compactMap({ $0 }).count == array.count
}
init(count: Int)
{
self.array = [T?](repeating: nil, count: count)
}
func write(_ element: T)
{
if writeIndex >= array.count
{
writeIndex = 0
}
array[writeIndex] = element
writeIndex += 1
}
func read() -> T?
{
guard array.filter({ $0 != nil }).count > 0 else { return nil }
if readIndex >= array.count { readIndex = 0 }
let element = array[readIndex]
readIndex += 1
return element
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment