Add UniqueQueue

Signed-off-by: Graham <gpe@openrs2.org>
Graham 4 years ago
parent ce741279b4
commit 81e665e9d8
  1. 25
      util/src/main/kotlin/org/openrs2/util/collect/UniqueQueue.kt
  2. 21
      util/src/test/kotlin/org/openrs2/util/collect/UniqueQueueTest.kt

@ -0,0 +1,25 @@
package org.openrs2.util.collect
public class UniqueQueue<T> {
private val queue = ArrayDeque<T>()
private val set = mutableSetOf<T>()
public fun add(v: T): Boolean {
if (set.add(v)) {
queue.addLast(v)
return true
}
return false
}
public fun poll(): T? {
val v = queue.removeFirstOrNull()
if (v != null) {
set.remove(v)
return v
}
return null
}
}

@ -0,0 +1,21 @@
package org.openrs2.util.collect
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
class UniqueQueueTest {
@Test
fun testAddPoll() {
val queue = UniqueQueue<String>()
assertTrue(queue.add("a"))
assertTrue(queue.add("b"))
assertFalse(queue.add("a"))
assertEquals("a", queue.poll())
assertEquals("b", queue.poll())
assertNull(queue.poll())
}
}
Loading…
Cancel
Save