Permalink
Browse files

Fixed If GetHashCode is negative

  • Loading branch information...
1 parent bdb5940 commit e6da90417ca665c14cafd7d1d21b3489ea23130b Sam Listopad committed Apr 19, 2012
Showing with 19 additions and 12 deletions.
  1. +19 −12 src/DotLiquid/Util/WeakTable.cs
@@ -31,29 +31,36 @@ public WeakTable(int size)
}
set
{
- int i = key.GetHashCode() % _buckets.Length;
- _buckets[i].Key = key;
+ int i = (int)((uint)key.GetHashCode() % (uint)_buckets.Length);
+ _buckets[i].Key = key;
_buckets[i].Value = new WeakReference(value);
}
}
public bool TryGetValue(TKey key, out TValue value)
{
- int i = key.GetHashCode() % _buckets.Length;
- WeakReference wr;
- if ((wr = _buckets[i].Value) == null || !_buckets[i].Key.Equals(key))
- {
- value = null;
- return false;
- }
- value = (TValue) wr.Target;
+ WeakReference wr;
+ try
+ {
+ int i = (int)((uint)key.GetHashCode() % (uint)_buckets.Length);
+ if ((wr = _buckets[i].Value) == null || !_buckets[i].Key.Equals(key))
+ {
+ value = null;
+ return false;
+ }
+ value = (TValue)wr.Target;
+ }
+ catch (IndexOutOfRangeException ex)
+ {
+ throw new IndexOutOfRangeException("Index Out Of Range, key was " + key.ToString() + ", hashcode was " + key.GetHashCode().ToString(), ex);
+ }
return wr.IsAlive;
}
public void Remove(TKey key)
{
- int i = key.GetHashCode() % _buckets.Length;
- if (_buckets[i].Key.Equals(key))
+ int i = (int)((uint)key.GetHashCode() % (uint)_buckets.Length);
+ if (_buckets[i].Key.Equals(key))
_buckets[i].Value = null;
}
}

0 comments on commit e6da904

Please sign in to comment.