| | | 1 | | using System; |
| | | 2 | | using System.Collections; |
| | | 3 | | using System.Collections.Generic; |
| | | 4 | | using System.Runtime.CompilerServices; |
| | | 5 | | using System.Runtime.Serialization; |
| | | 6 | | using System.Security.Cryptography; |
| | | 7 | | using System.Threading; |
| | | 8 | | |
| | | 9 | | namespace SwiftCollections; |
| | | 10 | | |
| | | 11 | | /// <summary> |
| | | 12 | | /// Provides utility functions for generating, combining, and working with hash codes. |
| | | 13 | | /// </summary> |
| | | 14 | | public static class SwiftHashTools |
| | | 15 | | { |
| | | 16 | | internal const int DefaultDeterministicStringHashSeed = 0x51C4B5D; |
| | | 17 | | internal const int DefaultDeterministicObjectHashSeed = 0x1F6E4D75; |
| | | 18 | | |
| | 1 | 19 | | private static readonly IEqualityComparer<string> s_deterministicStringComparer = |
| | 1 | 20 | | new SwiftDeterministicStringEqualityComparer(DefaultDeterministicStringHashSeed); |
| | | 21 | | |
| | 1 | 22 | | private static readonly IEqualityComparer<object> s_deterministicObjectComparer = |
| | 1 | 23 | | new SwiftDeterministicObjectEqualityComparer(DefaultDeterministicObjectHashSeed); |
| | | 24 | | |
| | | 25 | | /// <summary> |
| | | 26 | | /// Provides a cryptographic random number generator for collision-hardening entropy. |
| | | 27 | | /// </summary> |
| | | 28 | | private static RandomNumberGenerator rng; |
| | | 29 | | |
| | | 30 | | /// <summary> |
| | | 31 | | /// Stores random bytes used for entropy generation. |
| | | 32 | | /// </summary> |
| | | 33 | | private static byte[] data; |
| | | 34 | | |
| | | 35 | | /// <summary> |
| | | 36 | | /// Tracks the current index in the entropy data buffer. |
| | | 37 | | /// </summary> |
| | 1 | 38 | | private static int currentIndex = 1024; |
| | | 39 | | |
| | | 40 | | /// <summary> |
| | | 41 | | /// Synchronization object for thread-safe operations. |
| | | 42 | | /// </summary> |
| | 1 | 43 | | private static readonly object lockObj = new(); |
| | | 44 | | |
| | | 45 | | /// <summary> |
| | | 46 | | /// Holds serialization information for objects during the serialization process. |
| | | 47 | | /// </summary> |
| | | 48 | | private static ConditionalWeakTable<object, SerializationInfo> s_SerializationInfoTable; |
| | | 49 | | |
| | | 50 | | /// <summary> |
| | | 51 | | /// Gets the table that stores serialization information for objects. |
| | | 52 | | /// </summary> |
| | | 53 | | internal static ConditionalWeakTable<object, SerializationInfo> SerializationInfoTable |
| | | 54 | | { |
| | | 55 | | get |
| | 2 | 56 | | { |
| | 2 | 57 | | if (s_SerializationInfoTable == null) |
| | 1 | 58 | | { |
| | 1 | 59 | | ConditionalWeakTable<object, SerializationInfo> value = new ConditionalWeakTable<object, SerializationIn |
| | 1 | 60 | | Interlocked.CompareExchange(ref s_SerializationInfoTable, value, null); |
| | 1 | 61 | | } |
| | | 62 | | |
| | 2 | 63 | | return s_SerializationInfoTable; |
| | 2 | 64 | | } |
| | | 65 | | } |
| | | 66 | | |
| | | 67 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 4 | 68 | | public static bool IsPowerOfTwo(int x) => (x != 0) && ((x & (x - 1)) == 0); |
| | | 69 | | |
| | | 70 | | /// <summary> |
| | | 71 | | /// Calculates the smallest power of two that is greater than or equal to the specified integer. |
| | | 72 | | /// This method is used to ensure that capacities are powers of two, enabling optimizations |
| | | 73 | | /// in indexing operations through bitwise arithmetic. |
| | | 74 | | /// </summary> |
| | | 75 | | /// <param name="value">The integer value for which to find the next power of two.</param> |
| | | 76 | | /// <returns>The smallest power of two greater than or equal to <paramref name="value"/>.</returns> |
| | | 77 | | /// <remarks> |
| | | 78 | | /// If <paramref name="value"/> is less than or equal to zero, the method returns 1. |
| | | 79 | | /// If <paramref name="value"/> is too large to represent as a power of two within an <c>int</c>, |
| | | 80 | | /// the methods returns `int.Max`. |
| | | 81 | | /// </remarks> |
| | | 82 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 83 | | public static int NextPowerOfTwo(int value) |
| | 11614 | 84 | | { |
| | 11616 | 85 | | if (value <= 0) return 1; |
| | 11613 | 86 | | if (value >= (1 << 30)) return int.MaxValue; |
| | | 87 | | |
| | 11611 | 88 | | value--; |
| | 11611 | 89 | | value |= value >> 1; |
| | 11611 | 90 | | value |= value >> 2; |
| | 11611 | 91 | | value |= value >> 4; |
| | 11611 | 92 | | value |= value >> 8; |
| | 11611 | 93 | | value |= value >> 16; |
| | 11611 | 94 | | value++; |
| | 11611 | 95 | | return value; |
| | 11614 | 96 | | } |
| | | 97 | | |
| | | 98 | | /// <summary> |
| | | 99 | | /// Combines the hash codes of the elements in a tuple using a DJB2-inspired mixing strategy. |
| | | 100 | | /// </summary> |
| | | 101 | | public static int CombineHashCodes( |
| | | 102 | | this ITuple tupled, |
| | | 103 | | int seed = 5381, |
| | | 104 | | int shift1 = 16, |
| | | 105 | | int shift2 = 5, |
| | | 106 | | int shift3 = 27, |
| | | 107 | | int factor3 = 1566083941) |
| | 1 | 108 | | { |
| | 1 | 109 | | int hash1 = (seed << shift1) + seed; |
| | 1 | 110 | | int hash2 = hash1; |
| | | 111 | | |
| | 10 | 112 | | for (int i = 0; i < tupled.Length; i++) |
| | 4 | 113 | | { |
| | 4 | 114 | | int itemHash = tupled[i]?.GetHashCode() ?? 0; |
| | | 115 | | unchecked |
| | 4 | 116 | | { |
| | 4 | 117 | | if (i % 2 == 0) |
| | 2 | 118 | | hash1 = ((hash1 << shift2) + hash1 + (hash1 >> shift3)) ^ itemHash; |
| | | 119 | | else |
| | 2 | 120 | | hash2 = ((hash2 << shift2) + hash2 + (hash2 >> shift3)) ^ itemHash; |
| | 4 | 121 | | } |
| | 4 | 122 | | } |
| | | 123 | | |
| | 1 | 124 | | return hash1 ^ (hash2 * factor3); |
| | 1 | 125 | | } |
| | | 126 | | |
| | | 127 | | /// <summary> |
| | | 128 | | /// Combines the hash codes of a set of objects using a DJB2-inspired mixing strategy. |
| | | 129 | | /// </summary> |
| | | 130 | | public static int CombineHashCodes( |
| | | 131 | | this object[] values, |
| | | 132 | | int seed = 5381, |
| | | 133 | | int shift1 = 16, |
| | | 134 | | int shift2 = 5, |
| | | 135 | | int shift3 = 27, |
| | | 136 | | int factor3 = 1566083941) |
| | 3 | 137 | | { |
| | 3 | 138 | | int hash1 = (seed << shift1) + seed; |
| | 3 | 139 | | int hash2 = hash1; |
| | | 140 | | |
| | 30 | 141 | | for (int i = 0; i < values.Length; i++) |
| | 12 | 142 | | { |
| | 12 | 143 | | var itemHash = values[i]?.GetHashCode() ?? 0; |
| | | 144 | | unchecked |
| | 12 | 145 | | { |
| | 12 | 146 | | if ((i & 1) == 0) |
| | 6 | 147 | | hash1 = ((hash1 << shift2) + hash1 + (hash1 >> shift3)) ^ itemHash; |
| | | 148 | | else |
| | 6 | 149 | | hash2 = ((hash2 << shift2) + hash2 + (hash2 >> shift3)) ^ itemHash; |
| | 12 | 150 | | } |
| | 12 | 151 | | } |
| | | 152 | | |
| | 3 | 153 | | return hash1 + (hash2 * factor3); |
| | 3 | 154 | | } |
| | | 155 | | |
| | | 156 | | /// <summary> |
| | | 157 | | /// Combines the hash codes of the provided objects using a DJB2-inspired mixing strategy. |
| | | 158 | | /// </summary> |
| | | 159 | | public static int CombineHashCodes( |
| | | 160 | | params object[] values) |
| | 2 | 161 | | { |
| | 2 | 162 | | return values.CombineHashCodes(); |
| | 2 | 163 | | } |
| | | 164 | | |
| | | 165 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 166 | | public static bool IsWellKnownEqualityComparer(object comparer) |
| | 8 | 167 | | { |
| | 8 | 168 | | return comparer == null |
| | 8 | 169 | | || comparer == EqualityComparer<string>.Default |
| | 8 | 170 | | || comparer == EqualityComparer<object>.Default |
| | 8 | 171 | | || comparer is SwiftDeterministicStringEqualityComparer |
| | 8 | 172 | | || comparer is SwiftDeterministicObjectEqualityComparer; |
| | 8 | 173 | | } |
| | | 174 | | |
| | | 175 | | /// <summary> |
| | | 176 | | /// Gets the default comparer used by SwiftCollections for the specified type when no comparer is supplied. |
| | | 177 | | /// String keys are hashed deterministically. Object keys hash strings deterministically, while other object-key |
| | | 178 | | /// determinism still depends on the underlying key type's <see cref="object.GetHashCode()"/> implementation. |
| | | 179 | | /// </summary> |
| | | 180 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 181 | | public static IEqualityComparer<T> GetDeterministicEqualityComparer<T>() |
| | 304 | 182 | | { |
| | 304 | 183 | | if (typeof(T) == typeof(string)) |
| | 83 | 184 | | return (IEqualityComparer<T>)GetDeterministicStringEqualityComparer(); |
| | | 185 | | |
| | 221 | 186 | | if (typeof(T) == typeof(object)) |
| | 6 | 187 | | return (IEqualityComparer<T>)GetDeterministicObjectEqualityComparer(); |
| | | 188 | | |
| | 215 | 189 | | return EqualityComparer<T>.Default; |
| | 304 | 190 | | } |
| | | 191 | | |
| | | 192 | | /// <summary> |
| | | 193 | | /// Gets the deterministic default comparer used by SwiftCollections for strings. |
| | | 194 | | /// </summary> |
| | | 195 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 196 | | public static IEqualityComparer<string> GetDeterministicStringEqualityComparer() |
| | 84 | 197 | | => s_deterministicStringComparer; |
| | | 198 | | |
| | | 199 | | /// <summary> |
| | | 200 | | /// Gets a deterministic string comparer using the supplied seed. |
| | | 201 | | /// </summary> |
| | | 202 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 203 | | public static IEqualityComparer<string> GetDeterministicStringEqualityComparer(int seed) |
| | 2 | 204 | | => seed == DefaultDeterministicStringHashSeed |
| | 2 | 205 | | ? s_deterministicStringComparer |
| | 2 | 206 | | : new SwiftDeterministicStringEqualityComparer(seed); |
| | | 207 | | |
| | | 208 | | /// <summary> |
| | | 209 | | /// Gets the default comparer used by SwiftCollections for object keys. |
| | | 210 | | /// Strings are hashed deterministically even when stored as objects. Other object keys still depend on their |
| | | 211 | | /// runtime <see cref="object.GetHashCode()"/> implementations. |
| | | 212 | | /// </summary> |
| | | 213 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 214 | | public static IEqualityComparer<object> GetDeterministicObjectEqualityComparer() |
| | 7 | 215 | | => s_deterministicObjectComparer; |
| | | 216 | | |
| | | 217 | | /// <summary> |
| | | 218 | | /// Gets an object comparer using the supplied seed. |
| | | 219 | | /// Strings are hashed deterministically even when stored as objects. Other object keys still depend on their |
| | | 220 | | /// runtime <see cref="object.GetHashCode()"/> implementations. |
| | | 221 | | /// </summary> |
| | | 222 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 223 | | public static IEqualityComparer<object> GetDeterministicObjectEqualityComparer(int seed) |
| | 2 | 224 | | => seed == DefaultDeterministicObjectHashSeed |
| | 2 | 225 | | ? s_deterministicObjectComparer |
| | 2 | 226 | | : new SwiftDeterministicObjectEqualityComparer(seed); |
| | | 227 | | |
| | | 228 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 229 | | internal static IEqualityComparer<T> GetDefaultEqualityComparer<T>(IEqualityComparer<T> comparer = null) |
| | 360 | 230 | | => comparer ?? GetDeterministicEqualityComparer<T>(); |
| | | 231 | | |
| | | 232 | | public static IEqualityComparer GetSwiftEqualityComparer(object comparer) |
| | 7 | 233 | | { |
| | 7 | 234 | | if (comparer == EqualityComparer<string>.Default || comparer is SwiftDeterministicStringEqualityComparer) |
| | 4 | 235 | | return new SwiftStringEqualityComparer(); |
| | | 236 | | |
| | 3 | 237 | | if (comparer == EqualityComparer<object>.Default || comparer is SwiftDeterministicObjectEqualityComparer) |
| | 2 | 238 | | return new SwiftObjectEqualityComparer(); |
| | | 239 | | |
| | 1 | 240 | | return new SwiftObjectEqualityComparer(); |
| | 7 | 241 | | } |
| | | 242 | | |
| | | 243 | | /// <summary> |
| | | 244 | | /// Generates a cryptographically strong random 64-bit integer for collision-hardening entropy. |
| | | 245 | | /// </summary> |
| | | 246 | | /// <returns>A 64-bit integer filled with cryptographically strong random bytes.</returns> |
| | | 247 | | internal static long GetEntropy() |
| | 139 | 248 | | { |
| | 139 | 249 | | lock (lockObj) |
| | 139 | 250 | | { |
| | 139 | 251 | | if (currentIndex == 1024) |
| | 2 | 252 | | { |
| | 2 | 253 | | if (rng == null) |
| | 1 | 254 | | { |
| | 1 | 255 | | rng = RandomNumberGenerator.Create(); |
| | 1 | 256 | | data = new byte[1024]; |
| | 1 | 257 | | } |
| | | 258 | | |
| | 2 | 259 | | rng.GetBytes(data); |
| | 2 | 260 | | currentIndex = 0; |
| | 2 | 261 | | } |
| | | 262 | | |
| | 139 | 263 | | long result = BitConverter.ToInt64(data, currentIndex); |
| | 139 | 264 | | currentIndex += 8; |
| | 139 | 265 | | return result; |
| | | 266 | | } |
| | 139 | 267 | | } |
| | | 268 | | |
| | | 269 | | /// <summary> |
| | | 270 | | /// Computes a hash code for a string using the MurmurHash3 algorithm, incorporating entropy for randomization. |
| | | 271 | | /// </summary> |
| | | 272 | | /// <param name="key">The string to hash.</param> |
| | | 273 | | /// <param name="seed">The seed value for the hash function.</param> |
| | | 274 | | /// <returns>An integer hash code for the string.</returns> |
| | | 275 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 276 | | public static unsafe int MurmurHash3(string key, int seed) |
| | 305308 | 277 | | { |
| | | 278 | | const uint c1 = 0xcc9e2d51; |
| | | 279 | | const uint c2 = 0x1b873593; |
| | 305308 | 280 | | uint h1 = (uint)seed; |
| | | 281 | | |
| | 305308 | 282 | | fixed (char* ptr = key) |
| | 305308 | 283 | | { |
| | 305308 | 284 | | int length = key.Length; |
| | 305308 | 285 | | int blockCount = length / 2; |
| | | 286 | | |
| | | 287 | | unchecked |
| | 305308 | 288 | | { |
| | | 289 | | // Process 32-bit blocks |
| | 7734454 | 290 | | for (int i = 0; i < blockCount; i++) |
| | 3561919 | 291 | | { |
| | 3561919 | 292 | | uint k1 = *(uint*)(ptr + (i * 2)); |
| | 3561919 | 293 | | k1 *= c1; |
| | 3561919 | 294 | | k1 = RotateLeft(k1, 15); |
| | 3561919 | 295 | | k1 *= c2; |
| | 3561919 | 296 | | h1 ^= k1; |
| | 3561919 | 297 | | h1 = RotateLeft(h1, 13); |
| | 3561919 | 298 | | h1 = h1 * 5 + 0xe6546b64; |
| | 3561919 | 299 | | } |
| | | 300 | | |
| | | 301 | | // Handle remaining characters if odd length |
| | 305308 | 302 | | if (length % 2 != 0) |
| | 25793 | 303 | | { |
| | 25793 | 304 | | uint k1 = ptr[length - 1]; |
| | 25793 | 305 | | k1 *= c1; |
| | 25793 | 306 | | k1 = RotateLeft(k1, 15); |
| | 25793 | 307 | | k1 *= c2; |
| | 25793 | 308 | | h1 ^= k1; |
| | 25793 | 309 | | } |
| | 305308 | 310 | | } |
| | | 311 | | |
| | 305308 | 312 | | h1 ^= (uint)length; |
| | 305308 | 313 | | h1 = FMix(h1); |
| | 305308 | 314 | | return (int)(h1 & 0x7FFFFFFF); |
| | | 315 | | } |
| | 305308 | 316 | | } |
| | | 317 | | |
| | | 318 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | 7149631 | 319 | | private static uint RotateLeft(uint x, int r) => (x << r) | (x >> (32 - r)); |
| | | 320 | | |
| | | 321 | | [MethodImpl(MethodImplOptions.AggressiveInlining)] |
| | | 322 | | private static uint FMix(uint h) |
| | 305308 | 323 | | { |
| | 305308 | 324 | | h ^= h >> 16; |
| | 305308 | 325 | | h *= 0x85ebca6b; |
| | 305308 | 326 | | h ^= h >> 13; |
| | 305308 | 327 | | h *= 0xc2b2ae35; |
| | 305308 | 328 | | h ^= h >> 16; |
| | 305308 | 329 | | return h; |
| | 305308 | 330 | | } |
| | | 331 | | } |