1 //===- llvm/ADT/SmallSet.h - 'Normally small' sets --------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the SmallSet class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ADT_SMALLSET_H
15 #define LLVM_ADT_SMALLSET_H
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
23 /// SmallSet - This maintains a set of unique values, optimizing for the case
24 /// when the set is small (less than N). In this case, the set can be
25 /// maintained with no mallocs. If the set gets large, we expand to using an
26 /// std::set to maintain reasonable lookup times.
28 /// Note that this set does not provide a way to iterate over members in the
30 template <typename T, unsigned N>
32 /// Use a SmallVector to hold the elements here (even though it will never
33 /// reach its 'large' stage) to avoid calling the default ctors of elements
34 /// we will never use.
35 SmallVector<T, N> Vector;
37 typedef typename SmallVector<T, N>::const_iterator VIterator;
38 typedef typename SmallVector<T, N>::iterator mutable_iterator;
42 bool empty() const { return Vector.empty() && Set.empty(); }
43 unsigned size() const {
44 return isSmall() ? Vector.size() : Set.size();
47 /// count - Return true if the element is in the set.
48 bool count(const T &V) const {
50 // Since the collection is small, just do a linear search.
51 return vfind(V) != Vector.end();
57 /// insert - Insert an element into the set if it isn't already there.
58 bool insert(const T &V) {
60 return Set.insert(V).second;
62 VIterator I = vfind(V);
63 if (I != Vector.end()) // Don't reinsert if it already exists.
65 if (Vector.size() < N) {
70 // Otherwise, grow from vector to set.
71 while (!Vector.empty()) {
72 Set.insert(Vector.back());
79 template <typename IterT>
80 void insert(IterT I, IterT E) {
85 bool erase(const T &V) {
88 for (mutable_iterator I = Vector.begin(), E = Vector.end(); I != E; ++I)
101 bool isSmall() const { return Set.empty(); }
103 VIterator vfind(const T &V) const {
104 for (VIterator I = Vector.begin(), E = Vector.end(); I != E; ++I)
111 /// If this set is of pointer values, transparently switch over to using
112 /// SmallPtrSet for performance.
113 template <typename PointeeType, unsigned N>
114 class SmallSet<PointeeType*, N> : public SmallPtrSet<PointeeType*, N> {};
116 } // end namespace llvm