/*
Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using C5;
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Diagnostics;
using SCG = System.Collections.Generic;
namespace C5
{
///
/// Utility class for building default generic equalityComparers.
///
///
public static class EqualityComparer
{
readonly static Type isequenced = typeof(ISequenced<>);
readonly static Type icollection = typeof(ICollection<>);
readonly static Type orderedcollectionequalityComparer = typeof(SequencedCollectionEqualityComparer<,>);
readonly static Type unorderedcollectionequalityComparer = typeof(UnsequencedCollectionEqualityComparer<,>);
readonly static Type equalityequalityComparer = typeof(EquatableEqualityComparer<>);
readonly static Type iequalitytype = typeof(IEquatable);
static SCG.IEqualityComparer cachedDefault = null;
//TODO: find the right word for initialized+invocation
///
/// A default generic equality comparer for type T. The procedure is as follows:
///
/// - If T is a primitive type (char, sbyte, byte, short, ushort, int, uint, float, double, decimal),
/// the equalityComparer will be a standard equalityComparer for that type
/// - If the actual generic argument T implements the generic interface
/// for some value W of its generic parameter T,
/// the equalityComparer will be
/// - If the actual generic argument T implements
/// for some value W of its generic parameter T,
/// the equalityComparer will be
/// - If T is a type implementing , the equalityComparer
/// will be
/// - If T is a type not implementing , the equalityComparer
/// will be
///
/// The object is constructed when this class is initialised, i.e.
/// its static constructors called. Thus, the property will be the same object
/// for the duration of an invocation of the runtime, but a value serialized in
/// another invocation and deserialized here will not be the same object.
///
///
public static SCG.IEqualityComparer Default
{
get
{
if (cachedDefault != null)
return cachedDefault;
Type t = typeof(T);
if (t.IsValueType)
{
if (t.Equals(typeof(char)))
return cachedDefault = (SCG.IEqualityComparer)(CharEqualityComparer.Default);
if (t.Equals(typeof(sbyte)))
return cachedDefault = (SCG.IEqualityComparer)(SByteEqualityComparer.Default);
if (t.Equals(typeof(byte)))
return cachedDefault = (SCG.IEqualityComparer)(ByteEqualityComparer.Default);
if (t.Equals(typeof(short)))
return cachedDefault = (SCG.IEqualityComparer)(ShortEqualityComparer.Default);
if (t.Equals(typeof(ushort)))
return cachedDefault = (SCG.IEqualityComparer)(UShortEqualityComparer.Default);
if (t.Equals(typeof(int)))
return cachedDefault = (SCG.IEqualityComparer)(IntEqualityComparer.Default);
if (t.Equals(typeof(uint)))
return cachedDefault = (SCG.IEqualityComparer)(UIntEqualityComparer.Default);
if (t.Equals(typeof(long)))
return cachedDefault = (SCG.IEqualityComparer)(LongEqualityComparer.Default);
if (t.Equals(typeof(ulong)))
return cachedDefault = (SCG.IEqualityComparer)(ULongEqualityComparer.Default);
if (t.Equals(typeof(float)))
return cachedDefault = (SCG.IEqualityComparer)(FloatEqualityComparer.Default);
if (t.Equals(typeof(double)))
return cachedDefault = (SCG.IEqualityComparer)(DoubleEqualityComparer.Default);
if (t.Equals(typeof(decimal)))
return cachedDefault = (SCG.IEqualityComparer)(DecimalEqualityComparer.Default);
}
Type[] interfaces = t.GetInterfaces();
if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(isequenced))
return createAndCache(orderedcollectionequalityComparer.MakeGenericType(new Type[] { t, t.GetGenericArguments()[0] }));
foreach (Type ty in interfaces)
{
if (ty.IsGenericType && ty.GetGenericTypeDefinition().Equals(isequenced))
return createAndCache(orderedcollectionequalityComparer.MakeGenericType(new Type[] { t, ty.GetGenericArguments()[0] }));
}
if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(icollection))
return createAndCache(unorderedcollectionequalityComparer.MakeGenericType(new Type[] { t, t.GetGenericArguments()[0] }));
foreach (Type ty in interfaces)
{
if (ty.IsGenericType && ty.GetGenericTypeDefinition().Equals(icollection))
return createAndCache(unorderedcollectionequalityComparer.MakeGenericType(new Type[] { t, ty.GetGenericArguments()[0] }));
}
if (iequalitytype.IsAssignableFrom(t))
return createAndCache(equalityequalityComparer.MakeGenericType(new Type[] { t }));
else
return cachedDefault = NaturalEqualityComparer.Default;
}
}
static SCG.IEqualityComparer createAndCache(Type equalityComparertype)
{
return cachedDefault = (SCG.IEqualityComparer)(equalityComparertype.GetProperty("Default", BindingFlags.Static | BindingFlags.Public).GetValue(null, null));
}
}
///
/// A default item equalityComparer calling through to
/// the GetHashCode and Equals methods inherited from System.Object.
///
[Serializable]
public sealed class NaturalEqualityComparer : SCG.IEqualityComparer
{
static NaturalEqualityComparer cached;
NaturalEqualityComparer() { }
///
///
///
///
public static NaturalEqualityComparer Default { get { return cached ?? (cached = new NaturalEqualityComparer()); } }
//TODO: check if null check is reasonable
//Answer: if we have struct C { T t; int i;} and implement GetHashCode as
//the sum of hashcodes, and T may be any type, we cannot make the null check
//inside the definition of C in a reasonable way.
///
/// Get the hash code with respect to this item equalityComparer
///
/// The item
/// The hash code
[Tested]
public int GetHashCode(T item) { return item == null ? 0 : item.GetHashCode(); }
///
/// Check if two items are equal with respect to this item equalityComparer
///
/// first item
/// second item
/// True if equal
[Tested]
public bool Equals(T item1, T item2)
{
return item1 == null ? item2 == null : item1.Equals(item2);
}
}
///
/// A default equality comparer for a type T that implements System.IEquatable.
///
/// The equality comparer forwards calls to GetHashCode and Equals to the IEquatable methods
/// on T, so Equals(T) is called, not Equals(object).
/// This will save boxing abd unboxing if T is a value type
/// and in general saves a runtime type check.
///
///
[Serializable]
public class EquatableEqualityComparer : SCG.IEqualityComparer where T : IEquatable
{
static EquatableEqualityComparer cached = new EquatableEqualityComparer();
EquatableEqualityComparer() { }
///
///
///
///
public static EquatableEqualityComparer Default {
get { return cached ?? (cached = new EquatableEqualityComparer()); }
}
///
///
///
///
///
public int GetHashCode(T item) { return item == null ? 0 : item.GetHashCode(); }
///
///
///
///
///
///
public bool Equals(T item1, T item2) { return item1 == null ? item2 == null : item1.Equals(item2); }
}
///
/// A equalityComparer for a reference type that uses reference equality for equality and the hash code from object as hash code.
///
/// The item type. Must be a reference type.
[Serializable]
public class ReferenceEqualityComparer : SCG.IEqualityComparer where T : class
{
static ReferenceEqualityComparer cached;
ReferenceEqualityComparer() { }
///
///
///
///
public static ReferenceEqualityComparer Default {
get { return cached ?? (cached = new ReferenceEqualityComparer()); }
}
///
///
///
///
///
public int GetHashCode(T item)
{
return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(item);
}
///
///
///
///
///
///
public bool Equals(T i1, T i2)
{
return object.ReferenceEquals(i1, i2);
}
}
///
/// An equalityComparer compatible with a given comparer. All hash codes are 0,
/// meaning that anything based on hash codes will be quite inefficient.
/// Note: this will give a new EqualityComparer each time created!
///
///
[Serializable]
public class ComparerZeroHashCodeEqualityComparer : SCG.IEqualityComparer
{
SCG.IComparer comparer;
///
/// Create a trivial compatible with the
/// comparer
///
///
public ComparerZeroHashCodeEqualityComparer(SCG.IComparer comparer)
{
if (comparer == null)
throw new NullReferenceException("Comparer cannot be null");
this.comparer = comparer;
}
///
/// A trivial, inefficient hash fuction. Compatible with any equality relation.
///
///
/// 0
public int GetHashCode(T item) { return 0; }
///
/// Equality of two items as defined by the comparer.
///
///
///
///
public bool Equals(T item1, T item2) { return comparer.Compare(item1, item2) == 0; }
}
///
/// Prototype for a sequenced equalityComparer for something (T) that implements ISequenced[W].
/// This will use ISequenced[W] specific implementations of the equality comparer operations.
///
///
///
[Serializable]
public class SequencedCollectionEqualityComparer : SCG.IEqualityComparer
where T : ISequenced
{
static SequencedCollectionEqualityComparer cached;
SequencedCollectionEqualityComparer() { }
///
///
///
///
public static SequencedCollectionEqualityComparer Default {
get { return cached ?? (cached = new SequencedCollectionEqualityComparer()); }
}
///
/// Get the hash code with respect to this sequenced equalityComparer
///
/// The collection
/// The hash code
[Tested]
public int GetHashCode(T collection) { return collection.GetSequencedHashCode(); }
///
/// Check if two items are equal with respect to this sequenced equalityComparer
///
/// first collection
/// second collection
/// True if equal
[Tested]
public bool Equals(T collection1, T collection2) { return collection1 == null ? collection2 == null : collection1.SequencedEquals(collection2); }
}
///
/// Prototype for an unsequenced equalityComparer for something (T) that implements ICollection[W]
/// This will use ICollection[W] specific implementations of the equalityComparer operations
///
///
///
[Serializable]
public class UnsequencedCollectionEqualityComparer : SCG.IEqualityComparer
where T : ICollection
{
static UnsequencedCollectionEqualityComparer cached;
UnsequencedCollectionEqualityComparer() { }
///
///
///
///
public static UnsequencedCollectionEqualityComparer Default { get { return cached ?? (cached = new UnsequencedCollectionEqualityComparer()); } }
///
/// Get the hash code with respect to this unsequenced equalityComparer
///
/// The collection
/// The hash code
[Tested]
public int GetHashCode(T collection) { return collection.GetUnsequencedHashCode(); }
///
/// Check if two collections are equal with respect to this unsequenced equalityComparer
///
/// first collection
/// second collection
/// True if equal
[Tested]
public bool Equals(T collection1, T collection2) { return collection1 == null ? collection2 == null : collection1.UnsequencedEquals(collection2); }
}
}
#if EXPERIMENTAL
namespace C5.EqualityComparerBuilder
{
///
/// IEqualityComparer factory class: examines at instatiation time if T is an
/// interface implementing "int GetHashCode()" and "bool Equals(T)".
/// If those are not present, MakeEqualityComparer will return a default equalityComparer,
/// else this class will implement IequalityComparer[T] via Invoke() on the
/// reflected method infos.
///
public class ByInvoke : SCG.IEqualityComparer
{
internal static readonly System.Reflection.MethodInfo hinfo, einfo;
static ByInvoke()
{
Type t = typeof(T);
if (!t.IsInterface) return;
BindingFlags f = BindingFlags.Public | BindingFlags.Instance;
hinfo = t.GetMethod("GetHashCode", f, null, new Type[0], null);
einfo = t.GetMethod("Equals", f, null, new Type[1] { t }, null);
}
private ByInvoke() { }
///
///
///
///
public static SCG.IEqualityComparer MakeEqualityComparer()
{
if (hinfo != null && einfo != null)
return new ByInvoke();
else
return NaturalEqualityComparer.Default;
}
///
///
///
///
///
public int GetHashCode(T item)
{
return (int)(hinfo.Invoke(item, null));
}
///
///
///
///
///
///
public bool Equals(T i1, T i2)
{
return (bool)(einfo.Invoke(i1, new object[1] { i2 }));
}
}
///
/// Like ByInvoke, but tries to build a equalityComparer by RTCG to
/// avoid the Invoke() overhead.
///
public class ByRTCG
{
private static ModuleBuilder moduleBuilder;
private static AssemblyBuilder assemblyBuilder;
///
///
///
///
///
///
public static SCG.IEqualityComparer CreateEqualityComparer(MethodInfo hinfo, MethodInfo einfo)
{
if (moduleBuilder == null)
{
string assmname = "LeFake";
string filename = assmname + ".dll";
AssemblyName assemblyName = new AssemblyName("LeFake");
AppDomain appdomain = AppDomain.CurrentDomain;
AssemblyBuilderAccess acc = AssemblyBuilderAccess.RunAndSave;
assemblyBuilder = appdomain.DefineDynamicAssembly(assemblyName, acc);
moduleBuilder = assemblyBuilder.DefineDynamicModule(assmname, filename);
}
Type t = typeof(T);
Type o_t = typeof(object);
Type h_t = typeof(SCG.IEqualityComparer);
Type i_t = typeof(int);
//TODO: protect uid for thread safety!
string name = "C5.Dynamic.EqualityComparer_" + Guid.NewGuid().ToString();
TypeAttributes tatt = TypeAttributes.Class | TypeAttributes.Public | TypeAttributes.Sealed;
TypeBuilder tb = moduleBuilder.DefineType(name, tatt, o_t, new Type[1] { h_t });
MethodAttributes matt = MethodAttributes.Public | MethodAttributes.Virtual;
MethodBuilder mb = tb.DefineMethod("GetHashCode", matt, i_t, new Type[1] { t });
ILGenerator ilg = mb.GetILGenerator();
ilg.Emit(OpCodes.Ldarg_1);
ilg.Emit(OpCodes.Callvirt, hinfo);
ilg.Emit(OpCodes.Ret);
mb = tb.DefineMethod("Equals", matt, typeof(bool), new Type[2] { t, t });
ilg = mb.GetILGenerator();
ilg.Emit(OpCodes.Ldarg_1);
ilg.Emit(OpCodes.Ldarg_2);
ilg.Emit(OpCodes.Callvirt, einfo);
ilg.Emit(OpCodes.Ret);
Type equalityComparer_t = tb.CreateType();
object equalityComparer = equalityComparer_t.GetConstructor(new Type[0]).Invoke(null);
return (SCG.IEqualityComparer)equalityComparer;
}
///
///
///
///
///
public static SCG.IEqualityComparer build()
{
MethodInfo hinfo = ByInvoke.hinfo, einfo = ByInvoke.einfo;
if (hinfo != null && einfo != null)
return CreateEqualityComparer(hinfo, einfo);
else
return EqualityComparer.Default;
}
///
///
///
public void dump()
{
assemblyBuilder.Save("LeFake.dll");
}
}
}
#endif