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) {
42 /// StringMapEntryBase - Shared base class of StringMapEntry instances.
43 class StringMapEntryBase {
46 explicit StringMapEntryBase(unsigned Len) : StrLen(Len) {}
48 unsigned getKeyLength() const { return StrLen; }
51 /// StringMapImpl - This is the base class of StringMap that is shared among
52 /// all of its instantiations.
55 /// ItemBucket - The hash table consists of an array of these. If Item is
56 /// non-null, this is an extant entry, otherwise, it is a hole.
58 /// FullHashValue - This remembers the full hash value of the key for
60 unsigned FullHashValue;
62 /// Item - This is a pointer to the actual item object.
63 StringMapEntryBase *Item;
70 unsigned NumTombstones;
73 explicit StringMapImpl(unsigned itemSize) : ItemSize(itemSize) {
74 // Initialize the map with zero buckets to allocation.
80 StringMapImpl(unsigned InitSize, unsigned ItemSize);
83 /// ShouldRehash - Return true if the table should be rehashed after a new
84 /// element was recently inserted.
85 bool ShouldRehash() const {
86 // If the hash table is now more than 3/4 full, or if fewer than 1/8 of
87 // the buckets are empty (meaning that many are filled with tombstones),
89 return NumItems*4 > NumBuckets*3 ||
90 NumBuckets-(NumItems+NumTombstones) < NumBuckets/8;
93 /// LookupBucketFor - Look up the bucket that the specified string should end
94 /// up in. If it already exists as a key in the map, the Item pointer for the
95 /// specified bucket will be non-null. Otherwise, it will be null. In either
96 /// case, the FullHashValue field of the bucket will be set to the hash value
98 unsigned LookupBucketFor(const char *KeyStart, const char *KeyEnd);
100 /// FindKey - Look up the bucket that contains the specified key. If it exists
101 /// in the map, return the bucket number of the key. Otherwise return -1.
102 /// This does not modify the map.
103 int FindKey(const char *KeyStart, const char *KeyEnd) const;
105 /// RemoveKey - Remove the specified StringMapEntry from the table, but do not
106 /// delete it. This aborts if the value isn't in the table.
107 void RemoveKey(StringMapEntryBase *V);
109 /// RemoveKey - Remove the StringMapEntry for the specified key from the
110 /// table, returning it. If the key is not in the table, this returns null.
111 StringMapEntryBase *RemoveKey(const char *KeyStart, const char *KeyEnd);
113 void init(unsigned Size);
115 static StringMapEntryBase *getTombstoneVal() {
116 return (StringMapEntryBase*)-1;
119 unsigned getNumBuckets() const { return NumBuckets; }
120 unsigned getNumItems() const { return NumItems; }
122 bool empty() const { return NumItems == 0; }
123 unsigned size() const { return NumItems; }
126 /// StringMapEntry - This is used to represent one value that is inserted into
127 /// a StringMap. It contains the Value itself and the key: the string length
129 template<typename ValueTy>
130 class StringMapEntry : public StringMapEntryBase {
134 explicit StringMapEntry(unsigned strLen)
135 : StringMapEntryBase(strLen), second() {}
136 StringMapEntry(unsigned strLen, const ValueTy &V)
137 : StringMapEntryBase(strLen), second(V) {}
139 const ValueTy &getValue() const { return second; }
140 ValueTy &getValue() { return second; }
142 void setValue(const ValueTy &V) { second = V; }
144 /// getKeyData - Return the start of the string data that is the key for this
145 /// value. The string data is always stored immediately after the
146 /// StringMapEntry object.
147 const char *getKeyData() const {return reinterpret_cast<const char*>(this+1);}
149 const char *first() const { return getKeyData(); }
151 /// Create - Create a StringMapEntry for the specified key and default
152 /// construct the value.
153 template<typename AllocatorTy, typename InitType>
154 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
155 AllocatorTy &Allocator,
157 unsigned KeyLength = static_cast<unsigned>(KeyEnd-KeyStart);
159 // Okay, the item doesn't already exist, and 'Bucket' is the bucket to fill
160 // in. Allocate a new item with space for the string at the end and a null
163 unsigned AllocSize = static_cast<unsigned>(sizeof(StringMapEntry))+
165 unsigned Alignment = alignof<StringMapEntry>();
167 StringMapEntry *NewItem =
168 static_cast<StringMapEntry*>(Allocator.Allocate(AllocSize,Alignment));
170 // Default construct the value.
171 new (NewItem) StringMapEntry(KeyLength);
173 // Copy the string information.
174 char *StrBuffer = const_cast<char*>(NewItem->getKeyData());
175 memcpy(StrBuffer, KeyStart, KeyLength);
176 StrBuffer[KeyLength] = 0; // Null terminate for convenience of clients.
178 // Initialize the value if the client wants to.
179 StringMapEntryInitializer<ValueTy>::Initialize(*NewItem, InitVal);
183 template<typename AllocatorTy>
184 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
185 AllocatorTy &Allocator) {
186 return Create(KeyStart, KeyEnd, Allocator, 0);
190 /// Create - Create a StringMapEntry with normal malloc/free.
191 template<typename InitType>
192 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
195 return Create(KeyStart, KeyEnd, A, InitVal);
198 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd) {
199 return Create(KeyStart, KeyEnd, ValueTy());
202 /// GetStringMapEntryFromValue - Given a value that is known to be embedded
203 /// into a StringMapEntry, return the StringMapEntry itself.
204 static StringMapEntry &GetStringMapEntryFromValue(ValueTy &V) {
205 StringMapEntry *EPtr = 0;
206 char *Ptr = reinterpret_cast<char*>(&V) -
207 (reinterpret_cast<char*>(&EPtr->second) -
208 reinterpret_cast<char*>(EPtr));
209 return *reinterpret_cast<StringMapEntry*>(Ptr);
211 static const StringMapEntry &GetStringMapEntryFromValue(const ValueTy &V) {
212 return GetStringMapEntryFromValue(const_cast<ValueTy&>(V));
215 /// Destroy - Destroy this StringMapEntry, releasing memory back to the
216 /// specified allocator.
217 template<typename AllocatorTy>
218 void Destroy(AllocatorTy &Allocator) {
219 // Free memory referenced by the item.
220 this->~StringMapEntry();
221 Allocator.Deallocate(this);
224 /// Destroy this object, releasing memory back to the malloc allocator.
232 /// StringMap - This is an unconventional map that is specialized for handling
233 /// keys that are "strings", which are basically ranges of bytes. This does some
234 /// funky memory allocation and hashing things to make it extremely efficient,
235 /// storing the string data *after* the value in the map.
236 template<typename ValueTy, typename AllocatorTy = MallocAllocator>
237 class StringMap : public StringMapImpl {
238 AllocatorTy Allocator;
239 typedef StringMapEntry<ValueTy> MapEntryTy;
241 StringMap() : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))) {}
242 explicit StringMap(unsigned InitialSize)
243 : StringMapImpl(InitialSize, static_cast<unsigned>(sizeof(MapEntryTy))) {}
244 explicit StringMap(const StringMap &RHS)
245 : StringMapImpl(static_cast<unsigned>(sizeof(MapEntryTy))) {
246 assert(RHS.empty() &&
247 "Copy ctor from non-empty stringmap not implemented yet!");
249 void operator=(const StringMap &RHS) {
250 assert(RHS.empty() &&
251 "assignment from non-empty stringmap not implemented yet!");
256 AllocatorTy &getAllocator() { return Allocator; }
257 const AllocatorTy &getAllocator() const { return Allocator; }
259 typedef const char* key_type;
260 typedef ValueTy mapped_type;
261 typedef StringMapEntry<ValueTy> value_type;
262 typedef size_t size_type;
264 typedef StringMapConstIterator<ValueTy> const_iterator;
265 typedef StringMapIterator<ValueTy> iterator;
268 return iterator(TheTable, NumBuckets == 0);
271 return iterator(TheTable+NumBuckets, true);
273 const_iterator begin() const {
274 return const_iterator(TheTable, NumBuckets == 0);
276 const_iterator end() const {
277 return const_iterator(TheTable+NumBuckets, true);
280 iterator find(const char *KeyStart, const char *KeyEnd) {
281 int Bucket = FindKey(KeyStart, KeyEnd);
282 if (Bucket == -1) return end();
283 return iterator(TheTable+Bucket);
285 iterator find(const char *Key) {
286 return find(Key, Key + strlen(Key));
288 iterator find(const std::string &Key) {
289 return find(Key.data(), Key.data() + Key.size());
292 const_iterator find(const char *KeyStart, const char *KeyEnd) const {
293 int Bucket = FindKey(KeyStart, KeyEnd);
294 if (Bucket == -1) return end();
295 return const_iterator(TheTable+Bucket);
297 const_iterator find(const char *Key) const {
298 return find(Key, Key + strlen(Key));
300 const_iterator find(const std::string &Key) const {
301 return find(Key.data(), Key.data() + Key.size());
304 /// lookup - Return the entry for the specified key, or a default
305 /// constructed value if no such entry exists.
306 ValueTy lookup(const char *KeyStart, const char *KeyEnd) const {
307 const_iterator it = find(KeyStart, KeyEnd);
312 ValueTy lookup(const char *Key) const {
313 const_iterator it = find(Key);
318 ValueTy lookup(const std::string &Key) const {
319 const_iterator it = find(Key);
325 ValueTy& operator[](const char *Key) {
326 return GetOrCreateValue(Key, Key + strlen(Key)).getValue();
328 ValueTy& operator[](const std::string &Key) {
329 return GetOrCreateValue(Key.data(), Key.data() + Key.size()).getValue();
332 size_type count(const char *KeyStart, const char *KeyEnd) const {
333 return find(KeyStart, KeyEnd) == end() ? 0 : 1;
335 size_type count(const char *Key) const {
336 return count(Key, Key + strlen(Key));
338 size_type count(const std::string &Key) const {
339 return count(Key.data(), Key.data() + Key.size());
342 /// insert - Insert the specified key/value pair into the map. If the key
343 /// already exists in the map, return false and ignore the request, otherwise
344 /// insert it and return true.
345 bool insert(MapEntryTy *KeyValue) {
347 LookupBucketFor(KeyValue->getKeyData(),
348 KeyValue->getKeyData()+KeyValue->getKeyLength());
349 ItemBucket &Bucket = TheTable[BucketNo];
350 if (Bucket.Item && Bucket.Item != getTombstoneVal())
351 return false; // Already exists in map.
353 if (Bucket.Item == getTombstoneVal())
355 Bucket.Item = KeyValue;
363 // clear - Empties out the StringMap
367 // Zap all values, resetting the keys back to non-present (not tombstone),
368 // which is safe because we're removing all elements.
369 for (ItemBucket *I = TheTable, *E = TheTable+NumBuckets; I != E; ++I) {
370 if (I->Item && I->Item != getTombstoneVal()) {
371 static_cast<MapEntryTy*>(I->Item)->Destroy(Allocator);
379 /// GetOrCreateValue - Look up the specified key in the table. If a value
380 /// exists, return it. Otherwise, default construct a value, insert it, and
382 template <typename InitTy>
383 StringMapEntry<ValueTy> &GetOrCreateValue(const char *KeyStart,
386 unsigned BucketNo = LookupBucketFor(KeyStart, KeyEnd);
387 ItemBucket &Bucket = TheTable[BucketNo];
388 if (Bucket.Item && Bucket.Item != getTombstoneVal())
389 return *static_cast<MapEntryTy*>(Bucket.Item);
391 MapEntryTy *NewItem = MapEntryTy::Create(KeyStart, KeyEnd, Allocator, Val);
393 if (Bucket.Item == getTombstoneVal())
397 // Fill in the bucket for the hash table. The FullHashValue was already
398 // filled in by LookupBucketFor.
399 Bucket.Item = NewItem;
406 StringMapEntry<ValueTy> &GetOrCreateValue(const char *KeyStart,
407 const char *KeyEnd) {
408 return GetOrCreateValue(KeyStart, KeyEnd, ValueTy());
411 /// remove - Remove the specified key/value pair from the map, but do not
412 /// erase it. This aborts if the key is not in the map.
413 void remove(MapEntryTy *KeyValue) {
417 void erase(iterator I) {
420 V.Destroy(Allocator);
423 bool erase(const char *Key) {
424 iterator I = find(Key);
425 if (I == end()) return false;
430 bool erase(const std::string &Key) {
431 iterator I = find(Key);
432 if (I == end()) return false;
444 template<typename ValueTy>
445 class StringMapConstIterator {
447 StringMapImpl::ItemBucket *Ptr;
449 typedef StringMapEntry<ValueTy> value_type;
451 explicit StringMapConstIterator(StringMapImpl::ItemBucket *Bucket,
452 bool NoAdvance = false)
454 if (!NoAdvance) AdvancePastEmptyBuckets();
457 const value_type &operator*() const {
458 return *static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
460 const value_type *operator->() const {
461 return static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
464 bool operator==(const StringMapConstIterator &RHS) const {
465 return Ptr == RHS.Ptr;
467 bool operator!=(const StringMapConstIterator &RHS) const {
468 return Ptr != RHS.Ptr;
471 inline StringMapConstIterator& operator++() { // Preincrement
473 AdvancePastEmptyBuckets();
476 StringMapConstIterator operator++(int) { // Postincrement
477 StringMapConstIterator tmp = *this; ++*this; return tmp;
481 void AdvancePastEmptyBuckets() {
482 while (Ptr->Item == 0 || Ptr->Item == StringMapImpl::getTombstoneVal())
487 template<typename ValueTy>
488 class StringMapIterator : public StringMapConstIterator<ValueTy> {
490 explicit StringMapIterator(StringMapImpl::ItemBucket *Bucket,
491 bool NoAdvance = false)
492 : StringMapConstIterator<ValueTy>(Bucket, NoAdvance) {
494 StringMapEntry<ValueTy> &operator*() const {
495 return *static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);
497 StringMapEntry<ValueTy> *operator->() const {
498 return static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);