Paradox Game Engine  v1.0.0 beta06
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Events Macros Pages
ArrayExtensions.cs
Go to the documentation of this file.
1 // Copyright (c) 2014 Silicon Studio Corp. (http://siliconstudio.co.jp)
2 // This file is distributed under GPL v3. See LICENSE.md for details.
3 using System;
4 using System.Collections.Generic;
5 using System.Linq;
6 
7 namespace SiliconStudio.Core.Extensions
8 {
9  public static class ArrayExtensions
10  {
11  // TODO: Merge this file with CollectionExtensions.cs
12 
13  // This is not really an extension method, maybe it should go somewhere else.
14  public static bool ArraysEqual<T>(IList<T> a1, IList<T> a2, IEqualityComparer<T> comparer = null)
15  {
16  if (ReferenceEquals(a1, a2))
17  return true;
18 
19  if (a1 == null || a2 == null)
20  return false;
21 
22  if (a1.Count != a2.Count)
23  return false;
24 
25  if (comparer == null)
26  comparer = EqualityComparer<T>.Default;
27  for (int i = 0; i < a1.Count; i++)
28  {
29  if (!comparer.Equals(a1[i], a2[i]))
30  return false;
31  }
32 
33  return true;
34  }
35 
36  public static int ComputeHash<T>(this ICollection<T> data, IEqualityComparer<T> comparer = null)
37  {
38  unchecked
39  {
40  if (data == null)
41  return 0;
42 
43  if (comparer == null)
44  comparer = EqualityComparer<T>.Default;
45 
46  int hash = 17 + data.Count;
47  int result = hash;
48  foreach (T unknown in data)
49  result = result*31 + comparer.GetHashCode(unknown);
50  return result;
51  }
52  }
53 
54  public static int ComputeHash<T>(this T[] data, IEqualityComparer<T> comparer = null)
55  {
56  unchecked
57  {
58  if (data == null)
59  return 0;
60 
61  if (comparer == null)
62  comparer = EqualityComparer<T>.Default;
63 
64  int hash = 17 + data.Length;
65  int result = hash;
66  foreach (T unknown in data)
67  result = result * 31 + comparer.GetHashCode(unknown);
68  return result;
69  }
70  }
71 
72  public static T[] SubArray<T>(this T[] data, int index, int length)
73  {
74  var result = new T[length];
75  Array.Copy(data, index, result, 0, length);
76  return result;
77  }
78 
79  public static T[] Concat<T>(this T[] array1, T[] array2)
80  {
81  var result = new T[array1.Length + array2.Length];
82 
83  array1.CopyTo(result, 0);
84  array2.CopyTo(result, array1.Length);
85 
86  return result;
87  }
88  }
89 }