IndexedMap.h 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. #ifndef LLVM_ADT_INDEXEDMAP_H
  20. #define LLVM_ADT_INDEXEDMAP_H
  21. #include "llvm/ADT/STLExtras.h"
  22. #include "llvm/ADT/SmallVector.h"
  23. #include <cassert>
  24. #include <functional>
  25. namespace llvm {
  26. template <typename T, typename ToIndexT = llvm::identity<unsigned> >
  27. class IndexedMap {
  28. typedef typename ToIndexT::argument_type IndexT;
  29. // Prefer SmallVector with zero inline storage over std::vector. IndexedMaps
  30. // can grow very large and SmallVector grows more efficiently as long as T
  31. // is trivially copyable.
  32. typedef SmallVector<T, 0> StorageT;
  33. StorageT storage_;
  34. T nullVal_;
  35. ToIndexT toIndex_;
  36. public:
  37. IndexedMap() : nullVal_(T()) { }
  38. explicit IndexedMap(const T& val) : nullVal_(val) { }
  39. typename StorageT::reference operator[](IndexT n) {
  40. assert(toIndex_(n) < storage_.size() && "index out of bounds!");
  41. return storage_[toIndex_(n)];
  42. }
  43. typename StorageT::const_reference operator[](IndexT n) const {
  44. assert(toIndex_(n) < storage_.size() && "index out of bounds!");
  45. return storage_[toIndex_(n)];
  46. }
  47. void reserve(typename StorageT::size_type s) {
  48. storage_.reserve(s);
  49. }
  50. void resize(typename StorageT::size_type s) {
  51. storage_.resize(s, nullVal_);
  52. }
  53. void clear() {
  54. storage_.clear();
  55. }
  56. void grow(IndexT n) {
  57. unsigned NewSize = toIndex_(n) + 1;
  58. if (NewSize > storage_.size())
  59. resize(NewSize);
  60. }
  61. bool inBounds(IndexT n) const {
  62. return toIndex_(n) < storage_.size();
  63. }
  64. typename StorageT::size_type size() const {
  65. return storage_.size();
  66. }
  67. };
  68. } // End llvm namespace
  69. #endif