aboutsummaryrefslogtreecommitdiffstats
path: root/kotlinx-coroutines-core/common/src/internal/InlineList.kt
blob: 61bf6d01addc30514e8aa9ec9bdf63e0c7f26bdd (plain)
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
/*
 * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */

@file:Suppress("UNCHECKED_CAST")

package kotlinx.coroutines.internal

import kotlinx.coroutines.assert
import kotlin.jvm.*

/*
 * Inline class that represents a mutable list, but does not allocate an underlying storage
 * for zero and one elements.
 * Cannot be parametrized with `List<*>`.
 */
@JvmInline
internal value class InlineList<E>(private val holder: Any? = null) {
    operator fun plus(element: E): InlineList<E>  {
        assert { element !is List<*> } // Lists are prohibited
        return when (holder) {
            null -> InlineList(element)
            is ArrayList<*> -> {
                (holder as ArrayList<E>).add(element)
                InlineList(holder)
            }
            else -> {
                val list = ArrayList<E>(4)
                list.add(holder as E)
                list.add(element)
                InlineList(list)
            }
        }
    }

    inline fun forEachReversed(action: (E) -> Unit) {
        when (holder) {
            null -> return
            !is ArrayList<*> -> action(holder as E)
            else -> {
                val list = holder as ArrayList<E>
                for (i in (list.size - 1) downTo 0) {
                    action(list[i])
                }
            }
        }
    }
}