Skip to content

Instantly share code, notes, and snippets.

@pfn
Created August 19, 2013 20:50
Show Gist options
  • Save pfn/6274023 to your computer and use it in GitHub Desktop.
Save pfn/6274023 to your computer and use it in GitHub Desktop.
a ring buffer
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