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 @file:Suppress("UNCHECKED_CAST") 6 7 package kotlinx.coroutines.internal 8 9 import kotlinx.coroutines.assert 10 11 /* 12 * Inline class that represents a mutable list, but does not allocate an underlying storage 13 * for zero and one elements. 14 * Cannot be parametrized with `List<*>`. 15 */ 16 internal inline class InlineList<E>(private val holder: Any? = null) { plusnull17 public operator fun plus(element: E): InlineList<E> { 18 assert { element !is List<*> } // Lists are prohibited 19 return when (holder) { 20 null -> InlineList(element) 21 is ArrayList<*> -> { 22 (holder as ArrayList<E>).add(element) 23 InlineList(holder) 24 } 25 else -> { 26 val list = ArrayList<E>(4) 27 list.add(holder as E) 28 list.add(element) 29 InlineList(list) 30 } 31 } 32 } 33 forEachReversednull34 public inline fun forEachReversed(action: (E) -> Unit) { 35 when (holder) { 36 null -> return 37 !is ArrayList<*> -> action(holder as E) 38 else -> { 39 val list = holder as ArrayList<E> 40 for (i in (list.size - 1) downTo 0) { 41 action(list[i]) 42 } 43 } 44 } 45 } 46 } 47