| | | 1 | | using System.Collections; |
| | | 2 | | using System.Collections.Generic; |
| | | 3 | | using System.Runtime.CompilerServices; |
| | | 4 | | using System.Runtime.Serialization; |
| | | 5 | | |
| | | 6 | | namespace SwiftCollections; |
| | | 7 | | |
| | | 8 | | /// <summary> |
| | | 9 | | /// Provides a deterministic object comparer used by SwiftCollections when no comparer is supplied. |
| | | 10 | | /// Strings are hashed via <see cref="SwiftHashTools.MurmurHash3(string, int)"/> to avoid runtime-dependent string hashe |
| | | 11 | | /// </summary> |
| | | 12 | | internal sealed class SwiftDeterministicObjectEqualityComparer : IEqualityComparer<object>, IEqualityComparer, ISerializ |
| | | 13 | | { |
| | | 14 | | private readonly int _seed; |
| | | 15 | | |
| | 6 | 16 | | public SwiftDeterministicObjectEqualityComparer() : this(SwiftHashTools.DefaultDeterministicObjectHashSeed) { } |
| | | 17 | | |
| | 7 | 18 | | internal SwiftDeterministicObjectEqualityComparer(int seed) |
| | 7 | 19 | | { |
| | 7 | 20 | | _seed = seed; |
| | 7 | 21 | | } |
| | | 22 | | |
| | | 23 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 24 | | public new bool Equals(object x, object y) |
| | 5 | 25 | | { |
| | 5 | 26 | | return x == y || (x != null && y != null && x.Equals(y)); |
| | 5 | 27 | | } |
| | | 28 | | |
| | | 29 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 3 | 30 | | public override bool Equals(object obj) => obj is SwiftDeterministicObjectEqualityComparer other && _seed == other._ |
| | | 31 | | |
| | | 32 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 33 | | public int GetHashCode(object obj) |
| | 9 | 34 | | { |
| | 10 | 35 | | if (obj == null) return 0; |
| | 14 | 36 | | if (obj is string text) return SwiftHashTools.MurmurHash3(text, _seed); |
| | 2 | 37 | | return obj.GetHashCode() ^ _seed; |
| | 9 | 38 | | } |
| | | 39 | | |
| | | 40 | | [MethodImpl(MethodImplOptions.NoInlining)] |
| | 2 | 41 | | public override int GetHashCode() => GetType().Name.GetHashCode() ^ _seed; |
| | | 42 | | |
| | | 43 | | public void GetObjectData(SerializationInfo info, StreamingContext context) |
| | 1 | 44 | | { |
| | 1 | 45 | | info.AddValue("Seed", _seed); |
| | 1 | 46 | | } |
| | | 47 | | } |