1 /* 2 * Copyright 2023 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.snapshots 18 19 import androidx.compose.runtime.Composition 20 import androidx.compose.runtime.internal.AtomicInt 21 import kotlin.jvm.JvmInline 22 23 /** 24 * A [StateObject] that allows to record reader type when observed to optimize recording of 25 * modifications. Currently only reads in [Composition] and [SnapshotStateObserver] is supported. 26 * The methods are intentionally restricted to the internal types, as the API is expected to change. 27 */ 28 internal abstract class StateObjectImpl internal constructor() : StateObject { 29 private val readerKind = AtomicInt(0) 30 recordReadInnull31 internal fun recordReadIn(reader: ReaderKind) { 32 do { 33 val old = ReaderKind(readerKind.get()) 34 if (old.isReadIn(reader)) return 35 36 val new = old.withReadIn(reader) 37 } while (!readerKind.compareAndSet(old.mask, new.mask)) 38 } 39 isReadInnull40 internal fun isReadIn(reader: ReaderKind): Boolean = 41 ReaderKind(readerKind.get()).isReadIn(reader) 42 } 43 44 @JvmInline 45 internal value class ReaderKind(val mask: Int = 0) { 46 @Suppress("NOTHING_TO_INLINE") 47 inline fun withReadIn(reader: ReaderKind): ReaderKind = ReaderKind(mask or reader.mask) 48 49 @Suppress("NOTHING_TO_INLINE") 50 inline fun isReadIn(reader: ReaderKind): Boolean = mask and reader.mask != 0 51 52 internal companion object { 53 inline val Composition 54 get() = ReaderKind(mask = 1 shl 0) 55 56 inline val SnapshotStateObserver 57 get() = ReaderKind(mask = 1 shl 1) 58 59 inline val SnapshotFlow 60 get() = ReaderKind(mask = 1 shl 2) 61 } 62 } 63