TinyHashMap.h revision 527a3aace1dd72432c2e0472a570e030ad04bf16
1/* 2 * Copyright (C) 2013 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#ifndef ANDROID_HWUI_TINYHASHMAP_H 18#define ANDROID_HWUI_TINYHASHMAP_H 19 20#include <utils/BasicHashtable.h> 21 22namespace android { 23namespace uirenderer { 24 25/** 26 * A very simple hash map that doesn't allow duplicate keys, overwriting the older entry. 27 * 28 * Currently, expects simple keys that are handled by hash_t() 29 */ 30template <typename TKey, typename TValue> 31class TinyHashMap { 32public: 33 typedef key_value_pair_t<TKey, TValue> TEntry; 34 35 /** 36 * Puts an entry in the hash, removing any existing entry with the same key 37 */ 38 void put(TKey key, TValue value) { 39 hash_t hash = hash_t(key); 40 41 ssize_t index = mTable.find(-1, hash, key); 42 if (index != -1) { 43 mTable.removeAt(index); 44 } 45 46 TEntry initEntry(key, value); 47 mTable.add(hash, initEntry); 48 } 49 50 /** 51 * Return true if key is in the map, in which case stores the value in the output ref 52 */ 53 bool get(TKey key, TValue& outValue) { 54 hash_t hash = hash_t(key); 55 ssize_t index = mTable.find(-1, hash, key); 56 if (index == -1) { 57 return false; 58 } 59 outValue = mTable.entryAt(index).value; 60 return true; 61 } 62 63 void clear() { mTable.clear(); } 64 65private: 66 BasicHashtable<TKey, TEntry> mTable; 67}; 68 69}; // namespace uirenderer 70}; // namespace android 71 72#endif // ANDROID_HWUI_TINYHASHMAP_H 73