Yohei Yukawa | 3f8c568 | 2018-03-01 13:10:23 -0800 | [diff] [blame] | 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 | |
Yohei Yukawa | 81e806a | 2018-09-12 15:33:25 -0700 | [diff] [blame] | 17 | package com.android.server.textservices; |
Yohei Yukawa | 3f8c568 | 2018-03-01 13:10:23 -0800 | [diff] [blame] | 18 | |
| 19 | import android.annotation.NonNull; |
| 20 | import android.util.SparseIntArray; |
| 21 | |
Yohei Yukawa | 3f8c568 | 2018-03-01 13:10:23 -0800 | [diff] [blame] | 22 | import 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 Yukawa | 81e806a | 2018-09-12 15:33:25 -0700 | [diff] [blame] | 28 | final class LazyIntToIntMap { |
Yohei Yukawa | 3f8c568 | 2018-03-01 13:10:23 -0800 | [diff] [blame] | 29 | |
| 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 | } |