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 const char* key_start = (Key.empty() ? NULL : &Key[0]);
290 return find(key_start, key_start + Key.size());
293 const_iterator find(const char *KeyStart, const char *KeyEnd) const {
294 int Bucket = FindKey(KeyStart, KeyEnd);
295 if (Bucket == -1) return end();
296 return const_iterator(TheTable+Bucket);
298 const_iterator find(const char *Key) const {
299 return find(Key, Key + strlen(Key));
301 const_iterator find(const std::string &Key) const {
302 const char* key_start = (Key.empty() ? NULL : &Key[0]);
303 return find(key_start, key_start + Key.size());
306 /// lookup - Return the entry for the specified key, or a default
307 /// constructed value if no such entry exists.
308 ValueTy lookup(const char *KeyStart, const char *KeyEnd) const {
309 const_iterator it = find(KeyStart, KeyEnd);
314 ValueTy lookup(const char *Key) const {
315 const_iterator it = find(Key);
320 ValueTy lookup(const std::string &Key) const {
321 const_iterator it = find(Key);
327 ValueTy& operator[](const char *Key) {
328 return GetOrCreateValue(Key, Key + strlen(Key)).getValue();
330 ValueTy& operator[](const std::string &Key) {
331 const char* key_start = (Key.empty() ? NULL : &Key[0]);
332 return GetOrCreateValue(key_start, key_start + Key.size()).getValue();
335 size_type count(const char *KeyStart, const char *KeyEnd) const {
336 return find(KeyStart, KeyEnd) == end() ? 0 : 1;
338 size_type count(const char *Key) const {
339 return count(Key, Key + strlen(Key));
341 size_type count(const std::string &Key) const {
342 const char* key_start = (Key.empty() ? NULL : &Key[0]);
343 return count(key_start, key_start + Key.size());
346 /// insert - Insert the specified key/value pair into the map. If the key
347 /// already exists in the map, return false and ignore the request, otherwise
348 /// insert it and return true.
349 bool insert(MapEntryTy *KeyValue) {
351 LookupBucketFor(KeyValue->getKeyData(),
352 KeyValue->getKeyData()+KeyValue->getKeyLength());
353 ItemBucket &Bucket = TheTable[BucketNo];
354 if (Bucket.Item && Bucket.Item != getTombstoneVal())
355 return false; // Already exists in map.
357 if (Bucket.Item == getTombstoneVal())
359 Bucket.Item = KeyValue;
367 // clear - Empties out the StringMap
371 // Zap all values, resetting the keys back to non-present (not tombstone),
372 // which is safe because we're removing all elements.
373 for (ItemBucket *I = TheTable, *E = TheTable+NumBuckets; I != E; ++I) {
374 if (I->Item && I->Item != getTombstoneVal()) {
375 static_cast<MapEntryTy*>(I->Item)->Destroy(Allocator);
383 /// GetOrCreateValue - Look up the specified key in the table. If a value
384 /// exists, return it. Otherwise, default construct a value, insert it, and
386 template <typename InitTy>
387 StringMapEntry<ValueTy> &GetOrCreateValue(const char *KeyStart,
390 unsigned BucketNo = LookupBucketFor(KeyStart, KeyEnd);
391 ItemBucket &Bucket = TheTable[BucketNo];
392 if (Bucket.Item && Bucket.Item != getTombstoneVal())
393 return *static_cast<MapEntryTy*>(Bucket.Item);
395 MapEntryTy *NewItem = MapEntryTy::Create(KeyStart, KeyEnd, Allocator, Val);
397 if (Bucket.Item == getTombstoneVal())
401 // Fill in the bucket for the hash table. The FullHashValue was already
402 // filled in by LookupBucketFor.
403 Bucket.Item = NewItem;
410 StringMapEntry<ValueTy> &GetOrCreateValue(const char *KeyStart,
411 const char *KeyEnd) {
412 return GetOrCreateValue(KeyStart, KeyEnd, ValueTy());
415 /// remove - Remove the specified key/value pair from the map, but do not
416 /// erase it. This aborts if the key is not in the map.
417 void remove(MapEntryTy *KeyValue) {
421 void erase(iterator I) {
424 V.Destroy(Allocator);
427 bool erase(const char *Key) {
428 iterator I = find(Key);
429 if (I == end()) return false;
434 bool erase(const std::string &Key) {
435 iterator I = find(Key);
436 if (I == end()) return false;
448 template<typename ValueTy>
449 class StringMapConstIterator {
451 StringMapImpl::ItemBucket *Ptr;
453 typedef StringMapEntry<ValueTy> value_type;
455 explicit StringMapConstIterator(StringMapImpl::ItemBucket *Bucket,
456 bool NoAdvance = false)
458 if (!NoAdvance) AdvancePastEmptyBuckets();
461 const value_type &operator*() const {
462 return *static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
464 const value_type *operator->() const {
465 return static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
468 bool operator==(const StringMapConstIterator &RHS) const {
469 return Ptr == RHS.Ptr;
471 bool operator!=(const StringMapConstIterator &RHS) const {
472 return Ptr != RHS.Ptr;
475 inline StringMapConstIterator& operator++() { // Preincrement
477 AdvancePastEmptyBuckets();
480 StringMapConstIterator operator++(int) { // Postincrement
481 StringMapConstIterator tmp = *this; ++*this; return tmp;
485 void AdvancePastEmptyBuckets() {
486 while (Ptr->Item == 0 || Ptr->Item == StringMapImpl::getTombstoneVal())
491 template<typename ValueTy>
492 class StringMapIterator : public StringMapConstIterator<ValueTy> {
494 explicit StringMapIterator(StringMapImpl::ItemBucket *Bucket,
495 bool NoAdvance = false)
496 : StringMapConstIterator<ValueTy>(Bucket, NoAdvance) {
498 StringMapEntry<ValueTy> &operator*() const {
499 return *static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);
501 StringMapEntry<ValueTy> *operator->() const {
502 return static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);