1 /*
2  * Copyright (C) 2019 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 package com.android.internal.infra;
17 
18 import android.annotation.NonNull;
19 import android.util.SparseArray;
20 
21 import com.android.internal.util.Preconditions;
22 
23 /**
24  * A {@link SparseArray} customized for a common use-case of storing state per-user.
25  *
26  * Unlike a normal {@link SparseArray} this will always create a value on {@link #get} if one is
27  * not present instead of returning null.
28  *
29  * @param <T> user state type
30  */
31 public abstract class PerUser<T> extends SparseArray<T> {
32 
33     /**
34      * Initialize state for the given user
35      */
create(int userId)36     protected abstract @NonNull T create(int userId);
37 
38     /**
39      * Same as {@link #get(int)}, renamed for readability.
40      *
41      * This will never return null, deferring to {@link #create} instead
42      * when called for the first time.
43      */
forUser(int userId)44     public @NonNull T forUser(int userId) {
45         return get(userId);
46     }
47 
48     @Override
get(int userId)49     public @NonNull T get(int userId) {
50         T userState = super.get(userId);
51         if (userState != null) {
52             return userState;
53         } else {
54             userState = Preconditions.checkNotNull(create(userId));
55             put(userId, userState);
56             return userState;
57         }
58     }
59 }
60