• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 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 com.android.systemui.scene.data.model
18 
19 import com.android.compose.animation.scene.SceneKey
20 
21 /** An immutable stack of [SceneKey]s backed by a singly-linked list. */
22 sealed interface SceneStack
23 
24 private data object EmptyStack : SceneStack
25 
26 private data class StackedNodes(val head: SceneKey, val tail: SceneStack) : SceneStack
27 
28 /** Returns the scene at the head of the stack, or `null` if empty. O(1) */
SceneStacknull29 fun SceneStack.peek(): SceneKey? =
30     when (this) {
31         EmptyStack -> null
32         is StackedNodes -> head
33     }
34 
35 /** Returns a stack with the head removed, or `null` if empty. O(1) */
SceneStacknull36 fun SceneStack.pop(): SceneStack? =
37     when (this) {
38         EmptyStack -> null
39         is StackedNodes -> tail
40     }
41 
42 /** Returns a stack with [sceneKey] as the head on top of [this]. O(1) */
SceneStacknull43 fun SceneStack.push(sceneKey: SceneKey): SceneStack = StackedNodes(sceneKey, this)
44 
45 /** Returns an iterable that produces all elements in the stack, from head to tail. */
46 fun SceneStack.asIterable(): Iterable<SceneKey> = Iterable {
47     iterator {
48         when (this@asIterable) {
49             EmptyStack -> {}
50             is StackedNodes -> {
51                 yield(head)
52                 yieldAll(tail.asIterable())
53             }
54         }
55     }
56 }
57 
58 /**
59  * Returns a new [SceneStack] containing the given [scenes], ordered such that the first argument is
60  * the head returned from [peek], then the second, and so forth.
61  */
sceneStackOfnull62 fun sceneStackOf(vararg scenes: SceneKey): SceneStack {
63     var result: SceneStack = EmptyStack
64     for (sceneKey in scenes.reversed()) {
65         result = result.push(sceneKey)
66     }
67     return result
68 }
69