< Summary

Line coverage
0%
Covered lines: 0
Uncovered lines: 110
Coverable lines: 110
Total lines: 276
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 24
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Cyclomatic complexity NPath complexity Sequence coverage
ComputeHash32(...)100%110%
ComputeHash32(...)0%20200%
Block(...)100%110%
GenerateSeed()0%440%
RotateLeft(...)100%110%

File(s)

C:\h\w\B31A098C\w\BB5A0A33\e\runtime-utils\Runner\runtime\src\libraries\System.Private.CoreLib\src\System\Marvin.cs

#LineLine coverage
 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
 4using System.Diagnostics;
 5using System.Numerics;
 6using System.Runtime.CompilerServices;
 7using System.Runtime.InteropServices;
 8
 9#if SYSTEM_PRIVATE_CORELIB
 10using static System.Numerics.BitOperations;
 11#else
 12using System.Security.Cryptography;
 13#endif
 14
 15namespace System
 16{
 17    internal static partial class Marvin
 18    {
 19        /// <summary>
 20        /// Compute a Marvin hash and collapse it into a 32-bit hash.
 21        /// </summary>
 22        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 023        public static int ComputeHash32(ReadOnlySpan<byte> data, ulong seed) => ComputeHash32(ref MemoryMarshal.GetRefer
 24
 25        /// <summary>
 26        /// Compute a Marvin hash and collapse it into a 32-bit hash.
 27        /// </summary>
 28        [MethodImpl(MethodImplOptions.NoInlining)]
 29        public static int ComputeHash32(ref byte data, uint count, uint p0, uint p1)
 030        {
 31            // Control flow of this method generally flows top-to-bottom, trying to
 32            // minimize the number of branches taken for large (>= 8 bytes, 4 chars) inputs.
 33            // If small inputs (< 8 bytes, 4 chars) are given, this jumps to a "small inputs"
 34            // handler at the end of the method.
 35
 036            if (count < 8)
 037            {
 38                // We can't run the main loop, but we might still have 4 or more bytes available to us.
 39                // If so, jump to the 4 .. 7 bytes logic immediately after the main loop.
 40
 041                if (count >= 4)
 042                {
 043                    goto Between4And7BytesRemain;
 44                }
 45                else
 046                {
 047                    goto InputTooSmallToEnterMainLoop;
 48                }
 49            }
 50
 51            // Main loop - read 8 bytes at a time.
 52            // The block function is unrolled 2x in this loop.
 53
 054            uint loopCount = count / 8;
 055            Debug.Assert(loopCount > 0, "Shouldn't reach this code path for small inputs.");
 56
 57            do
 058            {
 59                // Most x86 processors have two dispatch ports for reads, so we can read 2x 32-bit
 60                // values in parallel. We opt for this instead of a single 64-bit read since the
 61                // typical use case for Marvin32 is computing String hash codes, and the particular
 62                // layout of String instances means the starting data is never 8-byte aligned when
 63                // running in a 64-bit process.
 64
 065                p0 += Unsafe.ReadUnaligned<uint>(ref data);
 066                uint nextUInt32 = Unsafe.ReadUnaligned<uint>(ref Unsafe.AddByteOffset(ref data, 4));
 67
 68                // One block round for each of the 32-bit integers we just read, 2x rounds total.
 69
 070                Block(ref p0, ref p1);
 071                p0 += nextUInt32;
 072                Block(ref p0, ref p1);
 73
 74                // Bump the data reference pointer and decrement the loop count.
 75
 76                // Decrementing by 1 every time and comparing against zero allows the JIT to produce
 77                // better codegen compared to a standard 'for' loop with an incrementing counter.
 78                // Requires https://github.com/dotnet/runtime/issues/6794 to be addressed first
 79                // before we can realize the full benefits of this.
 80
 081                data = ref Unsafe.AddByteOffset(ref data, 8);
 082            } while (--loopCount > 0);
 83
 84            // n.b. We've not been updating the original 'count' parameter, so its actual value is
 85            // still the original data length. However, we can still rely on its least significant
 86            // 3 bits to tell us how much data remains (0 .. 7 bytes) after the loop above is
 87            // completed.
 88
 089            if ((count & 0b_0100) == 0)
 090            {
 091                goto DoFinalPartialRead;
 92            }
 93
 094        Between4And7BytesRemain:
 95
 96            // If after finishing the main loop we still have 4 or more leftover bytes, or if we had
 97            // 4 .. 7 bytes to begin with and couldn't enter the loop in the first place, we need to
 98            // consume 4 bytes immediately and send them through one round of the block function.
 99
 0100            Debug.Assert(count >= 4, "Only should've gotten here if the original count was >= 4.");
 101
 0102            p0 += Unsafe.ReadUnaligned<uint>(ref data);
 0103            Block(ref p0, ref p1);
 104
 0105        DoFinalPartialRead:
 106
 107            // Finally, we have 0 .. 3 bytes leftover. Since we know the original data length was at
 108            // least 4 bytes (smaller lengths are handled at the end of this routine), we can safely
 109            // read the 4 bytes at the end of the buffer without reading past the beginning of the
 110            // original buffer. This necessarily means the data we're about to read will overlap with
 111            // some data we've already processed, but we can handle that below.
 112
 0113            Debug.Assert(count >= 4, "Only should've gotten here if the original count was >= 4.");
 114
 115            // Read the last 4 bytes of the buffer.
 116
 0117            uint partialResult = Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref Unsafe.AddByteOffset(ref data, (nuint)cou
 118
 119            // The 'partialResult' local above contains any data we have yet to read, plus some number
 120            // of bytes which we've already read from the buffer. An example of this is given below
 121            // for little-endian architectures. In this table, AA BB CC are the bytes which we still
 122            // need to consume, and ## are bytes which we want to throw away since we've already
 123            // consumed them as part of a previous read.
 124            //
 125            //                                                    (partialResult contains)   (we want it to contain)
 126            // count mod 4 = 0 -> [ ## ## ## ## |             ] -> 0x####_####             -> 0x0000_0080
 127            // count mod 4 = 1 -> [ ## ## ## ## | AA          ] -> 0xAA##_####             -> 0x0000_80AA
 128            // count mod 4 = 2 -> [ ## ## ## ## | AA BB       ] -> 0xBBAA_####             -> 0x0080_BBAA
 129            // count mod 4 = 3 -> [ ## ## ## ## | AA BB CC    ] -> 0xCCBB_AA##             -> 0x80CC_BBAA
 130
 0131            count = ~count << 3;
 132
 0133            if (BitConverter.IsLittleEndian)
 0134            {
 0135                partialResult >>= 8; // make some room for the 0x80 byte
 0136                partialResult |= 0x8000_0000u; // put the 0x80 byte at the beginning
 0137                partialResult >>= (int)count & 0x1F; // shift out all previously consumed bytes
 0138            }
 139            else
 0140            {
 0141                partialResult <<= 8; // make some room for the 0x80 byte
 0142                partialResult |= 0x80u; // put the 0x80 byte at the end
 0143                partialResult <<= (int)count & 0x1F; // shift out all previously consumed bytes
 0144            }
 145
 0146        DoFinalRoundsAndReturn:
 147
 148            // Now that we've computed the final partial result, merge it in and run two rounds of
 149            // the block function to finish out the Marvin algorithm.
 150
 0151            p0 += partialResult;
 0152            Block(ref p0, ref p1);
 0153            Block(ref p0, ref p1);
 154
 0155            return (int)(p1 ^ p0);
 156
 0157        InputTooSmallToEnterMainLoop:
 158
 159            // We had only 0 .. 3 bytes to begin with, so we can't perform any 32-bit reads.
 160            // This means that we're going to be building up the final result right away and
 161            // will only ever run two rounds total of the block function. Let's initialize
 162            // the partial result to "no data".
 163
 0164            if (BitConverter.IsLittleEndian)
 0165            {
 0166                partialResult = 0x80u;
 0167            }
 168            else
 0169            {
 0170                partialResult = 0x80000000u;
 0171            }
 172
 0173            if ((count & 0b_0001) != 0)
 0174            {
 175                // If the buffer is 1 or 3 bytes in length, let's read a single byte now
 176                // and merge it into our partial result. This will result in partialResult
 177                // having one of the two values below, where AA BB CC are the buffer bytes.
 178                //
 179                //                  (little-endian / big-endian)
 180                // [ AA          ]  -> 0x0000_80AA / 0xAA80_0000
 181                // [ AA BB CC    ]  -> 0x0000_80CC / 0xCC80_0000
 182
 0183                partialResult = Unsafe.AddByteOffset(ref data, (nuint)count & 2);
 184
 0185                if (BitConverter.IsLittleEndian)
 0186                {
 0187                    partialResult |= 0x8000;
 0188                }
 189                else
 0190                {
 0191                    partialResult <<= 24;
 0192                    partialResult |= 0x800000u;
 0193                }
 0194            }
 195
 0196            if ((count & 0b_0010) != 0)
 0197            {
 198                // If the buffer is 2 or 3 bytes in length, let's read a single ushort now
 199                // and merge it into the partial result. This will result in partialResult
 200                // having one of the two values below, where AA BB CC are the buffer bytes.
 201                //
 202                //                  (little-endian / big-endian)
 203                // [ AA BB       ]  -> 0x0080_BBAA / 0xAABB_8000
 204                // [ AA BB CC    ]  -> 0x80CC_BBAA / 0xAABB_CC80 (carried over from above)
 205
 0206                if (BitConverter.IsLittleEndian)
 0207                {
 0208                    partialResult <<= 16;
 0209                    partialResult |= (uint)Unsafe.ReadUnaligned<ushort>(ref data);
 0210                }
 211                else
 0212                {
 0213                    partialResult |= (uint)Unsafe.ReadUnaligned<ushort>(ref data);
 0214                    partialResult = RotateLeft(partialResult, 16);
 0215                }
 0216            }
 217
 218            // Everything is consumed! Go perform the final rounds and return.
 219
 0220            goto DoFinalRoundsAndReturn;
 0221        }
 222
 223        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 224        private static void Block(ref uint rp0, ref uint rp1)
 0225        {
 226            // Intrinsified in mono interpreter
 0227            uint p0 = rp0;
 0228            uint p1 = rp1;
 229
 0230            p1 ^= p0;
 0231            p0 = RotateLeft(p0, 20);
 232
 0233            p0 += p1;
 0234            p1 = RotateLeft(p1, 9);
 235
 0236            p1 ^= p0;
 0237            p0 = RotateLeft(p0, 27);
 238
 0239            p0 += p1;
 0240            p1 = RotateLeft(p1, 19);
 241
 0242            rp0 = p0;
 0243            rp1 = p1;
 0244        }
 245
 0246        public static ulong DefaultSeed { get; } = GenerateSeed();
 247
 248        private static unsafe ulong GenerateSeed()
 0249        {
 250            ulong seed;
 251#if SYSTEM_PRIVATE_CORELIB
 252            Interop.GetRandomBytes((byte*)&seed, sizeof(ulong));
 253#else
 0254            byte[] seedBytes = new byte[sizeof(ulong)];
 0255            using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
 0256            {
 0257                rng.GetBytes(seedBytes);
 0258                fixed (byte* b = seedBytes)
 0259                {
 0260                    seed = *(ulong*)b;
 0261                }
 0262            }
 263#endif
 0264            return seed;
 0265        }
 266
 267#if !SYSTEM_PRIVATE_CORELIB
 268        [MethodImpl(MethodImplOptions.AggressiveInlining)]
 269        private static uint RotateLeft(uint value, int shift)
 0270        {
 271            // This is expected to be optimized into a single rol (or ror with negated shift value) instruction
 0272            return (value << shift) | (value >> (32 - shift));
 0273        }
 274#endif
 275    }
 276}