[corlib] Fix Array.Sort throwing when fewer keys than items are provided
authorAlexander Köplinger <alex.koeplinger@outlook.com>
Mon, 9 Nov 2015 19:56:18 +0000 (20:56 +0100)
committerAlexander Köplinger <alex.koeplinger@outlook.com>
Tue, 10 Nov 2015 21:14:47 +0000 (22:14 +0100)
The `Sort<TKey, TValue> (TKey [] keys, TValue [] items, IComparer<TKey> comparer)` overload in Array throwed when keys.Length != items.Length.
However, on .NET you can pass in a keys array with fewer elements than in items and it'd sort the elements in items up to that point.

Fixed our implementation by only throwing when keys.Length > items.Length.

This was revealed by the coreclr/tests/src/CoreMangLib/cti/system/array/arraysort12.exe test.
I decided to port the test into our testsuite so we catch regressions earlier.

mcs/class/corlib/System/Array.cs
mcs/class/corlib/Test/System/ArrayTest.cs

index 024f3ff18f10a3ec19c4a4a211bb88adbd196964..32e873227de30ee98a4cafc752a52642ff3bdf31 100644 (file)
@@ -1689,10 +1689,10 @@ namespace System
                
                        if (keys == null)
                                throw new ArgumentNullException ("keys");
-                               
-                       if (keys.Length != items.Length)
-                               throw new ArgumentException ("Length of keys and items does not match.");
-                       
+
+                       if (keys.Length > items.Length)
+                               throw new ArgumentException ("Length of keys is larger than length of items.");
+
                        SortImpl<TKey, TValue> (keys, items, 0, keys.Length, comparer);
                }
 
index 6902f43be1e989a386ccaf9144a8dd7d1c881aa9..351d312c92d63c5d217d3f9df04524402671680b 100644 (file)
@@ -2548,6 +2548,33 @@ public class ArrayTest
                        Assert.AreEqual (4, indices [0]);
        }
 
+       [Test]
+       public void TestSortComparable()
+       {
+               int[] source = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
+               int[] expected = { 6, 5, 4, 3, 2, 1, 7, 8, 9 };
+               Comp[] c = { new Comp (100), new Comp (16), new Comp (11), new Comp (9), new Comp (0), new Comp (-100) };
+               IComparer<Comp> comp = null;
+               Array.Sort<Comp, int> (c, source, comp);
+
+               Assert.AreEqual (expected, source);
+       }
+
+       class Comp : IComparable
+       {
+               readonly int val;
+
+               public Comp (int a)
+               {
+                       val = a;
+               }
+
+               int IComparable.CompareTo (object obj)
+               {
+                       return val.CompareTo ((obj as Comp).val);
+               }
+       }
+
        [Test]
        public void TestInitializeEmpty()
        {