Marvin.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Diagnostics;
  5. using System.Numerics;
  6. using System.Runtime.CompilerServices;
  7. using System.Runtime.InteropServices;
  8. using Internal.Runtime.CompilerServices;
  9. #if BIT64
  10. using nuint = System.UInt64;
  11. #else
  12. using nuint = System.UInt32;
  13. #endif
  14. namespace System
  15. {
  16. internal static partial class Marvin
  17. {
  18. /// <summary>
  19. /// Compute a Marvin hash and collapse it into a 32-bit hash.
  20. /// </summary>
  21. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  22. public static int ComputeHash32(ReadOnlySpan<byte> data, ulong seed) => ComputeHash32(ref MemoryMarshal.GetReference(data), (uint)data.Length, (uint)seed, (uint)(seed >> 32));
  23. /// <summary>
  24. /// Compute a Marvin hash and collapse it into a 32-bit hash.
  25. /// </summary>
  26. public static int ComputeHash32(ref byte data, uint count, uint p0, uint p1)
  27. {
  28. // Control flow of this method generally flows top-to-bottom, trying to
  29. // minimize the number of branches taken for large (>= 8 bytes, 4 chars) inputs.
  30. // If small inputs (< 8 bytes, 4 chars) are given, this jumps to a "small inputs"
  31. // handler at the end of the method.
  32. if (count < 8)
  33. {
  34. // We can't run the main loop, but we might still have 4 or more bytes available to us.
  35. // If so, jump to the 4 .. 7 bytes logic immediately after the main loop.
  36. if (count >= 4)
  37. {
  38. goto Between4And7BytesRemain;
  39. }
  40. else
  41. {
  42. goto InputTooSmallToEnterMainLoop;
  43. }
  44. }
  45. // Main loop - read 8 bytes at a time.
  46. // The block function is unrolled 2x in this loop.
  47. uint loopCount = count / 8;
  48. Debug.Assert(loopCount > 0, "Shouldn't reach this code path for small inputs.");
  49. do
  50. {
  51. // Most x86 processors have two dispatch ports for reads, so we can read 2x 32-bit
  52. // values in parallel. We opt for this instead of a single 64-bit read since the
  53. // typical use case for Marvin32 is computing String hash codes, and the particular
  54. // layout of String instances means the starting data is never 8-byte aligned when
  55. // running in a 64-bit process.
  56. p0 += Unsafe.ReadUnaligned<uint>(ref data);
  57. uint nextUInt32 = Unsafe.ReadUnaligned<uint>(ref Unsafe.AddByteOffset(ref data, 4));
  58. // One block round for each of the 32-bit integers we just read, 2x rounds total.
  59. Block(ref p0, ref p1);
  60. p0 += nextUInt32;
  61. Block(ref p0, ref p1);
  62. // Bump the data reference pointer and decrement the loop count.
  63. // Decrementing by 1 every time and comparing against zero allows the JIT to produce
  64. // better codegen compared to a standard 'for' loop with an incrementing counter.
  65. // Requires https://github.com/dotnet/coreclr/issues/7566 to be addressed first
  66. // before we can realize the full benefits of this.
  67. data = ref Unsafe.AddByteOffset(ref data, 8);
  68. } while (--loopCount > 0);
  69. // n.b. We've not been updating the original 'count' parameter, so its actual value is
  70. // still the original data length. However, we can still rely on its least significant
  71. // 3 bits to tell us how much data remains (0 .. 7 bytes) after the loop above is
  72. // completed.
  73. if ((count & 0b_0100) == 0)
  74. {
  75. goto DoFinalPartialRead;
  76. }
  77. Between4And7BytesRemain:
  78. // If after finishing the main loop we still have 4 or more leftover bytes, or if we had
  79. // 4 .. 7 bytes to begin with and couldn't enter the loop in the first place, we need to
  80. // consume 4 bytes immediately and send them through one round of the block function.
  81. Debug.Assert(count >= 4, "Only should've gotten here if the original count was >= 4.");
  82. p0 += Unsafe.ReadUnaligned<uint>(ref data);
  83. Block(ref p0, ref p1);
  84. DoFinalPartialRead:
  85. // Finally, we have 0 .. 3 bytes leftover. Since we know the original data length was at
  86. // least 4 bytes (smaller lengths are handled at the end of this routine), we can safely
  87. // read the 4 bytes at the end of the buffer without reading past the beginning of the
  88. // original buffer. This necessarily means the data we're about to read will overlap with
  89. // some data we've already processed, but we can handle that below.
  90. Debug.Assert(count >= 4, "Only should've gotten here if the original count was >= 4.");
  91. // Read the last 4 bytes of the buffer.
  92. uint partialResult = Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref Unsafe.AddByteOffset(ref data, (nuint)count & 7), -4));
  93. // The 'partialResult' local above contains any data we have yet to read, plus some number
  94. // of bytes which we've already read from the buffer. An example of this is given below
  95. // for little-endian architectures. In this table, AA BB CC are the bytes which we still
  96. // need to consume, and ## are bytes which we want to throw away since we've already
  97. // consumed them as part of a previous read.
  98. //
  99. // (partialResult contains) (we want it to contain)
  100. // count mod 4 = 0 -> [ ## ## ## ## | ] -> 0x####_#### -> 0x0000_0080
  101. // count mod 4 = 1 -> [ ## ## ## ## | AA ] -> 0xAA##_#### -> 0x0000_80AA
  102. // count mod 4 = 2 -> [ ## ## ## ## | AA BB ] -> 0xBBAA_#### -> 0x0080_BBAA
  103. // count mod 4 = 3 -> [ ## ## ## ## | AA BB CC ] -> 0xCCBB_AA## -> 0x80CC_BBAA
  104. count = ~count << 3;
  105. if (BitConverter.IsLittleEndian)
  106. {
  107. partialResult >>= 8; // make some room for the 0x80 byte
  108. partialResult |= 0x8000_0000u; // put the 0x80 byte at the beginning
  109. partialResult >>= (int)count & 0x1F; // shift out all previously consumed bytes
  110. }
  111. else
  112. {
  113. partialResult <<= 8; // make some room for the 0x80 byte
  114. partialResult |= 0x80u; // put the 0x80 byte at the end
  115. partialResult <<= (int)count & 0x1F; // shift out all previously consumed bytes
  116. }
  117. DoFinalRoundsAndReturn:
  118. // Now that we've computed the final partial result, merge it in and run two rounds of
  119. // the block function to finish out the Marvin algorithm.
  120. p0 += partialResult;
  121. Block(ref p0, ref p1);
  122. Block(ref p0, ref p1);
  123. return (int)(p1 ^ p0);
  124. InputTooSmallToEnterMainLoop:
  125. // We had only 0 .. 3 bytes to begin with, so we can't perform any 32-bit reads.
  126. // This means that we're going to be building up the final result right away and
  127. // will only ever run two rounds total of the block function. Let's initialize
  128. // the partial result to "no data".
  129. if (BitConverter.IsLittleEndian)
  130. {
  131. partialResult = 0x80u;
  132. }
  133. else
  134. {
  135. partialResult = 0x80000000u;
  136. }
  137. if ((count & 0b_0001) != 0)
  138. {
  139. // If the buffer is 1 or 3 bytes in length, let's read a single byte now
  140. // and merge it into our partial result. This will result in partialResult
  141. // having one of the two values below, where AA BB CC are the buffer bytes.
  142. //
  143. // (little-endian / big-endian)
  144. // [ AA ] -> 0x0000_80AA / 0xAA80_0000
  145. // [ AA BB CC ] -> 0x0000_80CC / 0xCC80_0000
  146. partialResult = Unsafe.AddByteOffset(ref data, (nuint)count & 2);
  147. if (BitConverter.IsLittleEndian)
  148. {
  149. partialResult |= 0x8000;
  150. }
  151. else
  152. {
  153. partialResult <<= 24;
  154. partialResult |= 0x800000u;
  155. }
  156. }
  157. if ((count & 0b_0010) != 0)
  158. {
  159. // If the buffer is 2 or 3 bytes in length, let's read a single ushort now
  160. // and merge it into the partial result. This will result in partialResult
  161. // having one of the two values below, where AA BB CC are the buffer bytes.
  162. //
  163. // (little-endian / big-endian)
  164. // [ AA BB ] -> 0x0080_BBAA / 0xAABB_8000
  165. // [ AA BB CC ] -> 0x80CC_BBAA / 0xAABB_CC80 (carried over from above)
  166. if (BitConverter.IsLittleEndian)
  167. {
  168. partialResult <<= 16;
  169. partialResult |= (uint)Unsafe.ReadUnaligned<ushort>(ref data);
  170. }
  171. else
  172. {
  173. partialResult |= (uint)Unsafe.ReadUnaligned<ushort>(ref data);
  174. partialResult = BitOperations.RotateLeft(partialResult, 16);
  175. }
  176. }
  177. // Everything is consumed! Go perform the final rounds and return.
  178. goto DoFinalRoundsAndReturn;
  179. }
  180. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  181. private static void Block(ref uint rp0, ref uint rp1)
  182. {
  183. uint p0 = rp0;
  184. uint p1 = rp1;
  185. p1 ^= p0;
  186. p0 = BitOperations.RotateLeft(p0, 20);
  187. p0 += p1;
  188. p1 = BitOperations.RotateLeft(p1, 9);
  189. p1 ^= p0;
  190. p0 = BitOperations.RotateLeft(p0, 27);
  191. p0 += p1;
  192. p1 = BitOperations.RotateLeft(p1, 19);
  193. rp0 = p0;
  194. rp1 = p1;
  195. }
  196. public static ulong DefaultSeed { get; } = GenerateSeed();
  197. private static unsafe ulong GenerateSeed()
  198. {
  199. ulong seed;
  200. Interop.GetRandomBytes((byte*)&seed, sizeof(ulong));
  201. return seed;
  202. }
  203. }
  204. }