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