1 /* 2 * Copyright 2024 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package androidx.compose.runtime.collection 18 19 import androidx.collection.ScatterSet 20 21 /** 22 * A wrapper for [ScatterSet] that implements [Set] APIs. This wrapper allows to use [ScatterSet] 23 * through external APIs and unwrap it back into [Set] for faster iteration / other operations. 24 */ 25 internal class ScatterSetWrapper<T>(internal val set: ScatterSet<T>) : Set<T> { 26 override val size: Int 27 get() = set.size 28 isEmptynull29 override fun isEmpty(): Boolean = set.isEmpty() 30 31 override fun iterator(): Iterator<T> = iterator { set.forEach { yield(it) } } 32 <lambda>null33 override fun containsAll(elements: Collection<T>): Boolean = elements.all { set.contains(it) } 34 containsnull35 override fun contains(element: T): Boolean = set.contains(element) 36 } 37 38 internal fun <T> ScatterSet<T>.wrapIntoSet(): Set<T> = ScatterSetWrapper(this) 39 40 internal inline fun <T : Any> Set<T>.fastForEach(block: (T) -> Unit) = 41 when (this) { 42 is ScatterSetWrapper<T> -> { 43 set.forEach(block) 44 } 45 else -> { 46 forEach(block) 47 } 48 } 49 fastAnynull50internal inline fun Set<Any>.fastAny(block: (Any) -> Boolean) = 51 if (this is ScatterSetWrapper<Any>) { 52 set.any(block) 53 } else { 54 any(block) 55 } 56