DenseMap.h revision fc093bd0810b6e726c02c2430f77618fd7255541
1//===- 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 SUPPORT_DENSEMAP_H
21#define SUPPORT_DENSEMAP_H
22
23#include <vector>
24
25namespace llvm {
26
27  struct IdentityFunctor : std::unary_function<unsigned, unsigned> {
28    unsigned operator()(unsigned Index) const {
29      return Index;
30    }
31  };
32
33  template <typename T, typename ToIndexT = IdentityFunctor>
34  class DenseMap {
35    typedef typename ToIndexT::argument_type IndexT;
36    typedef std::vector<T> StorageT;
37    StorageT storage_;
38    T nullVal_;
39    ToIndexT toIndex_;
40
41  public:
42    DenseMap() : nullVal_(T()) { }
43
44    explicit DenseMap(const T& val) : nullVal_(val) { }
45
46    typename StorageT::reference operator[](IndexT n) {
47      assert(toIndex_(n) < storage_.size() && "index out of bounds!");
48      return storage_[toIndex_(n)];
49    }
50
51    typename StorageT::const_reference operator[](IndexT n) const {
52      assert(toIndex_(n) < storage_.size() && "index out of bounds!");
53      return storage_[toIndex_(n)];
54    }
55
56    void clear() {
57      storage_.clear();
58    }
59
60    void grow(IndexT n) {
61      unsigned NewSize = toIndex_(n) + 1;
62      if (NewSize > storage_.size())
63        storage_.resize(NewSize, nullVal_);
64    }
65
66    typename StorageT::size_type size() const {
67      return storage_.size();
68    }
69  };
70
71} // End llvm namespace
72
73#endif
74