Skip to content

Commit

Permalink
Faster Keccak Xor (#7998)
Browse files Browse the repository at this point in the history
  • Loading branch information
benaadams authored Jan 3, 2025
1 parent 06deb02 commit 4e44559
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion src/Nethermind/Nethermind.Core/Crypto/KeccakHash.cs
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,8 @@ private static unsafe void XorVectors(Span<byte> state, ReadOnlySpan<byte> input
state256 = Vector512.Xor(state256, input256);
}

if (input.Length == vectorLength) return;

input = input[vectorLength..];
stateRef = ref Unsafe.Add(ref stateRef, vectorLength);
}
Expand All @@ -452,6 +454,8 @@ private static unsafe void XorVectors(Span<byte> state, ReadOnlySpan<byte> input
state256 = Vector256.Xor(state256, input256);
}

if (input.Length == vectorLength) return;

input = input[vectorLength..];
stateRef = ref Unsafe.Add(ref stateRef, vectorLength);
}
Expand All @@ -467,11 +471,32 @@ private static unsafe void XorVectors(Span<byte> state, ReadOnlySpan<byte> input
state128 = Vector128.Xor(state128, input128);
}

if (input.Length == vectorLength) return;

input = input[vectorLength..];
stateRef = ref Unsafe.Add(ref stateRef, vectorLength);
}

// Handle remaining elements
// As 25 longs in state, 1 more to process after the vector sizes
if (input.Length >= sizeof(ulong))
{
int ulongLength = input.Length - (int)((uint)input.Length % sizeof(ulong));
ref byte inputRef = ref MemoryMarshal.GetReference(input);
for (int i = 0; i < ulongLength; i += sizeof(ulong))
{
ref ulong state64 = ref Unsafe.As<byte, ulong>(ref Unsafe.Add(ref stateRef, i));
ulong input64 = Unsafe.As<byte, ulong>(ref Unsafe.Add(ref inputRef, i));
state64 ^= input64;
}

// Should exit here for 25 longs
if (input.Length == ulongLength) return;

input = input[ulongLength..];
stateRef = ref Unsafe.Add(ref stateRef, ulongLength);
}

// Handle remaining bytes
for (int i = 0; i < input.Length; i++)
{
Unsafe.Add(ref stateRef, i) ^= input[i];
Expand Down

0 comments on commit 4e44559

Please sign in to comment.