blob: 2e7f2a92e1d9d6318b265197880d10b9c8a2b139 [file] [log] [blame]
Yohei Yukawa3f8c5682018-03-01 13:10:23 -08001/*
2 * Copyright (C) 2018 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
Yohei Yukawa81e806a2018-09-12 15:33:25 -070017package com.android.server.textservices;
Yohei Yukawa3f8c5682018-03-01 13:10:23 -080018
19import android.annotation.NonNull;
20import android.util.SparseIntArray;
21
Yohei Yukawa3f8c5682018-03-01 13:10:23 -080022import java.util.function.IntUnaryOperator;
23
24/**
25 * Simple int-to-int key-value-store that is to be lazily initialized with the given
26 * {@link IntUnaryOperator}.
27 */
Yohei Yukawa81e806a2018-09-12 15:33:25 -070028final class LazyIntToIntMap {
Yohei Yukawa3f8c5682018-03-01 13:10:23 -080029
30 private final SparseIntArray mMap = new SparseIntArray();
31
32 @NonNull
33 private final IntUnaryOperator mMappingFunction;
34
35 /**
36 * @param mappingFunction int to int mapping rules to be (lazily) evaluated
37 */
38 public LazyIntToIntMap(@NonNull IntUnaryOperator mappingFunction) {
39 mMappingFunction = mappingFunction;
40 }
41
42 /**
43 * Deletes {@code key} and associated value.
44 * @param key key to be deleted
45 */
46 public void delete(int key) {
47 mMap.delete(key);
48 }
49
50 /**
51 * @param key key associated with the value
52 * @return value associated with the {@code key}. If this is the first time to access
53 * {@code key}, then {@code mappingFunction} passed to the constructor will be evaluated
54 */
55 public int get(int key) {
56 final int index = mMap.indexOfKey(key);
57 if (index >= 0) {
58 return mMap.valueAt(index);
59 }
60 final int value = mMappingFunction.applyAsInt(key);
61 mMap.append(key, value);
62 return value;
63 }
64}