Created
October 4, 2016 13:30
-
-
Save Timshel/78aaed1dcee20055be371498717dc7fd to your computer and use it in GitHub Desktop.
RingBuffer
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
/** | |
* Implementation of a ring buffer optimised for our use case. | |
* There is minimum check and it's not thread safe | |
*/ | |
class Ring[T: reflect.ClassTag](size: Int) { | |
import java.lang.ArrayIndexOutOfBoundsException | |
protected val buffer = Array.ofDim[T](size) | |
protected var first: Int = 0 | |
protected var last: Int = -1 | |
var count: Int = 0 | |
def head: T = | |
if( count > 0 ) buffer(first) | |
else throw new ArrayIndexOutOfBoundsException("Empty ring") | |
def add(value: T): Unit = { | |
if( count < size ) { | |
last = (last + 1) % size | |
buffer(last) = value | |
count += 1 | |
} else throw new ArrayIndexOutOfBoundsException("Full ring") | |
} | |
@annotation.tailrec | |
final def dropWhile(f: T => Boolean): Unit = { | |
if( count > 0 && f(head) ) { | |
first = (first + 1) % size | |
count -= 1 | |
dropWhile(f) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment