LLVM API Documentation

IndexedMap.h
Go to the documentation of this file.
00001 //===- llvm/ADT/IndexedMap.h - An index map implementation ------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements an indexed map. The index map template takes two
00011 // types. The first is the mapped type and the second is a functor
00012 // that maps its argument to a size_t. On instantiation a "null" value
00013 // can be provided to be used as a "does not exist" indicator in the
00014 // map. A member function grow() is provided that given the value of
00015 // the maximally indexed key (the argument of the functor) makes sure
00016 // the map has enough space for it.
00017 //
00018 //===----------------------------------------------------------------------===//
00019 
00020 #ifndef LLVM_ADT_INDEXEDMAP_H
00021 #define LLVM_ADT_INDEXEDMAP_H
00022 
00023 #include "llvm/ADT/STLExtras.h"
00024 #include <cassert>
00025 #include <functional>
00026 #include <vector>
00027 
00028 namespace llvm {
00029 
00030 template <typename T, typename ToIndexT = llvm::identity<unsigned> >
00031   class IndexedMap {
00032     typedef typename ToIndexT::argument_type IndexT;
00033     typedef std::vector<T> StorageT;
00034     StorageT storage_;
00035     T nullVal_;
00036     ToIndexT toIndex_;
00037 
00038   public:
00039     IndexedMap() : nullVal_(T()) { }
00040 
00041     explicit IndexedMap(const T& val) : nullVal_(val) { }
00042 
00043     typename StorageT::reference operator[](IndexT n) {
00044       assert(toIndex_(n) < storage_.size() && "index out of bounds!");
00045       return storage_[toIndex_(n)];
00046     }
00047 
00048     typename StorageT::const_reference operator[](IndexT n) const {
00049       assert(toIndex_(n) < storage_.size() && "index out of bounds!");
00050       return storage_[toIndex_(n)];
00051     }
00052 
00053     void reserve(typename StorageT::size_type s) {
00054       storage_.reserve(s);
00055     }
00056 
00057     void resize(typename StorageT::size_type s) {
00058       storage_.resize(s, nullVal_);
00059     }
00060 
00061     void clear() {
00062       storage_.clear();
00063     }
00064 
00065     void grow(IndexT n) {
00066       unsigned NewSize = toIndex_(n) + 1;
00067       if (NewSize > storage_.size())
00068         resize(NewSize);
00069     }
00070 
00071     bool inBounds(IndexT n) const {
00072       return toIndex_(n) < storage_.size();
00073     }
00074 
00075     typename StorageT::size_type size() const {
00076       return storage_.size();
00077     }
00078   };
00079 
00080 } // End llvm namespace
00081 
00082 #endif