1 /* 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 17 package com.android.internal.textservice; 18 19 import android.annotation.NonNull; 20 import android.util.SparseIntArray; 21 22 import com.android.internal.annotations.VisibleForTesting; 23 24 import java.util.function.IntUnaryOperator; 25 26 /** 27 * Simple int-to-int key-value-store that is to be lazily initialized with the given 28 * {@link IntUnaryOperator}. 29 */ 30 @VisibleForTesting 31 public final class LazyIntToIntMap { 32 33 private final SparseIntArray mMap = new SparseIntArray(); 34 35 @NonNull 36 private final IntUnaryOperator mMappingFunction; 37 38 /** 39 * @param mappingFunction int to int mapping rules to be (lazily) evaluated 40 */ 41 public LazyIntToIntMap(@NonNull IntUnaryOperator mappingFunction) { 42 mMappingFunction = mappingFunction; 43 } 44 45 /** 46 * Deletes {@code key} and associated value. 47 * @param key key to be deleted 48 */ 49 public void delete(int key) { 50 mMap.delete(key); 51 } 52 53 /** 54 * @param key key associated with the value 55 * @return value associated with the {@code key}. If this is the first time to access 56 * {@code key}, then {@code mappingFunction} passed to the constructor will be evaluated 57 */ 58 public int get(int key) { 59 final int index = mMap.indexOfKey(key); 60 if (index >= 0) { 61 return mMap.valueAt(index); 62 } 63 final int value = mMappingFunction.applyAsInt(key); 64 mMap.append(key, value); 65 return value; 66 } 67 } 68