1//===- llvm/ADT/IndexedMap.h - An index map implementation ------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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.
17//
18//===----------------------------------------------------------------------===//
19
20#ifndef LLVM_ADT_INDEXEDMAP_H
21#define LLVM_ADT_INDEXEDMAP_H
22
23#include <cassert>
24#include <functional>
25#include <vector>
26
27namespace llvm {
28
29  struct IdentityFunctor : public std::unary_function<unsigned, unsigned> {
30    unsigned operator()(unsigned Index) const {
31      return Index;
32    }
33  };
34
35  template <typename T, typename ToIndexT = IdentityFunctor>
36  class IndexedMap {
37    typedef typename ToIndexT::argument_type IndexT;
38    typedef std::vector<T> StorageT;
39    StorageT storage_;
40    T nullVal_;
41    ToIndexT toIndex_;
42
43  public:
44    IndexedMap() : nullVal_(T()) { }
45
46    explicit IndexedMap(const T& val) : nullVal_(val) { }
47
48    typename StorageT::reference operator[](IndexT n) {
49      assert(toIndex_(n) < storage_.size() && "index out of bounds!");
50      return storage_[toIndex_(n)];
51    }
52
53    typename StorageT::const_reference operator[](IndexT n) const {
54      assert(toIndex_(n) < storage_.size() && "index out of bounds!");
55      return storage_[toIndex_(n)];
56    }
57
58    void reserve(typename StorageT::size_type s) {
59      storage_.reserve(s);
60    }
61
62    void resize(typename StorageT::size_type s) {
63      storage_.resize(s, nullVal_);
64    }
65
66    void clear() {
67      storage_.clear();
68    }
69
70    void grow(IndexT n) {
71      unsigned NewSize = toIndex_(n) + 1;
72      if (NewSize > storage_.size())
73        resize(NewSize);
74    }
75
76    bool inBounds(IndexT n) const {
77      return toIndex_(n) < storage_.size();
78    }
79
80    typename StorageT::size_type size() const {
81      return storage_.size();
82    }
83  };
84
85} // End llvm namespace
86
87#endif
88