1 //===--- StringMap.h - String Hash table map interface ----------*- 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 StringMap class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ADT_STRINGMAP_H
15 #define LLVM_ADT_STRINGMAP_H
17 #include "llvm/Support/Allocator.h"
22 template<typename ValueT>
23 class StringMapConstIterator;
24 template<typename ValueT>
25 class StringMapIterator;
26 template<typename ValueTy>
29 /// StringMapEntryInitializer - This datatype can be partially specialized for
30 /// various datatypes in a stringmap to allow them to be initialized when an
31 /// entry is default constructed for the map.
32 template<typename ValueTy>
33 class StringMapEntryInitializer {
35 template <typename InitTy>
36 static void Initialize(StringMapEntry<ValueTy> &T, InitTy InitVal) {
41 /// StringMapEntryBase - Shared base class of StringMapEntry instances.
42 class StringMapEntryBase {
45 explicit StringMapEntryBase(unsigned Len) : StrLen(Len) {}
47 unsigned getKeyLength() const { return StrLen; }
50 /// StringMapImpl - This is the base class of StringMap that is shared among
51 /// all of its instantiations.
54 /// ItemBucket - The hash table consists of an array of these. If Item is
55 /// non-null, this is an extant entry, otherwise, it is a hole.
57 /// FullHashValue - This remembers the full hash value of the key for
59 unsigned FullHashValue;
61 /// Item - This is a pointer to the actual item object.
62 StringMapEntryBase *Item;
69 unsigned NumTombstones;
72 explicit StringMapImpl(unsigned itemSize) : ItemSize(itemSize) {
73 // Initialize the map with zero buckets to allocation.
79 StringMapImpl(unsigned InitSize, unsigned ItemSize);
82 /// ShouldRehash - Return true if the table should be rehashed after a new
83 /// element was recently inserted.
84 bool ShouldRehash() const {
85 // If the hash table is now more than 3/4 full, or if fewer than 1/8 of
86 // the buckets are empty (meaning that many are filled with tombstones),
88 return NumItems*4 > NumBuckets*3 ||
89 NumBuckets-(NumItems+NumTombstones) < NumBuckets/8;
92 /// LookupBucketFor - Look up the bucket that the specified string should end
93 /// up in. If it already exists as a key in the map, the Item pointer for the
94 /// specified bucket will be non-null. Otherwise, it will be null. In either
95 /// case, the FullHashValue field of the bucket will be set to the hash value
97 unsigned LookupBucketFor(const char *KeyStart, const char *KeyEnd);
99 /// FindKey - Look up the bucket that contains the specified key. If it exists
100 /// in the map, return the bucket number of the key. Otherwise return -1.
101 /// This does not modify the map.
102 int FindKey(const char *KeyStart, const char *KeyEnd) const;
104 /// RemoveKey - Remove the specified StringMapEntry from the table, but do not
105 /// delete it. This aborts if the value isn't in the table.
106 void RemoveKey(StringMapEntryBase *V);
108 /// RemoveKey - Remove the StringMapEntry for the specified key from the
109 /// table, returning it. If the key is not in the table, this returns null.
110 StringMapEntryBase *RemoveKey(const char *KeyStart, const char *KeyEnd);
112 void init(unsigned Size);
114 static StringMapEntryBase *getTombstoneVal() {
115 return (StringMapEntryBase*)-1;
118 unsigned getNumBuckets() const { return NumBuckets; }
119 unsigned getNumItems() const { return NumItems; }
121 bool empty() const { return NumItems == 0; }
122 unsigned size() const { return NumItems; }
125 /// StringMapEntry - This is used to represent one value that is inserted into
126 /// a StringMap. It contains the Value itself and the key: the string length
128 template<typename ValueTy>
129 class StringMapEntry : public StringMapEntryBase {
133 explicit StringMapEntry(unsigned StrLen)
134 : StringMapEntryBase(StrLen), second() {}
135 StringMapEntry(unsigned StrLen, const ValueTy &V)
136 : StringMapEntryBase(StrLen), second(V) {}
138 const ValueTy &getValue() const { return second; }
139 ValueTy &getValue() { return second; }
141 void setValue(const ValueTy &V) { second = V; }
143 /// getKeyData - Return the start of the string data that is the key for this
144 /// value. The string data is always stored immediately after the
145 /// StringMapEntry object.
146 const char *getKeyData() const {return reinterpret_cast<const char*>(this+1);}
148 const char *first() const { return getKeyData(); }
150 /// Create - Create a StringMapEntry for the specified key and default
151 /// construct the value.
152 template<typename AllocatorTy, typename InitType>
153 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
154 AllocatorTy &Allocator,
156 unsigned KeyLength = KeyEnd-KeyStart;
158 // Okay, the item doesn't already exist, and 'Bucket' is the bucket to fill
159 // in. Allocate a new item with space for the string at the end and a null
162 unsigned AllocSize = sizeof(StringMapEntry)+KeyLength+1;
163 unsigned Alignment = alignof<StringMapEntry>();
165 StringMapEntry *NewItem =
166 static_cast<StringMapEntry*>(Allocator.Allocate(AllocSize,Alignment));
168 // Default construct the value.
169 new (NewItem) StringMapEntry(KeyLength);
171 // Copy the string information.
172 char *StrBuffer = const_cast<char*>(NewItem->getKeyData());
173 memcpy(StrBuffer, KeyStart, KeyLength);
174 StrBuffer[KeyLength] = 0; // Null terminate for convenience of clients.
176 // Initialize the value if the client wants to.
177 StringMapEntryInitializer<ValueTy>::Initialize(*NewItem, InitVal);
181 template<typename AllocatorTy>
182 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
183 AllocatorTy &Allocator) {
184 return Create(KeyStart, KeyEnd, Allocator, (void*)0);
188 /// Create - Create a StringMapEntry with normal malloc/free.
189 template<typename InitType>
190 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
193 return Create(KeyStart, KeyEnd, A, InitVal);
196 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd) {
197 return Create(KeyStart, KeyEnd, (void*)0);
200 /// GetStringMapEntryFromValue - Given a value that is known to be embedded
201 /// into a StringMapEntry, return the StringMapEntry itself.
202 static StringMapEntry &GetStringMapEntryFromValue(ValueTy &V) {
203 StringMapEntry *EPtr = 0;
204 char *Ptr = reinterpret_cast<char*>(&V) -
205 (reinterpret_cast<char*>(&EPtr->second) -
206 reinterpret_cast<char*>(EPtr));
207 return *reinterpret_cast<StringMapEntry*>(Ptr);
209 static const StringMapEntry &GetStringMapEntryFromValue(const ValueTy &V) {
210 return GetStringMapEntryFromValue(const_cast<ValueTy&>(V));
213 /// Destroy - Destroy this StringMapEntry, releasing memory back to the
214 /// specified allocator.
215 template<typename AllocatorTy>
216 void Destroy(AllocatorTy &Allocator) {
217 // Free memory referenced by the item.
218 this->~StringMapEntry();
219 Allocator.Deallocate(this);
222 /// Destroy this object, releasing memory back to the malloc allocator.
230 /// StringMap - This is an unconventional map that is specialized for handling
231 /// keys that are "strings", which are basically ranges of bytes. This does some
232 /// funky memory allocation and hashing things to make it extremely efficient,
233 /// storing the string data *after* the value in the map.
234 template<typename ValueTy, typename AllocatorTy = MallocAllocator>
235 class StringMap : public StringMapImpl {
236 AllocatorTy Allocator;
237 typedef StringMapEntry<ValueTy> MapEntryTy;
239 StringMap() : StringMapImpl(sizeof(MapEntryTy)) {}
240 explicit StringMap(unsigned InitialSize)
241 : StringMapImpl(InitialSize, sizeof(MapEntryTy)) {}
243 AllocatorTy &getAllocator() { return Allocator; }
244 const AllocatorTy &getAllocator() const { return Allocator; }
246 typedef const char* key_type;
247 typedef ValueTy mapped_type;
248 typedef StringMapEntry<ValueTy> value_type;
249 typedef size_t size_type;
251 typedef StringMapConstIterator<ValueTy> const_iterator;
252 typedef StringMapIterator<ValueTy> iterator;
255 return iterator(TheTable, NumBuckets == 0);
258 return iterator(TheTable+NumBuckets, true);
260 const_iterator begin() const {
261 return const_iterator(TheTable, NumBuckets == 0);
263 const_iterator end() const {
264 return const_iterator(TheTable+NumBuckets, true);
267 iterator find(const char *KeyStart, const char *KeyEnd) {
268 int Bucket = FindKey(KeyStart, KeyEnd);
269 if (Bucket == -1) return end();
270 return iterator(TheTable+Bucket);
272 iterator find(const char *Key) {
273 return find(Key, Key + strlen(Key));
275 iterator find(const std::string &Key) {
276 const char* key_start = &Key[0];
277 return find(key_start, key_start + Key.size());
280 const_iterator find(const char *KeyStart, const char *KeyEnd) const {
281 int Bucket = FindKey(KeyStart, KeyEnd);
282 if (Bucket == -1) return end();
283 return const_iterator(TheTable+Bucket);
285 const_iterator find(const char *Key) const {
286 return find(Key, Key + strlen(Key));
288 const_iterator find(const std::string &Key) const {
289 const char* key_start = &Key[0];
290 return find(key_start, key_start + Key.size());
293 ValueTy& operator[](const char *Key) {
294 value_type& entry = GetOrCreateValue(Key, Key + strlen(Key));
295 return entry.getValue();
297 ValueTy& operator[](const std::string &Key) {
298 const char* key_start = &Key[0];
299 value_type& entry = GetOrCreateValue(key_start, key_start + Key.size());
300 return entry.getValue();
303 size_type count(const char *KeyStart, const char *KeyEnd) const {
304 return find(KeyStart, KeyEnd) == end() ? 0 : 1;
306 size_type count(const char *Key) const {
307 return count(Key, Key + strlen(Key));
309 size_type count(const std::string &Key) const {
310 const char* key_start = &Key[0];
311 return count(key_start, key_start + Key.size());
314 /// insert - Insert the specified key/value pair into the map. If the key
315 /// already exists in the map, return false and ignore the request, otherwise
316 /// insert it and return true.
317 bool insert(MapEntryTy *KeyValue) {
319 LookupBucketFor(KeyValue->getKeyData(),
320 KeyValue->getKeyData()+KeyValue->getKeyLength());
321 ItemBucket &Bucket = TheTable[BucketNo];
322 if (Bucket.Item && Bucket.Item != getTombstoneVal())
323 return false; // Already exists in map.
325 if (Bucket.Item == getTombstoneVal())
327 Bucket.Item = KeyValue;
335 /// GetOrCreateValue - Look up the specified key in the table. If a value
336 /// exists, return it. Otherwise, default construct a value, insert it, and
338 template <typename InitTy>
339 StringMapEntry<ValueTy> &GetOrCreateValue(const char *KeyStart,
342 unsigned BucketNo = LookupBucketFor(KeyStart, KeyEnd);
343 ItemBucket &Bucket = TheTable[BucketNo];
344 if (Bucket.Item && Bucket.Item != getTombstoneVal())
345 return *static_cast<MapEntryTy*>(Bucket.Item);
347 MapEntryTy *NewItem = MapEntryTy::Create(KeyStart, KeyEnd, Allocator, Val);
349 if (Bucket.Item == getTombstoneVal())
353 // Fill in the bucket for the hash table. The FullHashValue was already
354 // filled in by LookupBucketFor.
355 Bucket.Item = NewItem;
362 StringMapEntry<ValueTy> &GetOrCreateValue(const char *KeyStart,
363 const char *KeyEnd) {
364 return GetOrCreateValue(KeyStart, KeyEnd, (void*)0);
367 /// remove - Remove the specified key/value pair from the map, but do not
368 /// erase it. This aborts if the key is not in the map.
369 void remove(MapEntryTy *KeyValue) {
373 void erase(iterator I) {
376 V.Destroy(Allocator);
380 for (ItemBucket *I = TheTable, *E = TheTable+NumBuckets; I != E; ++I) {
381 if (I->Item && I->Item != getTombstoneVal())
382 static_cast<MapEntryTy*>(I->Item)->Destroy(Allocator);
387 StringMap(const StringMap &); // FIXME: Implement.
388 void operator=(const StringMap &); // FIXME: Implement.
392 template<typename ValueTy>
393 class StringMapConstIterator {
395 StringMapImpl::ItemBucket *Ptr;
397 explicit StringMapConstIterator(StringMapImpl::ItemBucket *Bucket,
398 bool NoAdvance = false)
400 if (!NoAdvance) AdvancePastEmptyBuckets();
403 const StringMapEntry<ValueTy> &operator*() const {
404 return *static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
406 const StringMapEntry<ValueTy> *operator->() const {
407 return static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
410 bool operator==(const StringMapConstIterator &RHS) const {
411 return Ptr == RHS.Ptr;
413 bool operator!=(const StringMapConstIterator &RHS) const {
414 return Ptr != RHS.Ptr;
417 inline StringMapConstIterator& operator++() { // Preincrement
419 AdvancePastEmptyBuckets();
422 StringMapConstIterator operator++(int) { // Postincrement
423 StringMapConstIterator tmp = *this; ++*this; return tmp;
427 void AdvancePastEmptyBuckets() {
428 while (Ptr->Item == 0 || Ptr->Item == StringMapImpl::getTombstoneVal())
433 template<typename ValueTy>
434 class StringMapIterator : public StringMapConstIterator<ValueTy> {
436 explicit StringMapIterator(StringMapImpl::ItemBucket *Bucket,
437 bool NoAdvance = false)
438 : StringMapConstIterator<ValueTy>(Bucket, NoAdvance) {
440 StringMapEntry<ValueTy> &operator*() const {
441 return *static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);
443 StringMapEntry<ValueTy> *operator->() const {
444 return static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);