Created
August 19, 2013 20:50
-
-
Save pfn/6274023 to your computer and use it in GitHub Desktop.
a ring 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
case class RingBuffer[A: ClassManifest](capacity: Int) extends IndexedSeq[A] { | |
private val buffer = Array.fill[A](capacity)(null.asInstanceOf[A]) | |
private var _length = 0 | |
private var pos = 0 | |
def length = _length | |
private def zero = (capacity + (pos - _length)) % capacity | |
def clear() { | |
_length = 0 | |
pos = 0 | |
} | |
def +=(a: A) { | |
buffer(pos % capacity) = a | |
_length = math.min(_length + 1, capacity) | |
pos += 1 | |
} | |
def apply(i: Int) = buffer((zero + i) % capacity) | |
def copy(capacity: Int = capacity) = { | |
val b = RingBuffer[A](capacity) | |
foreach { item => b += item } | |
b | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment