DenseMap.h revision df8d5e908fe83dafe98a05086956e7b0943af1e0
1//===- llvm/ADT/DenseMap.h - A dense map implmentation ----------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a dense map. A dense 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_DENSEMAP_H
21#define LLVM_ADT_DENSEMAP_H
22
23#include <functional>
24#include <vector>
25
26namespace llvm {
27
28  struct IdentityFunctor : std::unary_function<unsigned, unsigned> {
29    unsigned operator()(unsigned Index) const {
30      return Index;
31    }
32  };
33
34  template <typename T, typename ToIndexT = IdentityFunctor>
35  class DenseMap {
36    typedef typename ToIndexT::argument_type IndexT;
37    typedef std::vector<T> StorageT;
38    StorageT storage_;
39    T nullVal_;
40    ToIndexT toIndex_;
41
42  public:
43    DenseMap() : nullVal_(T()) { }
44
45    explicit DenseMap(const T& val) : nullVal_(val) { }
46
47    typename StorageT::reference operator[](IndexT n) {
48      assert(toIndex_(n) < storage_.size() && "index out of bounds!");
49      return storage_[toIndex_(n)];
50    }
51
52    typename StorageT::const_reference operator[](IndexT n) const {
53      assert(toIndex_(n) < storage_.size() && "index out of bounds!");
54      return storage_[toIndex_(n)];
55    }
56
57    void clear() {
58      storage_.clear();
59    }
60
61    void grow(IndexT n) {
62      unsigned NewSize = toIndex_(n) + 1;
63      if (NewSize > storage_.size())
64        storage_.resize(NewSize, nullVal_);
65    }
66
67    typename StorageT::size_type size() const {
68      return storage_.size();
69    }
70  };
71
72} // End llvm namespace
73
74#endif
75