All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.io.ktor.util.pipeline.PhaseContent.kt Maven / Gradle / Ivy

There is a newer version: 4.0.0
Show newest version
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/

package io.ktor.util.pipeline

import io.ktor.util.*
import io.ktor.util.collections.*
import io.ktor.utils.io.concurrent.*

@Suppress("DEPRECATION")
internal class PhaseContent(
    val phase: PipelinePhase,
    val relation: PipelinePhaseRelation,
    interceptors: MutableList>
) {
    private var interceptors: MutableList> = interceptors

    @Suppress("UNCHECKED_CAST")
    constructor(
        phase: PipelinePhase,
        relation: PipelinePhaseRelation
    ) : this(phase, relation, SharedArrayList as MutableList>) {
        check(SharedArrayList.isEmpty()) { "The shared empty array list has been modified" }
    }

    var shared: Boolean = true

    val isEmpty: Boolean get() = interceptors.isEmpty()
    val size: Int get() = interceptors.size

    fun addInterceptor(interceptor: PipelineInterceptorFunction) {
        if (shared) {
            copyInterceptors()
        }

        interceptors.add(interceptor)
    }

    fun addTo(destination: MutableList>) {
        val interceptors = interceptors

        if (destination is ArrayList) {
            destination.ensureCapacity(destination.size + interceptors.size)
        }

        for (index in 0 until interceptors.size) {
            destination.add(interceptors[index])
        }
    }

    fun addTo(destination: PhaseContent) {
        if (isEmpty) return

        if (destination.isEmpty) {
            destination.interceptors = sharedInterceptors()
            destination.shared = true
            return
        }

        if (destination.shared) {
            destination.copyInterceptors()
        }

        addTo(destination.interceptors)
    }

    fun sharedInterceptors(): MutableList> {
        shared = true
        return interceptors
    }

    @OptIn(InternalAPI::class)
    fun copiedInterceptors(): MutableList> =
        mutableListOf>().apply {
            addAll(interceptors)
        }

    override fun toString(): String = "Phase `${phase.name}`, $size handlers"

    private fun copyInterceptors() {
        interceptors = copiedInterceptors()
        shared = false
    }

    companion object {
        @OptIn(InternalAPI::class)
        val SharedArrayList: MutableList = mutableListOf()
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy