Welcome to mirror list, hosted at ThFree Co, Russian Federation.

Hashers.cs « C5 « Mono.C5 « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d759c15a9f9f3b1e0cea099149abb4b0ba3d6769 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
#if NET_2_0
/*
 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
{
  /// <summary>
  /// Utility class for building default generic equalityComparers.
  /// </summary>
  /// <typeparam name="T"></typeparam>
  public static class EqualityComparer<T>
  {
    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<T>);

    static SCG.IEqualityComparer<T> cachedDefault = null;

    //TODO: find the right word for initialized+invocation 
    /// <summary>
    /// A default generic equalityComparer for type T. The procedure is as follows:
    /// <list>
    /// <item>If T is int, double, byte or char, 
    /// the equalityComparer will be a standard equalityComparer for that type</item>
    /// <item>If the actual generic argument T implements the generic interface
    /// <see cref="T:C5.ISequenced`1"/> for some value W of its generic parameter T,
    /// the equalityComparer will be <see cref="T:C5.SequencedCollectionEqualityComparer`2"/></item>
    /// <item>If the actual generic argument T implements 
    /// <see cref="T:C5.ICollectionValue`1"/> for some value W of its generic parameter T,
    /// the equalityComparer will be <see cref="T:C5.UnsequencedCollectionEqualityComparer`2"/></item>
    /// <item>If T is a type implementing <see cref="T:C5.IEquatable`1"/>, the equalityComparer
    /// will be <see cref="T:C5.EquatableEqualityComparer`1"/></item>
    /// <item>If T is a type not implementing <see cref="T:C5.IEquatable`1"/>, the equalityComparer
    /// will be <see cref="T:C5.NaturalEqualityComparer`1"/> </item>
    /// </list>   
    /// The <see cref="T:C5.IEqualityComparer`1"/> 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.
    /// </summary>
    /// <value></value>
    public static SCG.IEqualityComparer<T> Default
    {
      get
      {
        if (cachedDefault != null)
          return cachedDefault;

        Type t = typeof(T);

        if (t.IsValueType)
        {
          if (t.Equals(typeof(int)))
            return cachedDefault = (SCG.IEqualityComparer<T>)(IntEqualityComparer.Default);
          else if (t.Equals(typeof(double)))
            return cachedDefault = (SCG.IEqualityComparer<T>)(DoubleEqualityComparer.Default);
          else if (t.Equals(typeof(byte)))
            return cachedDefault = (SCG.IEqualityComparer<T>)(ByteEqualityComparer.Default);
          else if (t.Equals(typeof(char)))
            return cachedDefault = (SCG.IEqualityComparer<T>)(CharEqualityComparer.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<T>.Default;
      }
    }
    static SCG.IEqualityComparer<T> createAndCache(Type equalityComparertype)
    {
      return cachedDefault = (SCG.IEqualityComparer<T>)(equalityComparertype.GetProperty("Default", BindingFlags.Static | BindingFlags.Public).GetValue(null, null));
    }
  }

  /// <summary>
  /// A default item equalityComparer calling through to
  /// the GetHashCode and Equals methods inherited from System.Object.
  /// </summary>
  public sealed class NaturalEqualityComparer<T> : SCG.IEqualityComparer<T>
  {
    static NaturalEqualityComparer<T> cached;
    NaturalEqualityComparer() { }
    /// <summary>
    /// 
    /// </summary>
    /// <value></value>
    public static NaturalEqualityComparer<T> Default { get { return cached ?? (cached = new NaturalEqualityComparer<T>()); } }
    //TODO: check if null check is reasonable
    //Answer: if we have struct C<T> { 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<T> in a reasonable way.
    /// <summary>
    /// Get the hash code with respect to this item equalityComparer
    /// </summary>
    /// <param name="item">The item</param>
    /// <returns>The hash code</returns>
    [Tested]
    public int GetHashCode(T item) { return item == null ? 0 : item.GetHashCode(); }


    /// <summary>
    /// Check if two items are equal with respect to this item equalityComparer
    /// </summary>
    /// <param name="item1">first item</param>
    /// <param name="item2">second item</param>
    /// <returns>True if equal</returns>
    [Tested]
    public bool Equals(T item1, T item2)
    {
      return item1 == null ? item2 == null : item1.Equals(item2);
    }
  }

  /// <summary>
  /// A default equalityComparer for a type, T, implementing <see cref="T:C5.IEquatable`1"/>. 
  /// 
  /// The equalityComparer forwards calls to GetHashCode and Equals to the methods 
  /// on T. The point is that it is Equals(T) and not Equals(object)
  /// that is called. This will save a boxing/unboxing pair if T is a value type
  /// and in general a runtime type check.
  /// </summary>
  /// <typeparam name="T"></typeparam>
  public class EquatableEqualityComparer<T> : SCG.IEqualityComparer<T> where T : IEquatable<T>
  {
    static EquatableEqualityComparer<T> cached = new EquatableEqualityComparer<T>();
    EquatableEqualityComparer() { }
    /// <summary>
    /// 
    /// </summary>
    /// <value></value>
    public static EquatableEqualityComparer<T> Default { get { return cached ?? (cached = new EquatableEqualityComparer<T>()); } }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    public int GetHashCode(T item) { return item == null ? 0 : item.GetHashCode(); }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="item1"></param>
    /// <param name="item2"></param>
    /// <returns></returns>
    public bool Equals(T item1, T item2) { return item1 == null ? item2 == null : item1.Equals(item2); }
  }

  /// <summary>
  /// A equalityComparer for a reference type that uses reference equality for equality and the hash code from object as hash code.
  /// </summary>
  /// <typeparam name="T">The item type. Must be a reference type.</typeparam>
  public class ReferenceEqualityComparer<T> : SCG.IEqualityComparer<T> where T : class
  {
    static ReferenceEqualityComparer<T> cached;
    ReferenceEqualityComparer() { }
    /// <summary>
    /// 
    /// </summary>
    /// <value></value>
    public static ReferenceEqualityComparer<T> Default { get { return cached ?? (cached = new ReferenceEqualityComparer<T>()); } }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    public int GetHashCode(T item)
    {
      return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(item);
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="i1"></param>
    /// <param name="i2"></param>
    /// <returns></returns>
    public bool Equals(T i1, T i2)
    {
      return object.ReferenceEquals(i1, i2);
    }
  }

  /// <summary>
  /// An equalityComparer compatible with a given comparer. All hash codes are 0, 
  /// meaning that anything based on hash codes will be quite inefficient.
  /// <para><b>Note: this will give a new EqualityComparer each time created!</b></para>
  /// </summary>
  /// <typeparam name="T"></typeparam>
  public class ComparerZeroHashCodeEqualityComparer<T> : SCG.IEqualityComparer<T>
  {
    SCG.IComparer<T> comparer;
    /// <summary>
    /// Create a trivial <see cref="T:C5.IEqualityComparer`1"/> compatible with the 
    /// <see cref="T:C5.IComparer`1"/> <code>comparer</code>
    /// </summary>
    /// <param name="comparer"></param>
    public ComparerZeroHashCodeEqualityComparer(SCG.IComparer<T> comparer)
    {
      if (comparer == null)
        throw new NullReferenceException("Compaer cannot be null");
      this.comparer = comparer;
    }
    /// <summary>
    /// A trivial, inefficient hash fuction. Compatible with any equality relation.
    /// </summary>
    /// <param name="item"></param>
    /// <returns>0</returns>
    public int GetHashCode(T item) { return 0; }
    /// <summary>
    /// Equality of two items as defined by the comparer.
    /// </summary>
    /// <param name="item1"></param>
    /// <param name="item2"></param>
    /// <returns></returns>
    public bool Equals(T item1, T item2) { return comparer.Compare(item1, item2) == 0; }
  }

  /// <summary>
  /// Prototype for an sequenced equalityComparer for something (T) that implements ISequenced[W]
  /// This will use ISequenced[W] specific implementations of the equalityComparer operations
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <typeparam name="W"></typeparam>
  public class SequencedCollectionEqualityComparer<T, W> : SCG.IEqualityComparer<T>
      where T : ISequenced<W>
  {
    static SequencedCollectionEqualityComparer<T, W> cached;
    SequencedCollectionEqualityComparer() { }
    /// <summary>
    /// 
    /// </summary>
    /// <value></value>
    public static SequencedCollectionEqualityComparer<T, W> Default { get { return cached ?? (cached = new SequencedCollectionEqualityComparer<T, W>()); } }
    /// <summary>
    /// Get the hash code with respect to this sequenced equalityComparer
    /// </summary>
    /// <param name="collection">The collection</param>
    /// <returns>The hash code</returns>
    [Tested]
    public int GetHashCode(T collection) { return collection.GetSequencedHashCode(); }


    /// <summary>
    /// Check if two items are equal with respect to this sequenced equalityComparer
    /// </summary>
    /// <param name="collection1">first collection</param>
    /// <param name="collection2">second collection</param>
    /// <returns>True if equal</returns>
    [Tested]
    public bool Equals(T collection1, T collection2) { return collection1 == null ? collection2 == null : collection1.SequencedEquals(collection2); }
  }

  /// <summary>
  /// Prototype for an unsequenced equalityComparer for something (T) that implements ICollection[W]
  /// This will use ICollection[W] specific implementations of the equalityComparer operations
  /// </summary>
  /// <typeparam name="T"></typeparam>
  /// <typeparam name="W"></typeparam>
  public class UnsequencedCollectionEqualityComparer<T, W> : SCG.IEqualityComparer<T>
      where T : ICollection<W>
  {
    static UnsequencedCollectionEqualityComparer<T, W> cached;
    UnsequencedCollectionEqualityComparer() { }
    /// <summary>
    /// 
    /// </summary>
    /// <value></value>
    public static UnsequencedCollectionEqualityComparer<T, W> Default { get { return cached ?? (cached = new UnsequencedCollectionEqualityComparer<T, W>()); } }
    /// <summary>
    /// Get the hash code with respect to this unsequenced equalityComparer
    /// </summary>
    /// <param name="collection">The collection</param>
    /// <returns>The hash code</returns>
    [Tested]
    public int GetHashCode(T collection) { return collection.GetUnsequencedHashCode(); }


    /// <summary>
    /// Check if two collections are equal with respect to this unsequenced equalityComparer
    /// </summary>
    /// <param name="collection1">first collection</param>
    /// <param name="collection2">second collection</param>
    /// <returns>True if equal</returns>
    [Tested]
    public bool Equals(T collection1, T collection2) { return collection1 == null ? collection2 == null : collection1.UnsequencedEquals(collection2); }
  }

}





#if EXPERIMENTAL
namespace C5.EqualityComparerBuilder
{

  /// <summary>
  /// 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.
  /// </summary>
  public class ByInvoke<T> : SCG.IEqualityComparer<T>
  {
    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() { }

/// <summary>
/// 
/// </summary>
/// <returns></returns>
    public static SCG.IEqualityComparer<T> MakeEqualityComparer()
    {
      if (hinfo != null && einfo != null)
        return new ByInvoke<T>();
      else
        return NaturalEqualityComparer<T>.Default;
    }

/// <summary>
/// 
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
    public int GetHashCode(T item)
    {
      return (int)(hinfo.Invoke(item, null));
    }

/// <summary>
/// 
/// </summary>
/// <param name="i1"></param>
/// <param name="i2"></param>
/// <returns></returns>
    public bool Equals(T i1, T i2)
    {
      return (bool)(einfo.Invoke(i1, new object[1] { i2 }));
    }
  }



  /// <summary>
  /// Like ByInvoke, but tries to build a equalityComparer by RTCG to
  /// avoid the Invoke() overhead. 
  /// </summary>
  public class ByRTCG
  {
    private static ModuleBuilder moduleBuilder;

    private static AssemblyBuilder assemblyBuilder;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="hinfo"></param>
    /// <param name="einfo"></param>
    /// <returns></returns>
    public static SCG.IEqualityComparer<T> CreateEqualityComparer<T>(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<T>);
      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<T>)equalityComparer;
    }

/// <summary>
/// 
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
    public static SCG.IEqualityComparer<T> build<T>()
    {
      MethodInfo hinfo = ByInvoke<T>.hinfo, einfo = ByInvoke<T>.einfo;

      if (hinfo != null && einfo != null)
        return CreateEqualityComparer<T>(hinfo, einfo);
      else
        return EqualityComparer<T>.Default;
    }

/// <summary>
/// 
/// </summary>
    public void dump()
    {
      assemblyBuilder.Save("LeFake.dll");
    }
  }
}
#endif

#endif