forked from nhibernate/nhibernate-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCollectionHelper.cs
767 lines (634 loc) · 18.8 KB
/
CollectionHelper.cs
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Iesi.Collections.Generic;
namespace NHibernate.Util
{
public static class CollectionHelper
{
[Serializable]
private class EmptyEnumerator : IDictionaryEnumerator
{
public object Key
{
get { throw new InvalidOperationException("EmptyEnumerator.get_Key"); }
}
public object Value
{
get { throw new InvalidOperationException("EmptyEnumerator.get_Value"); }
}
public DictionaryEntry Entry
{
get { throw new InvalidOperationException("EmptyEnumerator.get_Entry"); }
}
public void Reset()
{
}
public object Current
{
get { throw new InvalidOperationException("EmptyEnumerator.get_Current"); }
}
public bool MoveNext()
{
return false;
}
}
private class EmptyEnumerableClass : IEnumerable
{
public IEnumerator GetEnumerator()
{
return new EmptyEnumerator();
}
}
/// <summary>
/// A read-only dictionary that is always empty and permits lookup by <see langword="null" /> key.
/// </summary>
[Serializable]
private class EmptyMapClass : IDictionary
{
private static readonly EmptyEnumerator emptyEnumerator = new EmptyEnumerator();
public bool Contains(object key)
{
return false;
}
public void Add(object key, object value)
{
throw new NotSupportedException("EmptyMap.Add");
}
public void Clear()
{
throw new NotSupportedException("EmptyMap.Clear");
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return emptyEnumerator;
}
public void Remove(object key)
{
throw new NotSupportedException("EmptyMap.Remove");
}
public object this[object key]
{
get { return null; }
set { throw new NotSupportedException("EmptyMap.set_Item"); }
}
public ICollection Keys
{
get { return this; }
}
public ICollection Values
{
get { return this; }
}
public bool IsReadOnly
{
get { return true; }
}
public bool IsFixedSize
{
get { return true; }
}
public void CopyTo(Array array, int index)
{
}
public int Count
{
get { return 0; }
}
public object SyncRoot
{
get { return this; }
}
public bool IsSynchronized
{
get { return false; }
}
public IEnumerator GetEnumerator()
{
return emptyEnumerator;
}
}
// To be removed in v6.0
[Serializable]
private class EmptyListClass : IList
{
public int Add(object value)
{
throw new NotImplementedException();
}
public bool Contains(object value)
{
return false;
}
public void Clear()
{
throw new NotImplementedException();
}
public int IndexOf(object value)
{
return -1;
}
public void Insert(int index, object value)
{
throw new NotImplementedException();
}
public void Remove(object value)
{
throw new NotImplementedException();
}
public void RemoveAt(int index)
{
throw new NotImplementedException();
}
public object this[int index]
{
get { throw new IndexOutOfRangeException(); }
set { throw new IndexOutOfRangeException(); }
}
public bool IsReadOnly
{
get { return true; }
}
public bool IsFixedSize
{
get { return true; }
}
public void CopyTo(Array array, int index)
{
}
public int Count
{
get { return 0; }
}
public object SyncRoot
{
get { return this; }
}
public bool IsSynchronized
{
get { return false; }
}
public IEnumerator GetEnumerator()
{
return new EmptyEnumerator();
}
}
public static readonly IEnumerable EmptyEnumerable = new EmptyEnumerableClass();
public static readonly IDictionary EmptyMap = new EmptyMapClass();
public static IDictionary<TKey, TValue> EmptyDictionary<TKey, TValue>()
{
return EmptyMapClass<TKey, TValue>.Instance;
}
internal static ISet<T> EmptySet<T>() => EmptyReadOnlySet<T>.Instance;
public static readonly ICollection EmptyCollection = EmptyMap;
// Since v5
[Obsolete("It has no more usages in NHibernate and will be removed in a future version.")]
public static readonly IList EmptyList = new EmptyListClass();
// Obsolete since v5
/// <summary>
/// Determines if two collections have equals elements, with the same ordering.
/// </summary>
/// <param name="c1">The first collection.</param>
/// <param name="c2">The second collection.</param>
/// <returns><c>true</c> if collection are equals, <c>false</c> otherwise.</returns>
[Obsolete("It has no more usages in NHibernate and will be removed in a future version.")]
public static bool CollectionEquals(ICollection c1, ICollection c2)
{
if (c1 == c2)
{
return true;
}
if (c1 == null || c2 == null)
{
return false;
}
if (c1.Count != c2.Count)
{
return false;
}
var e2 = c2.GetEnumerator();
try
{
foreach (var item1 in c1)
{
e2.MoveNext();
if (!Equals(item1, e2.Current))
{
return false;
}
}
}
finally
{
// Most IEnumerator will have a disposable concrete implementation, must check it.
(e2 as IDisposable)?.Dispose();
}
return true;
}
// Since v5
[Obsolete("It has no more usages in NHibernate and will be removed in a future version.")]
public static bool DictionaryEquals(IDictionary a, IDictionary b)
{
if (Equals(a, b))
{
return true;
}
if (a == null || b == null)
{
return false;
}
if (a.Count != b.Count)
{
return false;
}
foreach (object key in a.Keys)
{
if (!Equals(a[key], b[key]))
{
return false;
}
}
return true;
}
// Obsolete since v5
/// <summary>
/// Computes a hash code for <paramref name="coll"/>.
/// </summary>
/// <remarks>The hash code is computed as the sum of hash codes of individual elements
/// plus a length of the collection, so that the value is independent of the
/// collection iteration order.
/// </remarks>
[Obsolete("It has no more usages in NHibernate and will be removed in a future version.")]
public static int GetHashCode(IEnumerable coll)
{
var result = 0;
foreach (var obj in coll)
{
unchecked
{
if (obj != null)
result += obj.GetHashCode();
result++;
}
}
return result;
}
/// <summary>
/// Creates a <see cref="Hashtable" /> that uses case-insensitive string comparison
/// associated with invariant culture.
/// </summary>
/// <remarks>
/// This is different from the method in <see cref="System.Collections.Specialized.CollectionsUtil" />
/// in that the latter uses the current culture and is thus vulnerable to the "Turkish I" problem.
/// </remarks>
public static IDictionary<string, T> CreateCaseInsensitiveHashtable<T>()
{
return new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase);
}
/// <summary>
/// Creates a <see cref="Hashtable" /> that uses case-insensitive string comparison
/// associated with invariant culture.
/// </summary>
/// <remarks>
/// This is different from the method in <see cref="System.Collections.Specialized.CollectionsUtil" />
/// in that the latter uses the current culture and is thus vulnerable to the "Turkish I" problem.
/// </remarks>
public static IDictionary<string, T> CreateCaseInsensitiveHashtable<T>(IDictionary<string, T> dictionary)
{
return new Dictionary<string, T>(dictionary, StringComparer.OrdinalIgnoreCase);
}
// ~~~~~~~~~~~~~~~~~~~~~~ Generics ~~~~~~~~~~~~~~~~~~~~~~
[Serializable]
private class EmptyEnumerator<TKey, TValue> : IEnumerator<KeyValuePair<TKey, TValue>>
{
#region IEnumerator<KeyValuePair<TKey,TValue>> Members
KeyValuePair<TKey, TValue> IEnumerator<KeyValuePair<TKey, TValue>>.Current
{
get
{
throw new InvalidOperationException(
string.Format("EmptyEnumerator<{0},{1}>.KeyValuePair", typeof(TKey), typeof(TValue)));
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
}
#endregion
#region IEnumerator Members
public bool MoveNext()
{
return false;
}
public void Reset()
{
}
public object Current
{
get
{
throw new InvalidOperationException(
string.Format("EmptyEnumerator<{0},{1}>.Current", typeof(TKey), typeof(TValue)));
}
}
#endregion
}
[Serializable]
public class EmptyEnumerableClass<T> : IEnumerable<T>
{
#region IEnumerable<T> Members
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new EmptyEnumerator<T>();
}
#endregion
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return ((IEnumerable<T>)this).GetEnumerator();
}
#endregion
}
[Serializable]
private class EmptyEnumerator<T> : IEnumerator<T>
{
#region IEnumerator<T> Members
T IEnumerator<T>.Current
{
get { throw new InvalidOperationException("EmptyEnumerator.get_Current"); }
}
#endregion
#region IDisposable Members
public void Dispose()
{
}
#endregion
#region IEnumerator Members
public bool MoveNext()
{
return false;
}
public void Reset()
{
}
public object Current
{
get { throw new InvalidOperationException("EmptyEnumerator.get_Current"); }
}
#endregion
}
[Serializable]
private class EmptyReadOnlySet<T>
{
public static readonly ISet<T> Instance = new ReadOnlySet<T>(new HashSet<T>());
}
/// <summary>
/// A read-only dictionary that is always empty and permits lookup by <see langword="null" /> key.
/// </summary>
[Serializable]
public class EmptyMapClass<TKey, TValue> : IDictionary<TKey, TValue>
{
#pragma warning disable 618 // Constructor is obsolete, to be switched to non-obsolete but private.
internal static readonly IDictionary<TKey, TValue> Instance = new EmptyMapClass<TKey, TValue>();
#pragma warning restore 618
private static readonly EmptyEnumerator<TKey, TValue> emptyEnumerator = new EmptyEnumerator<TKey, TValue>();
// Since v5.1. To be switched to private.
[Obsolete("Please use CollectionHelper.EmptyDictionary<TKey, TValue>() instead.")]
public EmptyMapClass()
{
}
#region IDictionary<TKey,TValue> Members
public bool ContainsKey(TKey key)
{
return false;
}
public void Add(TKey key, TValue value)
{
throw new NotSupportedException(string.Format("EmptyMapClass<{0},{1}>.Add", typeof(TKey), typeof(TValue)));
}
public bool Remove(TKey key)
{
throw new NotSupportedException(string.Format("EmptyMapClass<{0},{1}>.Remove", typeof(TKey), typeof(TValue)));
}
public bool TryGetValue(TKey key, out TValue value)
{
value = default(TValue);
return false;
}
public TValue this[TKey key]
{
get { return default(TValue); }
set { throw new NotSupportedException(string.Format("EmptyMapClass<{0},{1}>.set_Item", typeof(TKey), typeof(TValue))); }
}
public ICollection<TKey> Keys
{
get { return Array.Empty<TKey>(); }
}
public ICollection<TValue> Values
{
get { return Array.Empty<TValue>(); }
}
#endregion
#region ICollection<KeyValuePair<TKey,TValue>> Members
public void Add(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException(string.Format("EmptyMapClass<{0},{1}>.Add", typeof(TKey), typeof(TValue)));
}
public void Clear()
{
throw new NotSupportedException(string.Format("EmptyMapClass<{0},{1}>.Clear", typeof(TKey), typeof(TValue)));
}
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return false;
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
}
public bool Remove(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException(string.Format("EmptyMapClass<{0},{1}>.Remove", typeof(TKey), typeof(TValue)));
}
public int Count
{
get { return 0; }
}
public bool IsReadOnly
{
get { return true; }
}
#endregion
#region IEnumerable<KeyValuePair<TKey,TValue>> Members
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return emptyEnumerator;
}
#endregion
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return ((IEnumerable<KeyValuePair<TKey, TValue>>)this).GetEnumerator();
}
#endregion
}
/// <summary>
/// Computes a hash code for <paramref name="coll"/>.
/// </summary>
/// <remarks>The hash code is computed as the sum of hash codes of individual elements
/// plus a length of the collection, so that the value is independent of the
/// collection iteration order.
/// </remarks>
public static int GetHashCode<T>(IEnumerable<T> coll)
{
var result = 0;
foreach (var obj in coll)
{
unchecked
{
if (!ReferenceEquals(obj, null))
result += obj.GetHashCode();
result++;
}
}
return result;
}
/// <summary>
/// Computes a hash code for <paramref name="coll"/>.
/// </summary>
/// <remarks>The hash code is computed as the sum of hash codes of individual elements
/// plus a length of the collection, so that the value is independent of the
/// collection iteration order.
/// </remarks>
public static int GetHashCode<T>(IEnumerable<T> coll, IEqualityComparer<T> comparer)
{
var result = 0;
foreach (var obj in coll)
{
unchecked
{
if (!ReferenceEquals(obj, null))
result += comparer.GetHashCode(obj);
result++;
}
}
return result;
}
/// <summary>
/// Determines if two sets have equal elements. Supports <c>null</c> arguments.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <param name="s1">The first set.</param>
/// <param name="s2">The second set.</param>
/// <returns><c>true</c> if sets are equals, <c>false</c> otherwise.</returns>
public static bool SetEquals<T>(ISet<T> s1, ISet<T> s2)
=> FastCheckEquality(s1, s2) ?? s1.SetEquals(s2);
// Obsolete since v5
/// <summary>
/// Determines if two collections have equals elements, with the same ordering.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <param name="c1">The first collection.</param>
/// <param name="c2">The second collection.</param>
/// <returns><c>true</c> if collections are equals, <c>false</c> otherwise.</returns>
[Obsolete("Please use SequenceEquals instead.")]
public static bool CollectionEquals<T>(ICollection<T> c1, ICollection<T> c2)
=> SequenceEquals(c1, c2);
/// <summary>
/// Determines if two collections have equals elements, with the same ordering. Supports <c>null</c> arguments.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <param name="c1">The first collection.</param>
/// <param name="c2">The second collection.</param>
/// <returns><c>true</c> if collections are equals, <c>false</c> otherwise.</returns>
public static bool SequenceEquals<T>(IEnumerable<T> c1, IEnumerable<T> c2)
=> SequenceEquals(c1, c2, null);
/// <summary>
/// Determines if two collections have equals elements, with the same ordering. Supports <c>null</c> arguments.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <param name="c1">The first collection.</param>
/// <param name="c2">The second collection.</param>
/// <param name="comparer">The element comparer.</param>
/// <returns><c>true</c> if collections are equals, <c>false</c> otherwise.</returns>
public static bool SequenceEquals<T>(IEnumerable<T> c1, IEnumerable<T> c2, IEqualityComparer<T> comparer)
=> FastCheckEquality(c1, c2) ?? c1.SequenceEqual(c2, comparer);
/// <summary>
/// Determines if two collections have the same elements with the same duplication count, whatever their ordering.
/// Supports <c>null</c> arguments.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <param name="c1">The first collection.</param>
/// <param name="c2">The second collection.</param>
/// <returns><c>true</c> if collections are equals, <c>false</c> otherwise.</returns>
public static bool BagEquals<T>(IEnumerable<T> c1, IEnumerable<T> c2)
=> BagEquals(c1, c2, null);
/// <summary>
/// Determines if two collections have the same elements with the same duplication count, whatever their ordering.
/// Supports <c>null</c> arguments.
/// </summary>
/// <typeparam name="T">The type of the elements.</typeparam>
/// <param name="c1">The first collection.</param>
/// <param name="c2">The second collection.</param>
/// <param name="comparer">The element comparer.</param>
/// <returns><c>true</c> if collections are equals, <c>false</c> otherwise.</returns>
public static bool BagEquals<T>(IEnumerable<T> c1, IEnumerable<T> c2, IEqualityComparer<T> comparer)
{
var result = FastCheckEquality(c1, c2);
if (result.HasValue)
return result.Value;
var l2 = c2.ToLookup(e => e, comparer);
// Lookups return an empty sequence if a key is missing, no need to test if it contains it.
return c1.ToLookup(e => e, comparer).All(g => g.Count() == l2[g.Key].Count());
}
/// <summary>
/// Determines if two maps have the same key-values. Supports <c>null</c> arguments.
/// </summary>
/// <typeparam name="K">The type of the keys.</typeparam>
/// <typeparam name="V">The type of the values.</typeparam>
/// <param name="m1">The first map.</param>
/// <param name="m2">The second map.</param>
/// <returns><c>true</c> if maps are equals, <c>false</c> otherwise.</returns>
public static bool DictionaryEquals<K, V>(IDictionary<K, V> m1, IDictionary<K, V> m2)
=> DictionaryEquals(m1, m2, null);
/// <summary>
/// Determines if two maps have the same key-values. Supports <c>null</c> arguments.
/// </summary>
/// <typeparam name="K">The type of the keys.</typeparam>
/// <typeparam name="V">The type of the values.</typeparam>
/// <param name="m1">The first map.</param>
/// <param name="m2">The second map.</param>
/// <param name="comparer">The value comparer.</param>
/// <returns><c>true</c> if maps are equals, <c>false</c> otherwise.</returns>
public static bool DictionaryEquals<K, V>(IDictionary<K, V> m1, IDictionary<K, V> m2, IEqualityComparer<V> comparer)
=> FastCheckEquality(m1, m2) ??
(comparer == null ? DictionaryEquals(m1, m2, EqualityComparer<V>.Default) :
m1.All(kv => m2.TryGetValue(kv.Key, out var value) && comparer.Equals(kv.Value, value)));
//It's added to make use of optimized .NET Core Dictionary.Remove(key, out value) method
internal static bool Remove<TKey, TValue>(this Dictionary<TKey, TValue> dic, TKey key, out TValue value)
{
if (!dic.TryGetValue(key, out value))
return false;
dic.Remove(key);
return true;
}
private static bool? FastCheckEquality<T>(IEnumerable<T> c1, IEnumerable<T> c2)
{
if (c1 == c2)
{
return true;
}
if (c1 == null || c2 == null)
{
return false;
}
if (c1.Count() != c2.Count())
{
return false;
}
// Requires elements comparison.
return null;
}
}
}