blob: ccec7bafa443e8e54a26cd317a0649085716b216 [file] [log] [blame]
Dragos Sbirlea8cc51622013-06-21 09:20:34 -07001/*
2 * Copyright (C) 2013 The Android Open Source Project
3
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18#include <stddef.h>
19#include <map>
20#include <list>
21
Brian Carlstroma6468f62013-07-19 11:36:19 -070022#ifndef ART_COMPILER_UTILS_SCOPED_HASHTABLE_H_
23#define ART_COMPILER_UTILS_SCOPED_HASHTABLE_H_
Dragos Sbirlea8cc51622013-06-21 09:20:34 -070024
25namespace utils {
26template <typename K, typename V>
27class ScopedHashtable {
28 public:
29 explicit ScopedHashtable():scopes() {
30 }
31
32 void OpenScope() {
33 scopes.push_front(std::map<K, V>());
34 }
35
36 // Lookups entry K starting from the current (topmost) scope
37 // and returns its value if found or NULL.
38 V Lookup(K k) const {
39 for (typename std::list<std::map<K, V> >::const_iterator scopes_it = scopes.begin();
40 scopes_it != scopes.end(); scopes_it++) {
41 typename std::map<K, V>::const_iterator result_it = (*scopes_it).find(k);
42 if (result_it != (*scopes_it).end()) {
43 return (*result_it).second;
44 }
45 }
46 return NULL;
47 }
48
49 // Adds a new entry in the current (topmost) scope.
50 void Add(K k, V v) {
51 scopes.front().erase(k);
52 scopes.front().insert(std::pair< K, V >(k, v));
53 }
54
55 // Removes the topmost scope.
56 bool CloseScope() {
57 // Added check to uniformly handle undefined behavior
58 // when removing scope and the list of scopes is empty.
59 if (scopes.size() > 0) {
60 scopes.pop_front();
61 return true;
62 }
63 return false;
64 }
65
66 private:
67 std::list<std::map<K, V> > scopes;
68};
Brian Carlstrom7934ac22013-07-26 10:54:15 -070069} // namespace utils
Dragos Sbirlea8cc51622013-06-21 09:20:34 -070070
Brian Carlstroma6468f62013-07-19 11:36:19 -070071#endif // ART_COMPILER_UTILS_SCOPED_HASHTABLE_H_