Переглянути джерело

[System.Core] Don't auto increment when trimming hashset. Fixes #18687

Marek Safar 11 роки тому
батько
коміт
633db36bd3

+ 4 - 4
mcs/class/System.Core/System.Collections.Generic/HashSet.cs

@@ -199,9 +199,9 @@ namespace System.Collections.Generic {
 			}
 		}
 
-		void Resize ()
+		void Resize (int size)
 		{
-			int newSize = HashPrimeNumbers.ToPrime ((table.Length << 1) | 1);
+			int newSize = HashPrimeNumbers.ToPrime (size);
 
 			// allocate new hash table and link slots array
 			var newTable = new int [newSize];
@@ -250,7 +250,7 @@ namespace System.Collections.Generic {
 				return false;
 
 			if (++count > threshold) {
-				Resize ();
+				Resize ((table.Length << 1) | 1);
 				index = (hashCode & int.MaxValue) % table.Length;
 			}
 
@@ -371,7 +371,7 @@ namespace System.Collections.Generic {
 
 		public void TrimExcess ()
 		{
-			Resize ();
+			Resize (count);
 		}
 
 		// set operations

+ 16 - 0
mcs/class/System.Core/Test/System.Collections.Generic/HashSetTest.cs

@@ -554,5 +554,21 @@ namespace MonoTests.System.Collections.Generic {
 				throw new ArgumentNullException ();  // Important aspect for test (same as what StringComparer.Ordinal does, and different from GenericEqualityComparer<string>)
 			}
 		}
+
+		[Test]
+		public void TrimWithoutChange ()
+		{
+			var lookup = new HashSet<string> ();
+
+			for (int i = 0; i < 10000; i++) {
+				lookup.Add (i.ToString ());
+			}
+
+			lookup.Remove (3.ToString ());
+
+			for (int i = 0; i < 1000; i++) {
+				lookup.TrimExcess ();
+			}
+		}
 	}
 }