Created
November 18, 2019 07:57
-
-
Save iseki0/6a74e7b8a5b268add1c9f1e1373e5363 to your computer and use it in GitHub Desktop.
RingBuffer.kt
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
class RingBuffer<T:Any>(val size:Int){ | |
init { | |
check(size>-1) | |
} | |
private var putptr=0 | |
private var getptr=0 | |
private var free=size | |
private val array= arrayOfNulls<Any>(size) | |
fun put(o:T){ | |
if (free==0){ | |
throw IndexOutOfBoundsException() | |
} | |
free-- | |
array[putptr]=o | |
putptr=(putptr+1)%size | |
} | |
fun get():T?{ | |
if (free==size){ | |
return null | |
} | |
free++ | |
val r=array[getptr] | |
getptr=(getptr+1)%size | |
return r as T? | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment