PageRenderTime 25ms CodeModel.GetById 11ms app.highlight 9ms RepoModel.GetById 1ms app.codeStats 0ms

/IronPython_Main/Runtime/Microsoft.Dynamic/Debugging/CollectionUtils.cs

#
C# | 70 lines | 45 code | 9 blank | 16 comment | 4 complexity | 21ef97a3ab13d277ccdb0ca2c08263cf MD5 | raw file
 1/* ****************************************************************************
 2 *
 3 * Copyright (c) Microsoft Corporation. 
 4 *
 5 * This source code is subject to terms and conditions of the Apache License, Version 2.0. A 
 6 * copy of the license can be found in the License.html file at the root of this distribution. If 
 7 * you cannot locate the  Apache License, Version 2.0, please send an email to 
 8 * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound 
 9 * by the terms of the Apache License, Version 2.0.
10 *
11 * You must not remove this notice, or any other, from this software.
12 *
13 *
14 * ***************************************************************************/
15
16using System;
17using System.Collections.Generic;
18using System.Text;
19
20namespace Microsoft.Scripting.Debugging {
21    internal static class CollectionUtils {
22        internal static T[] RemoveLast<T>(this T[] array) {
23            T[] result = new T[array.Length - 1];
24            Array.Copy(array, 0, result, 0, result.Length);
25            return result;
26        }
27
28        internal static bool ListEquals<T>(this ICollection<T> first, ICollection<T> second) {
29            if (first.Count != second.Count) {
30                return false;
31            }
32            var cmp = EqualityComparer<T>.Default;
33            var f = first.GetEnumerator();
34            var s = second.GetEnumerator();
35            while (f.MoveNext()) {
36                s.MoveNext();
37
38                if (!cmp.Equals(f.Current, s.Current)) {
39                    return false;
40                }
41            }
42            return true;
43        }
44
45        internal static int ListHashCode<T>(this IEnumerable<T> list) {
46            var cmp = EqualityComparer<T>.Default;
47            int h = 6551;
48            foreach (T t in list) {
49                h ^= (h << 5) ^ cmp.GetHashCode(t);
50            }
51            return h;
52        }
53    }
54
55    // Compares two ICollection<T>'s using element equality
56    internal sealed class ListEqualityComparer<T> : EqualityComparer<ICollection<T>> {
57        internal static readonly ListEqualityComparer<T> Instance = new ListEqualityComparer<T>();
58
59        private ListEqualityComparer() { }
60
61        // EqualityComparer<T> handles null and object identity for us
62        public override bool Equals(ICollection<T> x, ICollection<T> y) {
63            return x.ListEquals(y);
64        }
65
66        public override int GetHashCode(ICollection<T> obj) {
67            return obj.ListHashCode();
68        }
69    }
70}