This commit is contained in:
2026-11-24 15:51:02 +01:00
parent cca4d73e41
commit f4aa17114a
22092 changed files with 5042406 additions and 0 deletions
@@ -0,0 +1,285 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// Ported from dotnet/runtime (release/9.0):
// src/libraries/System.IO.Hashing/src/System/IO/Hashing/NonCryptographicHashAlgorithm.cs
// Adapted for the Unity editor (Mono, netstandard2.1 API surface):
// - Removed async methods (AppendAsync, WriteAsync, BeginWrite, EndWrite).
// - Removed #if NET specific overloads (Write(ReadOnlySpan<byte>), etc.).
// - Replaced SR resource strings with inline constants.
// - Removed [DoesNotReturn] and other .NET-specific attributes.
// - Removed EditorBrowsable/Obsolete GetHashCode override (not needed for internal use).
using System;
using System.Diagnostics;
using System.IO;
namespace Unity.PlasticSCM.Editor.Hashing
{
/// <summary>
/// Represents a non-cryptographic hash algorithm.
/// </summary>
internal abstract class NonCryptographicHashAlgorithm
{
/// <summary>
/// Gets the number of bytes produced from this hash algorithm.
/// </summary>
/// <value>The number of bytes produced from this hash algorithm.</value>
public int HashLengthInBytes { get; }
/// <summary>
/// Called from constructors in derived classes to initialize the
/// <see cref="NonCryptographicHashAlgorithm"/> class.
/// </summary>
/// <param name="hashLengthInBytes">
/// The number of bytes produced from this hash algorithm.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="hashLengthInBytes"/> is less than 1.
/// </exception>
protected NonCryptographicHashAlgorithm(int hashLengthInBytes)
{
if (hashLengthInBytes < 1)
throw new ArgumentOutOfRangeException(nameof(hashLengthInBytes));
HashLengthInBytes = hashLengthInBytes;
}
/// <summary>
/// When overridden in a derived class,
/// appends the contents of <paramref name="source"/> to the data already
/// processed for the current hash computation.
/// </summary>
/// <param name="source">The data to process.</param>
public abstract void Append(ReadOnlySpan<byte> source);
/// <summary>
/// When overridden in a derived class,
/// resets the hash computation to the initial state.
/// </summary>
public abstract void Reset();
/// <summary>
/// When overridden in a derived class,
/// writes the computed hash value to <paramref name="destination"/>
/// without modifying accumulated state.
/// </summary>
/// <param name="destination">The buffer that receives the computed hash value.</param>
protected abstract void GetCurrentHashCore(Span<byte> destination);
/// <summary>
/// Appends the contents of <paramref name="source"/> to the data already
/// processed for the current hash computation.
/// </summary>
/// <param name="source">The data to process.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="source"/> is <see langword="null"/>.
/// </exception>
public void Append(byte[] source)
{
if (source is null)
throw new ArgumentNullException(nameof(source));
Append(new ReadOnlySpan<byte>(source));
}
/// <summary>
/// Appends the contents of <paramref name="stream"/> to the data already
/// processed for the current hash computation.
/// </summary>
/// <param name="stream">The data to process.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="stream"/> is <see langword="null"/>.
/// </exception>
public void Append(Stream stream)
{
if (stream is null)
throw new ArgumentNullException(nameof(stream));
stream.CopyTo(new CopyToDestinationStream(this));
}
/// <summary>
/// Gets the current computed hash value without modifying accumulated state.
/// </summary>
/// <returns>
/// The hash value for the data already provided.
/// </returns>
public byte[] GetCurrentHash()
{
byte[] ret = new byte[HashLengthInBytes];
GetCurrentHashCore(ret);
return ret;
}
/// <summary>
/// Attempts to write the computed hash value to <paramref name="destination"/>
/// without modifying accumulated state.
/// </summary>
/// <param name="destination">The buffer that receives the computed hash value.</param>
/// <param name="bytesWritten">
/// On success, receives the number of bytes written to <paramref name="destination"/>.
/// </param>
/// <returns>
/// <see langword="true"/> if <paramref name="destination"/> is long enough to receive
/// the computed hash value; otherwise, <see langword="false"/>.
/// </returns>
public bool TryGetCurrentHash(Span<byte> destination, out int bytesWritten)
{
if (destination.Length < HashLengthInBytes)
{
bytesWritten = 0;
return false;
}
GetCurrentHashCore(destination.Slice(0, HashLengthInBytes));
bytesWritten = HashLengthInBytes;
return true;
}
/// <summary>
/// Writes the computed hash value to <paramref name="destination"/>
/// without modifying accumulated state.
/// </summary>
/// <param name="destination">The buffer that receives the computed hash value.</param>
/// <returns>
/// The number of bytes written to <paramref name="destination"/>,
/// which is always <see cref="HashLengthInBytes"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="destination"/> is shorter than <see cref="HashLengthInBytes"/>.
/// </exception>
public int GetCurrentHash(Span<byte> destination)
{
if (destination.Length < HashLengthInBytes)
ThrowDestinationTooShort();
GetCurrentHashCore(destination.Slice(0, HashLengthInBytes));
return HashLengthInBytes;
}
/// <summary>
/// Gets the current computed hash value and clears the accumulated state.
/// </summary>
/// <returns>
/// The hash value for the data already provided.
/// </returns>
public byte[] GetHashAndReset()
{
byte[] ret = new byte[HashLengthInBytes];
GetHashAndResetCore(ret);
return ret;
}
/// <summary>
/// Attempts to write the computed hash value to <paramref name="destination"/>.
/// If successful, clears the accumulated state.
/// </summary>
/// <param name="destination">The buffer that receives the computed hash value.</param>
/// <param name="bytesWritten">
/// On success, receives the number of bytes written to <paramref name="destination"/>.
/// </param>
/// <returns>
/// <see langword="true"/> and clears the accumulated state
/// if <paramref name="destination"/> is long enough to receive
/// the computed hash value; otherwise, <see langword="false"/>.
/// </returns>
public bool TryGetHashAndReset(Span<byte> destination, out int bytesWritten)
{
if (destination.Length < HashLengthInBytes)
{
bytesWritten = 0;
return false;
}
GetHashAndResetCore(destination.Slice(0, HashLengthInBytes));
bytesWritten = HashLengthInBytes;
return true;
}
/// <summary>
/// Writes the computed hash value to <paramref name="destination"/>
/// then clears the accumulated state.
/// </summary>
/// <param name="destination">The buffer that receives the computed hash value.</param>
/// <returns>
/// The number of bytes written to <paramref name="destination"/>,
/// which is always <see cref="HashLengthInBytes"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// <paramref name="destination"/> is shorter than <see cref="HashLengthInBytes"/>.
/// </exception>
public int GetHashAndReset(Span<byte> destination)
{
if (destination.Length < HashLengthInBytes)
ThrowDestinationTooShort();
GetHashAndResetCore(destination.Slice(0, HashLengthInBytes));
return HashLengthInBytes;
}
/// <summary>
/// Writes the computed hash value to <paramref name="destination"/>
/// then clears the accumulated state.
/// </summary>
/// <param name="destination">The buffer that receives the computed hash value.</param>
protected virtual void GetHashAndResetCore(Span<byte> destination)
{
Debug.Assert(destination.Length == HashLengthInBytes);
GetCurrentHashCore(destination);
Reset();
}
private protected static void ThrowDestinationTooShort() =>
throw new ArgumentException("Destination is too short.", "destination");
/// <summary>Stream-derived type used to support copying from a source stream to this instance via CopyTo.</summary>
private sealed class CopyToDestinationStream : Stream
{
private readonly NonCryptographicHashAlgorithm mHash;
public CopyToDestinationStream(NonCryptographicHashAlgorithm hash)
{
mHash = hash;
}
public override bool CanWrite => true;
public override void Write(byte[] buffer, int offset, int count)
{
mHash.Append(new ReadOnlySpan<byte>(buffer, offset, count));
}
public override void WriteByte(byte value)
{
Span<byte> span = stackalloc byte[1];
span[0] = value;
mHash.Append(span);
}
public override void Flush() { }
public override bool CanRead => false;
public override bool CanSeek => false;
public override long Length => throw new NotSupportedException();
public override long Position
{
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
public override int Read(byte[] buffer, int offset, int count) =>
throw new NotSupportedException();
public override long Seek(long offset, SeekOrigin origin) =>
throw new NotSupportedException();
public override void SetLength(long value) =>
throw new NotSupportedException();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: d1c8ba8f08844ab3ad8c0ef45536941e
@@ -0,0 +1,429 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// Based on the XXH128 implementation from https://github.com/Cyan4973/xxHash.
// Ported from dotnet/runtime (release/9.0):
// src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash128.cs
// Adapted for the Unity editor (Mono, netstandard2.1 API surface):
// - Inherits from the ported NonCryptographicHashAlgorithm base class.
// - UInt128-based members (#if NET) removed.
// - System.Runtime.CompilerServices.Unsafe and System.Numerics.BitOperations
// usages replaced to avoid extra assembly dependencies.
// Produces the same digests, in the same (big-endian) byte order, as
// System.IO.Hashing.XxHash128 - the implementation used by the rest of
// the Plastic SCM clients.
using System;
using System.Buffers.Binary;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using static Unity.PlasticSCM.Editor.Hashing.XxHashShared;
namespace Unity.PlasticSCM.Editor.Hashing
{
/// <summary>Provides an implementation of the XXH128 hash algorithm for generating a 128-bit hash.</summary>
/// <remarks>
/// For methods that persist the computed numerical hash value as bytes,
/// the value is written in the Big Endian byte order.
/// </remarks>
internal sealed unsafe class XxHash128 : NonCryptographicHashAlgorithm
{
/// <summary>XXH128 produces 16-byte hashes.</summary>
private new const int HashLengthInBytes = 16;
private State _state;
/// <summary>Initializes a new instance of the <see cref="XxHash128"/> class using the default seed value 0.</summary>
public XxHash128() : this(0)
{
}
/// <summary>Initializes a new instance of the <see cref="XxHash128"/> class using the specified seed.</summary>
public XxHash128(long seed) : base(HashLengthInBytes)
{
Initialize(ref _state, (ulong)seed);
}
/// <summary>Computes the XXH128 hash of the provided <paramref name="source"/> data.</summary>
/// <param name="source">The data to hash.</param>
/// <returns>The XXH128 128-bit hash code of the provided data.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
public static byte[] Hash(byte[] source) => Hash(source, seed: 0);
/// <summary>Computes the XXH128 hash of the provided data using the provided seed.</summary>
/// <param name="source">The data to hash.</param>
/// <param name="seed">The seed value for this hash computation.</param>
/// <returns>The XXH128 128-bit hash code of the provided data.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
public static byte[] Hash(byte[] source, long seed)
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
return Hash(new ReadOnlySpan<byte>(source), seed);
}
/// <summary>Computes the XXH128 hash of the provided <paramref name="source"/> data using the optionally provided <paramref name="seed"/>.</summary>
/// <param name="source">The data to hash.</param>
/// <param name="seed">The seed value for this hash computation. The default is zero.</param>
/// <returns>The XXH128 128-bit hash code of the provided data.</returns>
public static byte[] Hash(ReadOnlySpan<byte> source, long seed = 0)
{
byte[] result = new byte[HashLengthInBytes];
Hash(source, result, seed);
return result;
}
/// <summary>Computes the XXH128 hash of the provided <paramref name="source"/> data into the provided <paramref name="destination"/> using the optionally provided <paramref name="seed"/>.</summary>
/// <param name="source">The data to hash.</param>
/// <param name="destination">The buffer that receives the computed 128-bit hash code.</param>
/// <param name="seed">The seed value for this hash computation. The default is zero.</param>
/// <returns>The number of bytes written to <paramref name="destination"/>.</returns>
/// <exception cref="ArgumentException"><paramref name="destination"/> is shorter than <see cref="HashLengthInBytes"/> (16 bytes).</exception>
public static int Hash(ReadOnlySpan<byte> source, Span<byte> destination, long seed = 0)
{
if (!TryHash(source, destination, out int bytesWritten, seed))
{
ThrowDestinationTooShort();
}
return bytesWritten;
}
/// <summary>Attempts to compute the XXH128 hash of the provided <paramref name="source"/> data into the provided <paramref name="destination"/> using the optionally provided <paramref name="seed"/>.</summary>
/// <param name="source">The data to hash.</param>
/// <param name="destination">The buffer that receives the computed 128-bit hash code.</param>
/// <param name="bytesWritten">When this method returns, contains the number of bytes written to <paramref name="destination"/>.</param>
/// <param name="seed">The seed value for this hash computation. The default is zero.</param>
/// <returns><see langword="true"/> if <paramref name="destination"/> is long enough to receive the computed hash value (16 bytes); otherwise, <see langword="false"/>.</returns>
public static bool TryHash(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten, long seed = 0)
{
if (destination.Length >= sizeof(ulong) * 2)
{
Hash128 hash = HashToHash128(source, seed);
WriteBigEndian128(hash, destination);
bytesWritten = HashLengthInBytes;
return true;
}
bytesWritten = 0;
return false;
}
private static Hash128 HashToHash128(ReadOnlySpan<byte> source, long seed = 0)
{
uint length = (uint)source.Length;
fixed (byte* sourcePtr = &MemoryMarshal.GetReference(source))
{
if (length <= 16)
{
return HashLength0To16(sourcePtr, length, (ulong)seed);
}
if (length <= 128)
{
return HashLength17To128(sourcePtr, length, (ulong)seed);
}
if (length <= MidSizeMaxBytes)
{
return HashLength129To240(sourcePtr, length, (ulong)seed);
}
return HashLengthOver240(sourcePtr, length, (ulong)seed);
}
}
/// <summary>Resets the hash computation to the initial state.</summary>
public override void Reset()
{
XxHashShared.Reset(ref _state);
}
/// <summary>Appends the contents of <paramref name="source"/> to the data already processed for the current hash computation.</summary>
/// <param name="source">The data to process.</param>
public override void Append(ReadOnlySpan<byte> source)
{
XxHashShared.Append(ref _state, source);
}
/// <summary>Gets the current computed 128-bit hash value without modifying accumulated state.</summary>
/// <returns>The hash value for the data already provided, in Big Endian byte order.</returns>
public new byte[] GetCurrentHash()
{
byte[] result = new byte[HashLengthInBytes];
Hash128 current = GetCurrentHashAsHash128();
WriteBigEndian128(current, result);
return result;
}
/// <inheritdoc/>
protected override void GetCurrentHashCore(Span<byte> destination)
{
Hash128 current = GetCurrentHashAsHash128();
WriteBigEndian128(current, destination);
}
private Hash128 GetCurrentHashAsHash128()
{
Hash128 current;
if (_state.TotalLength > MidSizeMaxBytes)
{
// Digest on a local copy to ensure the accumulators remain unaltered.
ulong* accumulators = stackalloc ulong[AccumulatorCount];
CopyAccumulators(ref _state, accumulators);
fixed (byte* secret = _state.Secret)
{
DigestLong(ref _state, accumulators, secret);
current = new Hash128(
low64: MergeAccumulators(accumulators, secret + SecretMergeAccsStartBytes, _state.TotalLength * Prime64_1),
high64: MergeAccumulators(accumulators, secret + SecretLengthBytes - AccumulatorCount * sizeof(ulong) - SecretMergeAccsStartBytes, ~(_state.TotalLength * Prime64_2)));
}
}
else
{
fixed (byte* buffer = _state.Buffer)
{
current = HashToHash128(new ReadOnlySpan<byte>(buffer, (int)_state.TotalLength), (long)_state.Seed);
}
}
return current;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void WriteBigEndian128(in Hash128 hash, Span<byte> destination)
{
BinaryPrimitives.WriteUInt64BigEndian(destination, hash.High64);
BinaryPrimitives.WriteUInt64BigEndian(destination.Slice(sizeof(ulong)), hash.Low64);
}
private new static void ThrowDestinationTooShort() =>
throw new ArgumentException("Destination is too short.", "destination");
private static Hash128 HashLength0To16(byte* source, uint length, ulong seed)
{
if (length > 8)
{
return HashLength9To16(source, length, seed);
}
if (length >= 4)
{
return HashLength4To8(source, length, seed);
}
if (length != 0)
{
return HashLength1To3(source, length, seed);
}
const ulong BitFlipL = DefaultSecretUInt64_8 ^ DefaultSecretUInt64_9;
const ulong BitFlipH = DefaultSecretUInt64_10 ^ DefaultSecretUInt64_11;
return new Hash128(XxHash64.Avalanche(seed ^ BitFlipL), XxHash64.Avalanche(seed ^ BitFlipH));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Hash128 HashLength1To3(byte* source, uint length, ulong seed)
{
Debug.Assert(length >= 1 && length <= 3);
// When source.Length == 1, c1 == source[0], c2 == source[0], c3 == source[0]
// When source.Length == 2, c1 == source[0], c2 == source[1], c3 == source[1]
// When source.Length == 3, c1 == source[0], c2 == source[1], c3 == source[2]
byte c1 = *source;
byte c2 = source[length >> 1];
byte c3 = source[length - 1];
uint combinedl = ((uint)c1 << 16) | ((uint)c2 << 24) | c3 | (length << 8);
uint combinedh = RotateLeft(BinaryPrimitives.ReverseEndianness(combinedl), 13);
const uint SecretXorL = (unchecked((uint)DefaultSecretUInt64_0) ^ (uint)(DefaultSecretUInt64_0 >> 32));
const uint SecretXorH = (unchecked((uint)DefaultSecretUInt64_1) ^ (uint)(DefaultSecretUInt64_1 >> 32));
ulong bitflipl = SecretXorL + seed;
ulong bitfliph = SecretXorH - seed;
ulong keyedLo = combinedl ^ bitflipl;
ulong keyedHi = combinedh ^ bitfliph;
return new Hash128(XxHash64.Avalanche(keyedLo), XxHash64.Avalanche(keyedHi));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Hash128 HashLength4To8(byte* source, uint length, ulong seed)
{
Debug.Assert(length >= 4 && length <= 8);
seed ^= (ulong)BinaryPrimitives.ReverseEndianness((uint)seed) << 32;
uint inputLo = ReadUInt32LE(source);
uint inputHi = ReadUInt32LE(source + length - 4);
ulong input64 = inputLo + ((ulong)inputHi << 32);
ulong bitflip = (DefaultSecretUInt64_2 ^ DefaultSecretUInt64_3) + seed;
ulong keyed = input64 ^ bitflip;
ulong m128High = Multiply64To128(keyed, Prime64_1 + (length << 2), out ulong m128Low);
m128High += (m128Low << 1);
m128Low ^= (m128High >> 3);
m128Low = XorShift(m128Low, 35);
m128Low *= 0x9FB21C651E98DF25UL;
m128Low = XorShift(m128Low, 28);
m128High = Avalanche(m128High);
return new Hash128(m128Low, m128High);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Hash128 HashLength9To16(byte* source, uint length, ulong seed)
{
Debug.Assert(length >= 9 && length <= 16);
ulong bitflipl = (DefaultSecretUInt64_4 ^ DefaultSecretUInt64_5) - seed;
ulong bitfliph = (DefaultSecretUInt64_6 ^ DefaultSecretUInt64_7) + seed;
ulong inputLo = ReadUInt64LE(source);
ulong inputHi = ReadUInt64LE(source + length - 8);
ulong m128High = Multiply64To128(inputLo ^ inputHi ^ bitflipl, Prime64_1, out ulong m128Low);
m128Low += (ulong)(length - 1) << 54;
inputHi ^= bitfliph;
m128High += sizeof(void*) < sizeof(ulong) ?
(inputHi & 0xFFFFFFFF00000000UL) + Multiply32To64((uint)inputHi, Prime32_2) :
inputHi + Multiply32To64((uint)inputHi, Prime32_2 - 1);
m128Low ^= BinaryPrimitives.ReverseEndianness(m128High);
ulong h128High = Multiply64To128(m128Low, Prime64_2, out ulong h128Low);
h128High += m128High * (ulong)Prime64_2;
h128Low = Avalanche(h128Low);
h128High = Avalanche(h128High);
return new Hash128(h128Low, h128High);
}
private static Hash128 HashLength17To128(byte* source, uint length, ulong seed)
{
Debug.Assert(length >= 17 && length <= 128);
ulong accLow = length * Prime64_1;
ulong accHigh = 0;
switch ((length - 1) / 32)
{
default: // case 3
Mix32Bytes(ref accLow, ref accHigh, source + 48, source + length - 64, DefaultSecretUInt64_12, DefaultSecretUInt64_13, DefaultSecretUInt64_14, DefaultSecretUInt64_15, seed);
goto case 2;
case 2:
Mix32Bytes(ref accLow, ref accHigh, source + 32, source + length - 48, DefaultSecretUInt64_8, DefaultSecretUInt64_9, DefaultSecretUInt64_10, DefaultSecretUInt64_11, seed);
goto case 1;
case 1:
Mix32Bytes(ref accLow, ref accHigh, source + 16, source + length - 32, DefaultSecretUInt64_4, DefaultSecretUInt64_5, DefaultSecretUInt64_6, DefaultSecretUInt64_7, seed);
goto case 0;
case 0:
Mix32Bytes(ref accLow, ref accHigh, source, source + length - 16, DefaultSecretUInt64_0, DefaultSecretUInt64_1, DefaultSecretUInt64_2, DefaultSecretUInt64_3, seed);
break;
}
return AvalancheHash(accLow, accHigh, length, seed);
}
private static Hash128 HashLength129To240(byte* source, uint length, ulong seed)
{
Debug.Assert(length >= 129 && length <= 240);
ulong accLow = length * Prime64_1;
ulong accHigh = 0;
Mix32Bytes(ref accLow, ref accHigh, source + (32 * 0), source + (32 * 0) + 16, DefaultSecretUInt64_0, DefaultSecretUInt64_1, DefaultSecretUInt64_2, DefaultSecretUInt64_3, seed);
Mix32Bytes(ref accLow, ref accHigh, source + (32 * 1), source + (32 * 1) + 16, DefaultSecretUInt64_4, DefaultSecretUInt64_5, DefaultSecretUInt64_6, DefaultSecretUInt64_7, seed);
Mix32Bytes(ref accLow, ref accHigh, source + (32 * 2), source + (32 * 2) + 16, DefaultSecretUInt64_8, DefaultSecretUInt64_9, DefaultSecretUInt64_10, DefaultSecretUInt64_11, seed);
Mix32Bytes(ref accLow, ref accHigh, source + (32 * 3), source + (32 * 3) + 16, DefaultSecretUInt64_12, DefaultSecretUInt64_13, DefaultSecretUInt64_14, DefaultSecretUInt64_15, seed);
accLow = Avalanche(accLow);
accHigh = Avalanche(accHigh);
uint bound = ((length - (32 * 4)) / 32);
if (bound != 0)
{
Mix32Bytes(ref accLow, ref accHigh, source + (32 * 4), source + (32 * 4) + 16, DefaultSecret3UInt64_0, DefaultSecret3UInt64_1, DefaultSecret3UInt64_2, DefaultSecret3UInt64_3, seed);
if (bound >= 2)
{
Mix32Bytes(ref accLow, ref accHigh, source + (32 * 5), source + (32 * 5) + 16, DefaultSecret3UInt64_4, DefaultSecret3UInt64_5, DefaultSecret3UInt64_6, DefaultSecret3UInt64_7, seed);
if (bound == 3)
{
Mix32Bytes(ref accLow, ref accHigh, source + (32 * 6), source + (32 * 6) + 16, DefaultSecret3UInt64_8, DefaultSecret3UInt64_9, DefaultSecret3UInt64_10, DefaultSecret3UInt64_11, seed);
}
}
}
Mix32Bytes(ref accLow, ref accHigh, source + length - 16, source + length - 32, 0x4F0BC7C7BBDCF93F, 0x59B4CD4BE0518A1D, 0x7378D9C97E9FC831, 0xEBD33483ACC5EA64, 0 - seed);
return AvalancheHash(accLow, accHigh, length, seed);
}
private static Hash128 HashLengthOver240(byte* source, uint length, ulong seed)
{
Debug.Assert(length > 240);
fixed (byte* defaultSecret = &MemoryMarshal.GetReference(DefaultSecret))
{
byte* secret = defaultSecret;
if (seed != 0)
{
byte* customSecret = stackalloc byte[SecretLengthBytes];
DeriveSecretFromSeed(customSecret, seed);
secret = customSecret;
}
ulong* accumulators = stackalloc ulong[AccumulatorCount];
InitializeAccumulators(accumulators);
HashInternalLoop(accumulators, source, length, secret);
return new Hash128(
low64: MergeAccumulators(accumulators, secret + SecretMergeAccsStartBytes, length * Prime64_1),
high64: MergeAccumulators(accumulators, secret + SecretLengthBytes - AccumulatorCount * sizeof(ulong) - SecretMergeAccsStartBytes, ~(length * Prime64_2)));
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static Hash128 AvalancheHash(ulong accLow, ulong accHigh, uint length, ulong seed)
{
ulong h128Low = accLow + accHigh;
ulong h128High = (accLow * Prime64_1)
+ (accHigh * Prime64_4)
+ ((length - seed) * Prime64_2);
h128Low = Avalanche(h128Low);
h128High = 0ul - Avalanche(h128High);
return new Hash128(h128Low, h128High);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void Mix32Bytes(ref ulong accLow, ref ulong accHigh, byte* input1, byte* input2, ulong secret1, ulong secret2, ulong secret3, ulong secret4, ulong seed)
{
accLow += Mix16Bytes(input1, secret1, secret2, seed);
accLow ^= ReadUInt64LE(input2) + ReadUInt64LE(input2 + 8);
accHigh += Mix16Bytes(input2, secret3, secret4, seed);
accHigh ^= ReadUInt64LE(input1) + ReadUInt64LE(input1 + 8);
}
[DebuggerDisplay("Low64 = {" + nameof(Low64) + "}, High64 = {" + nameof(High64) + "}")]
private readonly struct Hash128
{
public readonly ulong Low64;
public readonly ulong High64;
public Hash128(ulong low64, ulong high64)
{
Low64 = low64;
High64 = high64;
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 318741862274d44d7a9e24a21a14fd8d
@@ -0,0 +1,23 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// Ported from dotnet/runtime (release/9.0):
// src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHash64.State.cs
// Only the Avalanche mixer required by XxHash128 is included. The XXH64
// primes match XxHashShared.Prime64_2/Prime64_3, so those constants are used.
namespace Unity.PlasticSCM.Editor.Hashing
{
internal static class XxHash64
{
internal static ulong Avalanche(ulong hash)
{
hash ^= hash >> 33;
hash *= XxHashShared.Prime64_2;
hash ^= hash >> 29;
hash *= XxHashShared.Prime64_3;
hash ^= hash >> 32;
return hash;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: d9f7fbcfec44541f38ad555a93fad564
@@ -0,0 +1,572 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// Ported from dotnet/runtime (release/9.0):
// src/libraries/System.IO.Hashing/src/System/IO/Hashing/XxHashShared.cs
// Adapted for the Unity editor (Mono, netstandard2.1 API surface):
// - SIMD intrinsics paths (#if NET) removed; the scalar fallbacks are kept.
// - System.Runtime.CompilerServices.Unsafe and System.Numerics.BitOperations
// usages replaced to avoid extra assembly dependencies.
using System;
using System.Buffers.Binary;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Unity.PlasticSCM.Editor.Hashing
{
/// <summary>Shared implementation of the XXH3 hash algorithm for the <see cref="XxHash128"/> version.</summary>
internal static unsafe class XxHashShared
{
public const int StripeLengthBytes = 64;
public const int SecretLengthBytes = 192;
public const int SecretSizeMin = 136;
public const int SecretLastAccStartBytes = 7;
public const int SecretConsumeRateBytes = 8;
public const int SecretMergeAccsStartBytes = 11;
public const int NumStripesPerBlock = (SecretLengthBytes - StripeLengthBytes) / SecretConsumeRateBytes;
public const int AccumulatorCount = StripeLengthBytes / sizeof(ulong);
public const int MidSizeMaxBytes = 240;
public const int InternalBufferStripes = InternalBufferLengthBytes / StripeLengthBytes;
public const int InternalBufferLengthBytes = 256;
/// <summary>The default secret for when no seed is provided.</summary>
/// <remarks>This is the same as a custom secret derived from a seed of 0.</remarks>
public static ReadOnlySpan<byte> DefaultSecret => new byte[]
{
0xb8, 0xfe, 0x6c, 0x39, 0x23, 0xa4, 0x4b, 0xbe, // DefaultSecretUInt64_0
0x7c, 0x01, 0x81, 0x2c, 0xf7, 0x21, 0xad, 0x1c, // DefaultSecretUInt64_1
0xde, 0xd4, 0x6d, 0xe9, 0x83, 0x90, 0x97, 0xdb, // DefaultSecretUInt64_2
0x72, 0x40, 0xa4, 0xa4, 0xb7, 0xb3, 0x67, 0x1f, // DefaultSecretUInt64_3
0xcb, 0x79, 0xe6, 0x4e, 0xcc, 0xc0, 0xe5, 0x78, // DefaultSecretUInt64_4
0x82, 0x5a, 0xd0, 0x7d, 0xcc, 0xff, 0x72, 0x21, // DefaultSecretUInt64_5
0xb8, 0x08, 0x46, 0x74, 0xf7, 0x43, 0x24, 0x8e, // DefaultSecretUInt64_6
0xe0, 0x35, 0x90, 0xe6, 0x81, 0x3a, 0x26, 0x4c, // DefaultSecretUInt64_7
0x3c, 0x28, 0x52, 0xbb, 0x91, 0xc3, 0x00, 0xcb, // DefaultSecretUInt64_8
0x88, 0xd0, 0x65, 0x8b, 0x1b, 0x53, 0x2e, 0xa3, // DefaultSecretUInt64_9
0x71, 0x64, 0x48, 0x97, 0xa2, 0x0d, 0xf9, 0x4e, // DefaultSecretUInt64_10
0x38, 0x19, 0xef, 0x46, 0xa9, 0xde, 0xac, 0xd8, // DefaultSecretUInt64_11
0xa8, 0xfa, 0x76, 0x3f, 0xe3, 0x9c, 0x34, 0x3f, // DefaultSecretUInt64_12
0xf9, 0xdc, 0xbb, 0xc7, 0xc7, 0x0b, 0x4f, 0x1d, // DefaultSecretUInt64_13
0x8a, 0x51, 0xe0, 0x4b, 0xcd, 0xb4, 0x59, 0x31, // DefaultSecretUInt64_14
0xc8, 0x9f, 0x7e, 0xc9, 0xd9, 0x78, 0x73, 0x64, // DefaultSecretUInt64_15
0xea, 0xc5, 0xac, 0x83, 0x34, 0xd3, 0xeb, 0xc3, // DefaultSecretUInt64_16
0xc5, 0x81, 0xa0, 0xff, 0xfa, 0x13, 0x63, 0xeb, // DefaultSecretUInt64_17
0x17, 0x0d, 0xdd, 0x51, 0xb7, 0xf0, 0xda, 0x49, // DefaultSecretUInt64_18
0xd3, 0x16, 0x55, 0x26, 0x29, 0xd4, 0x68, 0x9e, // DefaultSecretUInt64_19
0x2b, 0x16, 0xbe, 0x58, 0x7d, 0x47, 0xa1, 0xfc, // DefaultSecretUInt64_20
0x8f, 0xf8, 0xb8, 0xd1, 0x7a, 0xd0, 0x31, 0xce, // DefaultSecretUInt64_21
0x45, 0xcb, 0x3a, 0x8f, 0x95, 0x16, 0x04, 0x28, // DefaultSecretUInt64_22
0xaf, 0xd7, 0xfb, 0xca, 0xbb, 0x4b, 0x40, 0x7e, // DefaultSecretUInt64_23
};
// Cast of DefaultSecret byte[] => ulong[] (See above for the correspondence)
public const ulong DefaultSecretUInt64_0 = 0xBE4BA423396CFEB8;
public const ulong DefaultSecretUInt64_1 = 0x1CAD21F72C81017C;
public const ulong DefaultSecretUInt64_2 = 0xDB979083E96DD4DE;
public const ulong DefaultSecretUInt64_3 = 0x1F67B3B7A4A44072;
public const ulong DefaultSecretUInt64_4 = 0x78E5C0CC4EE679CB;
public const ulong DefaultSecretUInt64_5 = 0x2172FFCC7DD05A82;
public const ulong DefaultSecretUInt64_6 = 0x8E2443F7744608B8;
public const ulong DefaultSecretUInt64_7 = 0x4C263A81E69035E0;
public const ulong DefaultSecretUInt64_8 = 0xCB00C391BB52283C;
public const ulong DefaultSecretUInt64_9 = 0xA32E531B8B65D088;
public const ulong DefaultSecretUInt64_10 = 0x4EF90DA297486471;
public const ulong DefaultSecretUInt64_11 = 0xD8ACDEA946EF1938;
public const ulong DefaultSecretUInt64_12 = 0x3F349CE33F76FAA8;
public const ulong DefaultSecretUInt64_13 = 0x1D4F0BC7C7BBDCF9;
public const ulong DefaultSecretUInt64_14 = 0x3159B4CD4BE0518A;
public const ulong DefaultSecretUInt64_15 = 0x647378D9C97E9FC8;
// Cast of DefaultSecret offset by 3 bytes, byte[] => ulong[]
public const ulong DefaultSecret3UInt64_0 = 0x81017CBE4BA42339;
public const ulong DefaultSecret3UInt64_1 = 0x6DD4DE1CAD21F72C;
public const ulong DefaultSecret3UInt64_2 = 0xA44072DB979083E9;
public const ulong DefaultSecret3UInt64_3 = 0xE679CB1F67B3B7A4;
public const ulong DefaultSecret3UInt64_4 = 0xD05A8278E5C0CC4E;
public const ulong DefaultSecret3UInt64_5 = 0x4608B82172FFCC7D;
public const ulong DefaultSecret3UInt64_6 = 0x9035E08E2443F774;
public const ulong DefaultSecret3UInt64_7 = 0x52283C4C263A81E6;
public const ulong DefaultSecret3UInt64_8 = 0x65D088CB00C391BB;
public const ulong DefaultSecret3UInt64_9 = 0x486471A32E531B8B;
public const ulong DefaultSecret3UInt64_10 = 0xEF19384EF90DA297;
public const ulong DefaultSecret3UInt64_11 = 0x76FAA8D8ACDEA946;
public const ulong DefaultSecret3UInt64_12 = 0xBBDCF93F349CE33F;
public const ulong DefaultSecret3UInt64_13 = 0xE0518A1D4F0BC7C7;
public const ulong Prime64_1 = 0x9E3779B185EBCA87UL;
public const ulong Prime64_2 = 0xC2B2AE3D27D4EB4FUL;
public const ulong Prime64_3 = 0x165667B19E3779F9UL;
public const ulong Prime64_4 = 0x85EBCA77C2B2AE63UL;
public const ulong Prime64_5 = 0x27D4EB2F165667C5UL;
public const uint Prime32_1 = 0x9E3779B1U;
public const uint Prime32_2 = 0x85EBCA77U;
public const uint Prime32_3 = 0xC2B2AE3DU;
public const uint Prime32_4 = 0x27D4EB2FU;
public const uint Prime32_5 = 0x165667B1U;
#if DEBUG
static XxHashShared()
{
// Make sure DefaultSecret is the custom secret derived from a seed of 0.
byte* secret = stackalloc byte[SecretLengthBytes];
DeriveSecretFromSeed(secret, 0);
Debug.Assert(new Span<byte>(secret, SecretLengthBytes).SequenceEqual(DefaultSecret));
// Validate some relationships.
Debug.Assert(InternalBufferLengthBytes % StripeLengthBytes == 0);
ReadOnlySpan<ulong> defaultSecretUInt64 = MemoryMarshal.Cast<byte, ulong>(DefaultSecret);
Debug.Assert(ReadLE64(defaultSecretUInt64[0]) == DefaultSecretUInt64_0);
Debug.Assert(ReadLE64(defaultSecretUInt64[1]) == DefaultSecretUInt64_1);
Debug.Assert(ReadLE64(defaultSecretUInt64[2]) == DefaultSecretUInt64_2);
Debug.Assert(ReadLE64(defaultSecretUInt64[3]) == DefaultSecretUInt64_3);
Debug.Assert(ReadLE64(defaultSecretUInt64[4]) == DefaultSecretUInt64_4);
Debug.Assert(ReadLE64(defaultSecretUInt64[5]) == DefaultSecretUInt64_5);
Debug.Assert(ReadLE64(defaultSecretUInt64[6]) == DefaultSecretUInt64_6);
Debug.Assert(ReadLE64(defaultSecretUInt64[7]) == DefaultSecretUInt64_7);
Debug.Assert(ReadLE64(defaultSecretUInt64[8]) == DefaultSecretUInt64_8);
Debug.Assert(ReadLE64(defaultSecretUInt64[9]) == DefaultSecretUInt64_9);
Debug.Assert(ReadLE64(defaultSecretUInt64[10]) == DefaultSecretUInt64_10);
Debug.Assert(ReadLE64(defaultSecretUInt64[11]) == DefaultSecretUInt64_11);
Debug.Assert(ReadLE64(defaultSecretUInt64[12]) == DefaultSecretUInt64_12);
Debug.Assert(ReadLE64(defaultSecretUInt64[13]) == DefaultSecretUInt64_13);
Debug.Assert(ReadLE64(defaultSecretUInt64[14]) == DefaultSecretUInt64_14);
Debug.Assert(ReadLE64(defaultSecretUInt64[15]) == DefaultSecretUInt64_15);
ReadOnlySpan<ulong> defaultSecret3UInt64 = MemoryMarshal.Cast<byte, ulong>(DefaultSecret.Slice(3));
Debug.Assert(ReadLE64(defaultSecret3UInt64[0]) == DefaultSecret3UInt64_0);
Debug.Assert(ReadLE64(defaultSecret3UInt64[1]) == DefaultSecret3UInt64_1);
Debug.Assert(ReadLE64(defaultSecret3UInt64[2]) == DefaultSecret3UInt64_2);
Debug.Assert(ReadLE64(defaultSecret3UInt64[3]) == DefaultSecret3UInt64_3);
Debug.Assert(ReadLE64(defaultSecret3UInt64[4]) == DefaultSecret3UInt64_4);
Debug.Assert(ReadLE64(defaultSecret3UInt64[5]) == DefaultSecret3UInt64_5);
Debug.Assert(ReadLE64(defaultSecret3UInt64[6]) == DefaultSecret3UInt64_6);
Debug.Assert(ReadLE64(defaultSecret3UInt64[7]) == DefaultSecret3UInt64_7);
Debug.Assert(ReadLE64(defaultSecret3UInt64[8]) == DefaultSecret3UInt64_8);
Debug.Assert(ReadLE64(defaultSecret3UInt64[9]) == DefaultSecret3UInt64_9);
Debug.Assert(ReadLE64(defaultSecret3UInt64[10]) == DefaultSecret3UInt64_10);
Debug.Assert(ReadLE64(defaultSecret3UInt64[11]) == DefaultSecret3UInt64_11);
Debug.Assert(ReadLE64(defaultSecret3UInt64[12]) == DefaultSecret3UInt64_12);
Debug.Assert(ReadLE64(defaultSecret3UInt64[13]) == DefaultSecret3UInt64_13);
static ulong ReadLE64(ulong data) => BitConverter.IsLittleEndian ? data : BinaryPrimitives.ReverseEndianness(data);
}
#endif
public static void Initialize(ref State state, ulong seed)
{
state.Seed = (ulong)seed;
fixed (byte* secret = state.Secret)
{
if (seed == 0)
{
DefaultSecret.CopyTo(new Span<byte>(secret, SecretLengthBytes));
}
else
{
DeriveSecretFromSeed(secret, (ulong)seed);
}
}
Reset(ref state);
}
public static void Reset(ref State state)
{
state.BufferedCount = 0;
state.StripesProcessedInCurrentBlock = 0;
state.TotalLength = 0;
fixed (ulong* accumulators = state.Accumulators)
{
InitializeAccumulators(accumulators);
}
}
/// <summary>"This is a stronger avalanche, preferable when input has not been previously mixed."</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong Rrmxmx(ulong hash, uint length)
{
hash ^= RotateLeft(hash, 49) ^ RotateLeft(hash, 24);
hash *= 0x9FB21C651E98DF25;
hash ^= (hash >> 35) + length;
hash *= 0x9FB21C651E98DF25;
return XorShift(hash, 28);
}
public static void HashInternalLoop(ulong* accumulators, byte* source, uint length, byte* secret)
{
Debug.Assert(length > 240);
const int StripesPerBlock = (SecretLengthBytes - StripeLengthBytes) / SecretConsumeRateBytes;
const int BlockLen = StripeLengthBytes * StripesPerBlock;
int blocksNum = (int)((length - 1) / BlockLen);
Accumulate(accumulators, source, secret, StripesPerBlock, true, blocksNum);
int offset = BlockLen * blocksNum;
int stripesNumber = (int)((length - 1 - offset) / StripeLengthBytes);
Accumulate(accumulators, source + offset, secret, stripesNumber);
Accumulate512(accumulators, source + length - StripeLengthBytes, secret + (SecretLengthBytes - StripeLengthBytes - SecretLastAccStartBytes));
}
public static void ConsumeStripes(ulong* accumulators, ref ulong stripesSoFar, ulong stripesPerBlock, byte* source, ulong stripes, byte* secret)
{
Debug.Assert(stripes <= stripesPerBlock); // can handle max 1 scramble per invocation
Debug.Assert(stripesSoFar < stripesPerBlock);
ulong stripesToEndOfBlock = stripesPerBlock - stripesSoFar;
if (stripesToEndOfBlock <= stripes)
{
// need a scrambling operation
ulong stripesAfterBlock = stripes - stripesToEndOfBlock;
Accumulate(accumulators, source, secret + ((int)stripesSoFar * SecretConsumeRateBytes), (int)stripesToEndOfBlock);
ScrambleAccumulators(accumulators, secret + (SecretLengthBytes - StripeLengthBytes));
Accumulate(accumulators, source + ((int)stripesToEndOfBlock * StripeLengthBytes), secret, (int)stripesAfterBlock);
stripesSoFar = stripesAfterBlock;
}
else
{
Accumulate(accumulators, source, secret + ((int)stripesSoFar * SecretConsumeRateBytes), (int)stripes);
stripesSoFar += stripes;
}
}
public static void Append(ref State state, ReadOnlySpan<byte> source)
{
Debug.Assert(state.BufferedCount <= InternalBufferLengthBytes);
state.TotalLength += (uint)source.Length;
fixed (byte* buffer = state.Buffer)
{
// Small input: just copy the data to the buffer.
if (source.Length <= InternalBufferLengthBytes - state.BufferedCount)
{
source.CopyTo(new Span<byte>(buffer + state.BufferedCount, source.Length));
state.BufferedCount += (uint)source.Length;
return;
}
fixed (byte* secret = state.Secret)
fixed (ulong* accumulators = state.Accumulators)
fixed (byte* sourcePtr = &MemoryMarshal.GetReference(source))
{
// Internal buffer is partially filled (always, except at beginning). Complete it, then consume it.
int sourceIndex = 0;
if (state.BufferedCount != 0)
{
int loadSize = InternalBufferLengthBytes - (int)state.BufferedCount;
source.Slice(0, loadSize).CopyTo(new Span<byte>(buffer + state.BufferedCount, loadSize));
sourceIndex = loadSize;
ConsumeStripes(accumulators, ref state.StripesProcessedInCurrentBlock, NumStripesPerBlock, buffer, InternalBufferStripes, secret);
state.BufferedCount = 0;
}
Debug.Assert(sourceIndex < source.Length);
// Large input to consume: ingest per full block.
if (source.Length - sourceIndex > NumStripesPerBlock * StripeLengthBytes)
{
ulong stripes = (ulong)(source.Length - sourceIndex - 1) / StripeLengthBytes;
Debug.Assert(NumStripesPerBlock >= state.StripesProcessedInCurrentBlock);
// Join to current block's end.
ulong stripesToEnd = NumStripesPerBlock - state.StripesProcessedInCurrentBlock;
Debug.Assert(stripesToEnd <= stripes);
Accumulate(accumulators, sourcePtr + sourceIndex, secret + ((int)state.StripesProcessedInCurrentBlock * SecretConsumeRateBytes), (int)stripesToEnd);
ScrambleAccumulators(accumulators, secret + (SecretLengthBytes - StripeLengthBytes));
state.StripesProcessedInCurrentBlock = 0;
sourceIndex += (int)stripesToEnd * StripeLengthBytes;
stripes -= stripesToEnd;
// Consume entire blocks.
while (stripes >= NumStripesPerBlock)
{
Accumulate(accumulators, sourcePtr + sourceIndex, secret, NumStripesPerBlock);
ScrambleAccumulators(accumulators, secret + (SecretLengthBytes - StripeLengthBytes));
sourceIndex += NumStripesPerBlock * StripeLengthBytes;
stripes -= NumStripesPerBlock;
}
// Consume complete stripes in the last partial block.
Accumulate(accumulators, sourcePtr + sourceIndex, secret, (int)stripes);
sourceIndex += (int)stripes * StripeLengthBytes;
Debug.Assert(sourceIndex < source.Length); // at least some bytes left
state.StripesProcessedInCurrentBlock = stripes;
// Copy the last stripe into the end of the buffer so it is available to GetCurrentHashCore when processing the "stripe from the end".
source.Slice(sourceIndex - StripeLengthBytes, StripeLengthBytes).CopyTo(new Span<byte>(buffer + InternalBufferLengthBytes - StripeLengthBytes, StripeLengthBytes));
}
else if (source.Length - sourceIndex > InternalBufferLengthBytes)
{
// Content to consume <= block size. Consume source by a multiple of internal buffer size.
do
{
ConsumeStripes(accumulators, ref state.StripesProcessedInCurrentBlock, NumStripesPerBlock, sourcePtr + sourceIndex, InternalBufferStripes, secret);
sourceIndex += InternalBufferLengthBytes;
}
while (source.Length - sourceIndex > InternalBufferLengthBytes);
// Copy the last stripe into the end of the buffer so it is available to GetCurrentHashCore when processing the "stripe from the end".
source.Slice(sourceIndex - StripeLengthBytes, StripeLengthBytes).CopyTo(new Span<byte>(buffer + InternalBufferLengthBytes - StripeLengthBytes, StripeLengthBytes));
}
// Buffer the remaining input.
Span<byte> remaining = new Span<byte>(buffer, source.Length - sourceIndex);
Debug.Assert(sourceIndex < source.Length);
Debug.Assert(remaining.Length <= InternalBufferLengthBytes);
Debug.Assert(state.BufferedCount == 0);
source.Slice(sourceIndex).CopyTo(remaining);
state.BufferedCount = (uint)remaining.Length;
}
}
}
public static void CopyAccumulators(ref State state, ulong* accumulators)
{
fixed (ulong* stateAccumulators = state.Accumulators)
{
for (int i = 0; i < 8; i++)
{
accumulators[i] = stateAccumulators[i];
}
}
}
public static void DigestLong(ref State state, ulong* accumulators, byte* secret)
{
Debug.Assert(state.BufferedCount > 0);
fixed (byte* buffer = state.Buffer)
{
byte* accumulateData;
if (state.BufferedCount >= StripeLengthBytes)
{
uint stripes = (state.BufferedCount - 1) / StripeLengthBytes;
ulong stripesSoFar = state.StripesProcessedInCurrentBlock;
ConsumeStripes(accumulators, ref stripesSoFar, NumStripesPerBlock, buffer, stripes, secret);
accumulateData = buffer + state.BufferedCount - StripeLengthBytes;
}
else
{
byte* lastStripe = stackalloc byte[StripeLengthBytes];
int catchupSize = StripeLengthBytes - (int)state.BufferedCount;
new ReadOnlySpan<byte>(buffer + InternalBufferLengthBytes - catchupSize, catchupSize).CopyTo(new Span<byte>(lastStripe, StripeLengthBytes));
new ReadOnlySpan<byte>(buffer, (int)state.BufferedCount).CopyTo(new Span<byte>(lastStripe + catchupSize, (int)state.BufferedCount));
accumulateData = lastStripe;
}
Accumulate512(accumulators, accumulateData, secret + (SecretLengthBytes - StripeLengthBytes - SecretLastAccStartBytes));
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void InitializeAccumulators(ulong* accumulators)
{
accumulators[0] = Prime32_3;
accumulators[1] = Prime64_1;
accumulators[2] = Prime64_2;
accumulators[3] = Prime64_3;
accumulators[4] = Prime64_4;
accumulators[5] = Prime32_2;
accumulators[6] = Prime64_5;
accumulators[7] = Prime32_1;
}
public static ulong MergeAccumulators(ulong* accumulators, byte* secret, ulong start)
{
ulong result64 = start;
result64 += Multiply64To128ThenFold(accumulators[0] ^ ReadUInt64LE(secret), accumulators[1] ^ ReadUInt64LE(secret + 8));
result64 += Multiply64To128ThenFold(accumulators[2] ^ ReadUInt64LE(secret + 16), accumulators[3] ^ ReadUInt64LE(secret + 24));
result64 += Multiply64To128ThenFold(accumulators[4] ^ ReadUInt64LE(secret + 32), accumulators[5] ^ ReadUInt64LE(secret + 40));
result64 += Multiply64To128ThenFold(accumulators[6] ^ ReadUInt64LE(secret + 48), accumulators[7] ^ ReadUInt64LE(secret + 56));
return Avalanche(result64);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong Mix16Bytes(byte* source, ulong secretLow, ulong secretHigh, ulong seed) =>
Multiply64To128ThenFold(
ReadUInt64LE(source) ^ (secretLow + seed),
ReadUInt64LE(source + sizeof(ulong)) ^ (secretHigh - seed));
/// <summary>Calculates a 32-bit to 64-bit long multiply.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong Multiply32To64(uint v1, uint v2) => (ulong)v1 * v2;
/// <summary>"This is a fast avalanche stage, suitable when input bits are already partially mixed."</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong Avalanche(ulong hash)
{
hash = XorShift(hash, 37);
hash *= 0x165667919E3779F9;
hash = XorShift(hash, 32);
return hash;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong Multiply64To128(ulong left, ulong right, out ulong lower)
{
ulong lowerLow = Multiply32To64((uint)left, (uint)right);
ulong higherLow = Multiply32To64((uint)(left >> 32), (uint)right);
ulong lowerHigh = Multiply32To64((uint)left, (uint)(right >> 32));
ulong higherHigh = Multiply32To64((uint)(left >> 32), (uint)(right >> 32));
ulong cross = (lowerLow >> 32) + (higherLow & 0xFFFFFFFF) + lowerHigh;
ulong upper = (higherLow >> 32) + (cross >> 32) + higherHigh;
lower = (cross << 32) | (lowerLow & 0xFFFFFFFF);
return upper;
}
/// <summary>Calculates a 64-bit to 128-bit multiply, then XOR folds it.</summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong Multiply64To128ThenFold(ulong left, ulong right)
{
ulong upper = Multiply64To128(left, right, out ulong lower);
return lower ^ upper;
}
public static void DeriveSecretFromSeed(byte* destinationSecret, ulong seed)
{
fixed (byte* defaultSecret = &MemoryMarshal.GetReference(DefaultSecret))
{
for (int i = 0; i < SecretLengthBytes; i += sizeof(ulong) * 2)
{
WriteUInt64LE(destinationSecret + i, ReadUInt64LE(defaultSecret + i) + seed);
WriteUInt64LE(destinationSecret + i + 8, ReadUInt64LE(defaultSecret + i + 8) - seed);
}
}
}
/// <summary>Optimized version of looping over <see cref="Accumulate512"/>.</summary>
[MethodImpl(MethodImplOptions.NoInlining)]
private static void Accumulate(ulong* accumulators, byte* source, byte* secret, int stripesToProcess, bool scramble = false, int blockCount = 1)
{
byte* secretForScramble = secret + (SecretLengthBytes - StripeLengthBytes);
for (int j = 0; j < blockCount; j++)
{
for (int i = 0; i < stripesToProcess; i++)
{
Accumulate512Inlined(accumulators, source, secret + (i * SecretConsumeRateBytes));
source += StripeLengthBytes;
}
if (scramble)
{
ScrambleAccumulators(accumulators, secretForScramble);
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void Accumulate512(ulong* accumulators, byte* source, byte* secret)
{
Accumulate512Inlined(accumulators, source, secret);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void Accumulate512Inlined(ulong* accumulators, byte* source, byte* secret)
{
for (int i = 0; i < AccumulatorCount; i++)
{
ulong sourceVal = ReadUInt64LE(source + (8 * i));
ulong sourceKey = sourceVal ^ ReadUInt64LE(secret + (i * 8));
accumulators[i ^ 1] += sourceVal; // swap adjacent lanes
accumulators[i] += Multiply32To64((uint)sourceKey, (uint)(sourceKey >> 32));
}
}
private static void ScrambleAccumulators(ulong* accumulators, byte* secret)
{
for (int i = 0; i < AccumulatorCount; i++)
{
ulong xorShift = XorShift(*accumulators, 47);
ulong xorWithKey = xorShift ^ ReadUInt64LE(secret);
*accumulators = xorWithKey * Prime32_1;
accumulators++;
secret += sizeof(ulong);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong XorShift(ulong value, int shift)
{
Debug.Assert(shift >= 0 && shift < 64);
return value ^ (value >> shift);
}
// Replacements for System.Numerics.BitOperations.RotateLeft, which is not
// available in the Unity editor's netstandard2.1 profile.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static uint RotateLeft(uint value, int offset) =>
(value << offset) | (value >> (32 - offset));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong RotateLeft(ulong value, int offset) =>
(value << offset) | (value >> (64 - offset));
// Plain pointer dereferences instead of Unsafe.ReadUnaligned/WriteUnaligned:
// every platform the Unity editor runs on (x64/arm64) supports unaligned
// scalar loads and stores, and this avoids a dependency on the
// System.Runtime.CompilerServices.Unsafe assembly.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static uint ReadUInt32LE(byte* data) =>
BitConverter.IsLittleEndian ?
*(uint*)data :
BinaryPrimitives.ReverseEndianness(*(uint*)data);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong ReadUInt64LE(byte* data) =>
BitConverter.IsLittleEndian ?
*(ulong*)data :
BinaryPrimitives.ReverseEndianness(*(ulong*)data);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void WriteUInt64LE(byte* data, ulong value)
{
if (!BitConverter.IsLittleEndian)
{
value = BinaryPrimitives.ReverseEndianness(value);
}
*(ulong*)data = value;
}
[StructLayout(LayoutKind.Auto)]
public struct State
{
/// <summary>The accumulators. Length is <see cref="AccumulatorCount"/>.</summary>
internal fixed ulong Accumulators[AccumulatorCount];
/// <summary>Used to store a custom secret generated from a seed. Length is <see cref="SecretLengthBytes"/>.</summary>
internal fixed byte Secret[SecretLengthBytes];
/// <summary>The internal buffer. Length is <see cref="InternalBufferLengthBytes"/>.</summary>
internal fixed byte Buffer[InternalBufferLengthBytes];
/// <summary>The amount of memory in <see cref="Buffer"/>.</summary>
internal uint BufferedCount;
/// <summary>Number of stripes processed in the current block.</summary>
internal ulong StripesProcessedInCurrentBlock;
/// <summary>Total length hashed.</summary>
internal ulong TotalLength;
/// <summary>The seed employed (possibly 0).</summary>
internal ulong Seed;
};
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8642afe1b2639478e91ff46ccf3145d3