IndexedMap.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. //===- llvm/ADT/IndexedMap.h - An index map implementation ------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements an indexed map. The index map template takes two
  10. // types. The first is the mapped type and the second is a functor
  11. // that maps its argument to a size_t. On instantiation a "null" value
  12. // can be provided to be used as a "does not exist" indicator in the
  13. // map. A member function grow() is provided that given the value of
  14. // the maximally indexed key (the argument of the functor) makes sure
  15. // the map has enough space for it.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_ADT_INDEXEDMAP_H
  19. #define LLVM_ADT_INDEXEDMAP_H
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/ADT/STLExtras.h"
  22. #include <cassert>
  23. namespace llvm {
  24. template <typename T, typename ToIndexT = identity<unsigned>>
  25. class IndexedMap {
  26. using IndexT = typename ToIndexT::argument_type;
  27. // Prefer SmallVector with zero inline storage over std::vector. IndexedMaps
  28. // can grow very large and SmallVector grows more efficiently as long as T
  29. // is trivially copyable.
  30. using StorageT = SmallVector<T, 0>;
  31. StorageT storage_;
  32. T nullVal_;
  33. ToIndexT toIndex_;
  34. public:
  35. IndexedMap() : nullVal_(T()) {}
  36. explicit IndexedMap(const T& val) : nullVal_(val) {}
  37. typename StorageT::reference operator[](IndexT n) {
  38. assert(toIndex_(n) < storage_.size() && "index out of bounds!");
  39. return storage_[toIndex_(n)];
  40. }
  41. typename StorageT::const_reference operator[](IndexT n) const {
  42. assert(toIndex_(n) < storage_.size() && "index out of bounds!");
  43. return storage_[toIndex_(n)];
  44. }
  45. void reserve(typename StorageT::size_type s) {
  46. storage_.reserve(s);
  47. }
  48. void resize(typename StorageT::size_type s) {
  49. storage_.resize(s, nullVal_);
  50. }
  51. void clear() {
  52. storage_.clear();
  53. }
  54. void grow(IndexT n) {
  55. unsigned NewSize = toIndex_(n) + 1;
  56. if (NewSize > storage_.size())
  57. resize(NewSize);
  58. }
  59. bool inBounds(IndexT n) const {
  60. return toIndex_(n) < storage_.size();
  61. }
  62. typename StorageT::size_type size() const {
  63. return storage_.size();
  64. }
  65. };
  66. } // end namespace llvm
  67. #endif // LLVM_ADT_INDEXEDMAP_H