1 //===- llvm/ADT/SmallSet.h - 'Normally small' sets --------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source 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"
22 /// SmallSet - This maintains a set of unique values, optimizing for the case
23 /// when the set is small (less than N). In this case, the set can be
24 /// maintained with no mallocs. If the set gets large, we expand to using an
25 /// std::set to maintain reasonable lookup times.
27 /// Note that this set does not provide a way to iterate over members in the
29 template <typename T, unsigned N>
31 /// Use a SmallVector to hold the elements here (even though it will never
32 /// reach it's 'large' stage) to avoid calling the default ctors of elements
33 /// we will never use.
34 SmallVector<T, N> Vector;
36 typedef typename SmallVector<T, N>::const_iterator VIterator;
37 typedef typename SmallVector<T, N>::iterator mutable_iterator;
41 bool empty() const { return Vector.empty() && Set.empty(); }
42 unsigned size() const {
43 return isSmall() ? Vector.size() : Set.size();
46 /// count - Return true if the element is in the set.
47 bool count(const T &V) const {
49 // Since the collection is small, just do a linear search.
50 return vfind(V) != Vector.end();
56 /// insert - Insert an element into the set if it isn't already there.
57 bool insert(const T &V) {
59 return Set.insert(V).second;
61 VIterator I = vfind(V);
62 if (I != Vector.end()) // Don't reinsert if it already exists.
64 if (Vector.size() < N) {
69 // Otherwise, grow from vector to set.
70 while (!Vector.empty()) {
71 Set.insert(Vector.back());
78 bool erase(const T &V) {
80 return Set.erase(V).second;
81 for (mutable_iterator I = Vector.begin(), E = Vector.end(); I != E; ++I)
94 bool isSmall() const { return Set.empty(); }
96 VIterator vfind(const T &V) const {
97 for (VIterator I = Vector.begin(), E = Vector.end(); I != E; ++I)
105 } // end namespace llvm