Home | History | Annotate | Download | only in utils
      1 /*
      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 
     22 #ifndef ART_COMPILER_UTILS_SCOPED_HASHTABLE_H_
     23 #define ART_COMPILER_UTILS_SCOPED_HASHTABLE_H_
     24 
     25 namespace utils {
     26 template <typename K, typename V>
     27 class 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 };
     69 }  // namespace utils
     70 
     71 #endif  // ART_COMPILER_UTILS_SCOPED_HASHTABLE_H_
     72