1 /*
2  * Copyright (C) 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 com.android.providers.media.util;
18 
19 
20 import static androidx.core.util.Preconditions.checkNotNull;
21 
22 import android.annotation.UserIdInt;
23 import android.util.SparseArray;
24 
25 import androidx.annotation.NonNull;
26 
27 /**
28  * A {@link SparseArray} customized for a common use-case of storing state per-user.
29  *
30  * @param <T> user state type
31  */
32 public abstract class PerUser<T> extends SparseArray<T> {
33     /**
34      * Initialize state for the given user
35      */
36     @NonNull
create(@serIdInt int userId)37     protected abstract T create(@UserIdInt int userId);
38 
39     /**
40      * @return -
41      *      {@link #get(int)} if not {@code null} or
42      *      {@link #create(int)} otherwise.
43      */
44     @NonNull
forUser(@serIdInt int userId)45     public T forUser(@UserIdInt int userId) {
46         T userState = super.get(userId);
47         if (userState == null) {
48             userState = checkNotNull(create(userId));
49             put(userId, userState);
50         }
51         return userState;
52     }
53 }
54