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"
21 template<typename ValueT>
22 class StringMapConstIterator;
23 template<typename ValueT>
24 class StringMapIterator;
25 template<typename ValueTy>
28 /// StringMapEntryInitializer - This datatype can be partially specialized for
29 /// various datatypes in a stringmap to allow them to be initialized when an
30 /// entry is default constructed for the map.
31 template<typename ValueTy>
32 class StringMapEntryInitializer {
34 template <typename InitTy>
35 static void Initialize(StringMapEntry<ValueTy> &T, InitTy InitVal) {
40 /// StringMapEntryBase - Shared base class of StringMapEntry instances.
41 class StringMapEntryBase {
44 explicit StringMapEntryBase(unsigned Len) : StrLen(Len) {}
46 unsigned getKeyLength() const { return StrLen; }
49 /// StringMapImpl - This is the base class of StringMap that is shared among
50 /// all of its instantiations.
53 /// ItemBucket - The hash table consists of an array of these. If Item is
54 /// non-null, this is an extant entry, otherwise, it is a hole.
56 /// FullHashValue - This remembers the full hash value of the key for
58 unsigned FullHashValue;
60 /// Item - This is a pointer to the actual item object.
61 StringMapEntryBase *Item;
68 unsigned NumTombstones;
71 explicit StringMapImpl(unsigned itemSize) : ItemSize(itemSize) {
72 // Initialize the map with zero buckets to allocation.
78 StringMapImpl(unsigned InitSize, unsigned ItemSize);
81 /// ShouldRehash - Return true if the table should be rehashed after a new
82 /// element was recently inserted.
83 bool ShouldRehash() const {
84 // If the hash table is now more than 3/4 full, or if fewer than 1/8 of
85 // the buckets are empty (meaning that many are filled with tombstones),
87 return NumItems*4 > NumBuckets*3 ||
88 NumBuckets-(NumItems+NumTombstones) < NumBuckets/8;
91 /// LookupBucketFor - Look up the bucket that the specified string should end
92 /// up in. If it already exists as a key in the map, the Item pointer for the
93 /// specified bucket will be non-null. Otherwise, it will be null. In either
94 /// case, the FullHashValue field of the bucket will be set to the hash value
96 unsigned LookupBucketFor(const char *KeyStart, const char *KeyEnd);
98 /// FindKey - Look up the bucket that contains the specified key. If it exists
99 /// in the map, return the bucket number of the key. Otherwise return -1.
100 /// This does not modify the map.
101 int FindKey(const char *KeyStart, const char *KeyEnd) const;
103 /// RemoveKey - Remove the specified StringMapEntry from the table, but do not
104 /// delete it. This aborts if the value isn't in the table.
105 void RemoveKey(StringMapEntryBase *V);
107 /// RemoveKey - Remove the StringMapEntry for the specified key from the
108 /// table, returning it. If the key is not in the table, this returns null.
109 StringMapEntryBase *RemoveKey(const char *KeyStart, const char *KeyEnd);
111 void init(unsigned Size);
113 static StringMapEntryBase *getTombstoneVal() {
114 return (StringMapEntryBase*)-1;
117 unsigned getNumBuckets() const { return NumBuckets; }
118 unsigned getNumItems() const { return NumItems; }
120 bool empty() const { return NumItems == 0; }
121 unsigned size() const { return NumItems; }
124 /// StringMapEntry - This is used to represent one value that is inserted into
125 /// a StringMap. It contains the Value itself and the key: the string length
127 template<typename ValueTy>
128 class StringMapEntry : public StringMapEntryBase {
132 explicit StringMapEntry(unsigned StrLen)
133 : StringMapEntryBase(StrLen), second() {}
134 StringMapEntry(unsigned StrLen, const ValueTy &V)
135 : StringMapEntryBase(StrLen), second(V) {}
137 const ValueTy &getValue() const { return second; }
138 ValueTy &getValue() { return second; }
140 void setValue(const ValueTy &V) { second = V; }
142 /// getKeyData - Return the start of the string data that is the key for this
143 /// value. The string data is always stored immediately after the
144 /// StringMapEntry object.
145 const char *getKeyData() const {return reinterpret_cast<const char*>(this+1);}
147 const char *first() const { return getKeyData(); }
149 /// Create - Create a StringMapEntry for the specified key and default
150 /// construct the value.
151 template<typename AllocatorTy, typename InitType>
152 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
153 AllocatorTy &Allocator,
155 unsigned KeyLength = KeyEnd-KeyStart;
157 // Okay, the item doesn't already exist, and 'Bucket' is the bucket to fill
158 // in. Allocate a new item with space for the string at the end and a null
161 unsigned AllocSize = sizeof(StringMapEntry)+KeyLength+1;
162 unsigned Alignment = alignof<StringMapEntry>();
164 StringMapEntry *NewItem =
165 static_cast<StringMapEntry*>(Allocator.Allocate(AllocSize,Alignment));
167 // Default construct the value.
168 new (NewItem) StringMapEntry(KeyLength);
170 // Copy the string information.
171 char *StrBuffer = const_cast<char*>(NewItem->getKeyData());
172 memcpy(StrBuffer, KeyStart, KeyLength);
173 StrBuffer[KeyLength] = 0; // Null terminate for convenience of clients.
175 // Initialize the value if the client wants to.
176 StringMapEntryInitializer<ValueTy>::Initialize(*NewItem, InitVal);
180 template<typename AllocatorTy>
181 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
182 AllocatorTy &Allocator) {
183 return Create(KeyStart, KeyEnd, Allocator, (void*)0);
187 /// Create - Create a StringMapEntry with normal malloc/free.
188 template<typename InitType>
189 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd,
192 return Create(KeyStart, KeyEnd, A, InitVal);
195 static StringMapEntry *Create(const char *KeyStart, const char *KeyEnd) {
196 return Create(KeyStart, KeyEnd, (void*)0);
199 /// GetStringMapEntryFromValue - Given a value that is known to be embedded
200 /// into a StringMapEntry, return the StringMapEntry itself.
201 static StringMapEntry &GetStringMapEntryFromValue(ValueTy &V) {
202 StringMapEntry *EPtr = 0;
203 char *Ptr = reinterpret_cast<char*>(&V) -
204 (reinterpret_cast<char*>(&EPtr->Val) -
205 reinterpret_cast<char*>(EPtr));
206 return *reinterpret_cast<StringMapEntry*>(Ptr);
208 static const StringMapEntry &GetStringMapEntryFromValue(const ValueTy &V) {
209 return GetStringMapEntryFromValue(const_cast<ValueTy&>(V));
212 /// Destroy - Destroy this StringMapEntry, releasing memory back to the
213 /// specified allocator.
214 template<typename AllocatorTy>
215 void Destroy(AllocatorTy &Allocator) {
216 // Free memory referenced by the item.
217 this->~StringMapEntry();
218 Allocator.Deallocate(this);
221 /// Destroy this object, releasing memory back to the malloc allocator.
229 /// StringMap - This is an unconventional map that is specialized for handling
230 /// keys that are "strings", which are basically ranges of bytes. This does some
231 /// funky memory allocation and hashing things to make it extremely efficient,
232 /// storing the string data *after* the value in the map.
233 template<typename ValueTy, typename AllocatorTy = MallocAllocator>
234 class StringMap : public StringMapImpl {
235 AllocatorTy Allocator;
236 typedef StringMapEntry<ValueTy> MapEntryTy;
238 StringMap() : StringMapImpl(sizeof(MapEntryTy)) {}
239 explicit StringMap(unsigned InitialSize)
240 : StringMapImpl(InitialSize, sizeof(MapEntryTy)) {}
242 AllocatorTy &getAllocator() { return Allocator; }
243 const AllocatorTy &getAllocator() const { return Allocator; }
245 typedef const char* key_type;
246 typedef ValueTy mapped_type;
247 typedef StringMapEntry<ValueTy> value_type;
248 typedef size_t size_type;
250 typedef StringMapConstIterator<ValueTy> const_iterator;
251 typedef StringMapIterator<ValueTy> iterator;
254 return iterator(TheTable, NumBuckets == 0);
257 return iterator(TheTable+NumBuckets, true);
259 const_iterator begin() const {
260 return const_iterator(TheTable, NumBuckets == 0);
262 const_iterator end() const {
263 return const_iterator(TheTable+NumBuckets, true);
266 iterator find(const char *KeyStart, const char *KeyEnd) {
267 int Bucket = FindKey(KeyStart, KeyEnd);
268 if (Bucket == -1) return end();
269 return iterator(TheTable+Bucket);
272 const_iterator find(const char *KeyStart, const char *KeyEnd) const {
273 int Bucket = FindKey(KeyStart, KeyEnd);
274 if (Bucket == -1) return end();
275 return const_iterator(TheTable+Bucket);
278 iterator find(const char *Key) {
279 return find(Key, Key + strlen(Key));
281 const_iterator find(const char *Key) const {
282 return find(Key, Key + strlen(Key));
285 ValueTy& operator[](const char *Key) {
286 value_type& entry = GetOrCreateValue(Key, Key + strlen(Key));
287 return entry.getValue();
290 size_type count(const char *KeyStart, const char *KeyEnd) const {
291 return find(KeyStart, KeyEnd) == end() ? 0 : 1;
293 size_type count(const char *Key) const {
294 return count(Key, Key + strlen(Key));
297 /// insert - Insert the specified key/value pair into the map. If the key
298 /// already exists in the map, return false and ignore the request, otherwise
299 /// insert it and return true.
300 bool insert(MapEntryTy *KeyValue) {
302 LookupBucketFor(KeyValue->getKeyData(),
303 KeyValue->getKeyData()+KeyValue->getKeyLength());
304 ItemBucket &Bucket = TheTable[BucketNo];
305 if (Bucket.Item && Bucket.Item != getTombstoneVal())
306 return false; // Already exists in map.
308 if (Bucket.Item == getTombstoneVal())
310 Bucket.Item = KeyValue;
318 /// GetOrCreateValue - Look up the specified key in the table. If a value
319 /// exists, return it. Otherwise, default construct a value, insert it, and
321 template <typename InitTy>
322 StringMapEntry<ValueTy> &GetOrCreateValue(const char *KeyStart,
325 unsigned BucketNo = LookupBucketFor(KeyStart, KeyEnd);
326 ItemBucket &Bucket = TheTable[BucketNo];
327 if (Bucket.Item && Bucket.Item != getTombstoneVal())
328 return *static_cast<MapEntryTy*>(Bucket.Item);
330 MapEntryTy *NewItem = MapEntryTy::Create(KeyStart, KeyEnd, Allocator, Val);
332 if (Bucket.Item == getTombstoneVal())
336 // Fill in the bucket for the hash table. The FullHashValue was already
337 // filled in by LookupBucketFor.
338 Bucket.Item = NewItem;
345 StringMapEntry<ValueTy> &GetOrCreateValue(const char *KeyStart,
346 const char *KeyEnd) {
347 return GetOrCreateValue(KeyStart, KeyEnd, (void*)0);
350 /// remove - Remove the specified key/value pair from the map, but do not
351 /// erase it. This aborts if the key is not in the map.
352 void remove(MapEntryTy *KeyValue) {
356 void erase(iterator I) {
359 V.Destroy(Allocator);
363 for (ItemBucket *I = TheTable, *E = TheTable+NumBuckets; I != E; ++I) {
364 if (I->Item && I->Item != getTombstoneVal())
365 static_cast<MapEntryTy*>(I->Item)->Destroy(Allocator);
370 StringMap(const StringMap &); // FIXME: Implement.
371 void operator=(const StringMap &); // FIXME: Implement.
375 template<typename ValueTy>
376 class StringMapConstIterator {
378 StringMapImpl::ItemBucket *Ptr;
380 explicit StringMapConstIterator(StringMapImpl::ItemBucket *Bucket,
381 bool NoAdvance = false)
383 if (!NoAdvance) AdvancePastEmptyBuckets();
386 const StringMapEntry<ValueTy> &operator*() const {
387 return *static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
389 const StringMapEntry<ValueTy> *operator->() const {
390 return static_cast<StringMapEntry<ValueTy>*>(Ptr->Item);
393 bool operator==(const StringMapConstIterator &RHS) const {
394 return Ptr == RHS.Ptr;
396 bool operator!=(const StringMapConstIterator &RHS) const {
397 return Ptr != RHS.Ptr;
400 inline StringMapConstIterator& operator++() { // Preincrement
402 AdvancePastEmptyBuckets();
405 StringMapConstIterator operator++(int) { // Postincrement
406 StringMapConstIterator tmp = *this; ++*this; return tmp;
410 void AdvancePastEmptyBuckets() {
411 while (Ptr->Item == 0 || Ptr->Item == StringMapImpl::getTombstoneVal())
416 template<typename ValueTy>
417 class StringMapIterator : public StringMapConstIterator<ValueTy> {
419 explicit StringMapIterator(StringMapImpl::ItemBucket *Bucket,
420 bool NoAdvance = false)
421 : StringMapConstIterator<ValueTy>(Bucket, NoAdvance) {
423 StringMapEntry<ValueTy> &operator*() const {
424 return *static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);
426 StringMapEntry<ValueTy> *operator->() const {
427 return static_cast<StringMapEntry<ValueTy>*>(this->Ptr->Item);