Advertisement
magnusbakken

Untitled

Nov 1st, 2013
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.92 KB | None | 0 0
  1. public class Dictionary<TKey, TValue>
  2. {
  3.     public TValue this[TKey key] {
  4.     get {
  5.         int i = FindEntry(key);
  6.         if (i >= 0) return entries[i].value;
  7.         ThrowHelper.ThrowKeyNotFoundException();
  8.         return default(TValue);
  9.     }
  10.     set {
  11.         Insert(key, value, false);
  12.     }
  13.     }
  14.  
  15.     public void Add(TKey key, TValue value) {
  16.     Insert(key, value, true);
  17.     }
  18.  
  19.     private void Insert(TKey key, TValue value, bool add) {
  20.  
  21.     if( key == null ) {
  22.         ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
  23.     }
  24.  
  25.     if (buckets == null) Initialize(0);
  26.     int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
  27.     int targetBucket = hashCode % buckets.Length;
  28.  
  29. #if FEATURE_RANDOMIZED_STRING_HASHING
  30.     int collisionCount = 0;
  31. #endif
  32.  
  33.     for (int i = buckets[targetBucket]; i >= 0; i = entries[i].next) {
  34.         if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) {
  35.         if (add) {
  36.             ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
  37.         }
  38.         entries[i].value = value;
  39.         version++;
  40.         return;
  41.         }
  42.  
  43. #if FEATURE_RANDOMIZED_STRING_HASHING
  44.         collisionCount++;
  45. #endif
  46.     }
  47.     int index;
  48.     if (freeCount > 0) {
  49.         index = freeList;
  50.         freeList = entries[index].next;
  51.         freeCount--;
  52.     }
  53.     else {
  54.         if (count == entries.Length)
  55.         {
  56.         Resize();
  57.         targetBucket = hashCode % buckets.Length;
  58.         }
  59.         index = count;
  60.         count++;
  61.     }
  62.  
  63.     entries[index].hashCode = hashCode;
  64.     entries[index].next = buckets[targetBucket];
  65.     entries[index].key = key;
  66.     entries[index].value = value;
  67.     buckets[targetBucket] = index;
  68.     version++;
  69.  
  70. #if FEATURE_RANDOMIZED_STRING_HASHING
  71.     if(collisionCount > HashHelpers.HashCollisionThreshold && HashHelpers.IsWellKnownEqualityComparer(comparer))
  72.     {
  73.         comparer = (IEqualityComparer<TKey>) HashHelpers.GetRandomizedEqualityComparer(comparer);
  74.         Resize(entries.Length, true);
  75.     }
  76. #endif
  77.  
  78.     }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement