-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathArrayQueue.kt
52 lines (45 loc) · 1.37 KB
/
ArrayQueue.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.internal
internal open class ArrayQueue<T : Any> {
private var elements = arrayOfNulls<Any>(16)
private var head = 0
private var tail = 0
val isEmpty: Boolean get() = head == tail
public fun addLast(element: T) {
elements[tail] = element
tail = (tail + 1) and elements.size - 1
if (tail == head) ensureCapacity()
}
@Suppress("UNCHECKED_CAST")
public fun removeFirstOrNull(): T? {
if (head == tail) return null
val element = elements[head]
elements[head] = null
head = (head + 1) and elements.size - 1
return element as T
}
public fun clear() {
head = 0
tail = 0
elements = arrayOfNulls(elements.size)
}
private fun ensureCapacity() {
val currentSize = elements.size
val newCapacity = currentSize shl 1
val newElements = arrayOfNulls<Any>(newCapacity)
elements.copyInto(
destination = newElements,
startIndex = head
)
elements.copyInto(
destination = newElements,
destinationOffset = elements.size - head,
endIndex = head
)
elements = newElements
head = 0
tail = currentSize
}
}