Created
August 30, 2019 23:51
-
-
Save AtharvaVaidya/d1aa562bf76f97178a008d8e2209891f to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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