using System; using System.Collections; using System.Text; using System.Collections.Generic; using System.Threading; namespace MonoTorrent.Common { public delegate long Operation(T target); public static class Toolbox { private static Random r = new Random(); public static int Count(IEnumerable enumerable, Predicate predicate) { int count = 0; foreach (T t in enumerable) if (predicate(t)) count++; return count; } public static long Accumulate(IEnumerable enumerable, Operation action) { long count = 0; foreach (T t in enumerable) count += action(t); return count; } public static void RaiseAsyncEvent(EventHandler e, object o, T args) where T : EventArgs { if (e == null) return; ThreadPool.QueueUserWorkItem(delegate { if (e != null) e(o, args); }); } /// /// Randomizes the contents of the array /// /// /// public static void Randomize(List array) { List clone = new List(array); array.Clear(); while (clone.Count > 0) { int index = r.Next(0, clone.Count); array.Add(clone[index]); clone.RemoveAt(index); } } /// /// Switches the positions of two elements in an array /// /// /// /// /// public static void Switch(IList array, int first, int second) { T obj = array[first]; array[first] = array[second]; array[second] = obj; } /// /// Checks to see if the contents of two byte arrays are equal /// /// The first array /// The second array /// True if the arrays are equal, false if they aren't public static bool ByteMatch(byte[] array1, byte[] array2) { if (array1 == null) throw new ArgumentNullException("array1"); if (array2 == null) throw new ArgumentNullException("array2"); if (array1.Length != array2.Length) return false; return ByteMatch(array1, 0, array2, 0, array1.Length); } /// /// Checks to see if the contents of two byte arrays are equal /// /// The first array /// The second array /// The starting index for the first array /// The starting index for the second array /// The number of bytes to check /// public static bool ByteMatch(byte[] array1, int offset1, byte[] array2, int offset2, int count) { if (array1 == null) throw new ArgumentNullException("array1"); if (array2 == null) throw new ArgumentNullException("array2"); // If either of the arrays is too small, they're not equal if ((array1.Length - offset1) < count || (array2.Length - offset2) < count) return false; // Check if any elements are unequal for (int i = 0; i < count; i++) if (array1[offset1 + i] != array2[offset2 + i]) return false; return true; } } }