1 //===- llvm/ADT/IndexedMap.h - An index map implementation ------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
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.
17 //===----------------------------------------------------------------------===//
19 #ifndef LLVM_ADT_INDEXEDMAP_H
20 #define LLVM_ADT_INDEXEDMAP_H
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/STLExtras.h"
28 template <typename T
, typename ToIndexT
= identity
<unsigned>>
30 using IndexT
= typename
ToIndexT::argument_type
;
31 // Prefer SmallVector with zero inline storage over std::vector. IndexedMaps
32 // can grow very large and SmallVector grows more efficiently as long as T
33 // is trivially copyable.
34 using StorageT
= SmallVector
<T
, 0>;
41 IndexedMap() : nullVal_(T()) {}
43 explicit IndexedMap(const T
& val
) : nullVal_(val
) {}
45 typename
StorageT::reference
operator[](IndexT n
) {
46 assert(toIndex_(n
) < storage_
.size() && "index out of bounds!");
47 return storage_
[toIndex_(n
)];
50 typename
StorageT::const_reference
operator[](IndexT n
) const {
51 assert(toIndex_(n
) < storage_
.size() && "index out of bounds!");
52 return storage_
[toIndex_(n
)];
55 void reserve(typename
StorageT::size_type s
) {
59 void resize(typename
StorageT::size_type s
) {
60 storage_
.resize(s
, nullVal_
);
68 unsigned NewSize
= toIndex_(n
) + 1;
69 if (NewSize
> storage_
.size())
73 bool inBounds(IndexT n
) const {
74 return toIndex_(n
) < storage_
.size();
77 typename
StorageT::size_type
size() const {
78 return storage_
.size();
82 } // end namespace llvm
84 #endif // LLVM_ADT_INDEXEDMAP_H