1 //===- llvm/ADT/IndexedMap.h - An index map implementation ------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements an indexed map. The index map template takes two
11 // types. The first is the mapped type and the second is a functor
12 // that maps its argument to a size_t. On instantiation a "null" value
13 // can be provided to be used as a "does not exist" indicator in the
14 // map. A member function grow() is provided that given the value of
15 // the maximally indexed key (the argument of the functor) makes sure
16 // the map has enough space for it.
18 //===----------------------------------------------------------------------===//
20 #ifndef LLVM_ADT_INDEXEDMAP_H
21 #define LLVM_ADT_INDEXEDMAP_H
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallVector.h"
30 template <typename T, typename ToIndexT = llvm::identity<unsigned> >
32 typedef typename ToIndexT::argument_type IndexT;
33 // Prefer SmallVector with zero inline storage over std::vector. IndexedMaps
34 // can grow very large and SmallVector grows more efficiently as long as T
35 // is trivially copyable.
36 typedef SmallVector<T, 0> StorageT;
42 IndexedMap() : nullVal_(T()) { }
44 explicit IndexedMap(const T& val) : nullVal_(val) { }
46 typename StorageT::reference operator[](IndexT n) {
47 assert(toIndex_(n) < storage_.size() && "index out of bounds!");
48 return storage_[toIndex_(n)];
51 typename StorageT::const_reference operator[](IndexT n) const {
52 assert(toIndex_(n) < storage_.size() && "index out of bounds!");
53 return storage_[toIndex_(n)];
56 void reserve(typename StorageT::size_type s) {
60 void resize(typename StorageT::size_type s) {
61 storage_.resize(s, nullVal_);
69 unsigned NewSize = toIndex_(n) + 1;
70 if (NewSize > storage_.size())
74 bool inBounds(IndexT n) const {
75 return toIndex_(n) < storage_.size();
78 typename StorageT::size_type size() const {
79 return storage_.size();
83 } // End llvm namespace