Skip to content

Commit 4002a97

Browse files
Merge pull request #1201 from SixLabors/js/fast-hash
Add Hardware Accelerated Checksums
2 parents 17ec6ee + f6f6b51 commit 4002a97

17 files changed

+720
-306
lines changed

src/ImageSharp/Formats/Png/PngDecoderCore.cs

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,6 @@ internal sealed class PngDecoderCore
3030
/// </summary>
3131
private readonly byte[] buffer = new byte[4];
3232

33-
/// <summary>
34-
/// Reusable CRC for validating chunks.
35-
/// </summary>
36-
private readonly Crc32 crc = new Crc32();
37-
3833
/// <summary>
3934
/// The global configuration.
4035
/// </summary>
@@ -1159,18 +1154,17 @@ private bool TryReadChunk(out PngChunk chunk)
11591154
/// <param name="chunk">The <see cref="PngChunk"/>.</param>
11601155
private void ValidateChunk(in PngChunk chunk)
11611156
{
1162-
uint crc = this.ReadChunkCrc();
1157+
uint inputCrc = this.ReadChunkCrc();
11631158

11641159
if (chunk.IsCritical)
11651160
{
11661161
Span<byte> chunkType = stackalloc byte[4];
11671162
BinaryPrimitives.WriteUInt32BigEndian(chunkType, (uint)chunk.Type);
11681163

1169-
this.crc.Reset();
1170-
this.crc.Update(chunkType);
1171-
this.crc.Update(chunk.Data.GetSpan());
1164+
uint validCrc = Crc32.Calculate(chunkType);
1165+
validCrc = Crc32.Calculate(validCrc, chunk.Data.GetSpan());
11721166

1173-
if (this.crc.Value != crc)
1167+
if (validCrc != inputCrc)
11741168
{
11751169
string chunkTypeName = Encoding.ASCII.GetString(chunkType);
11761170
PngThrowHelper.ThrowInvalidChunkCrc(chunkTypeName);

src/ImageSharp/Formats/Png/PngEncoderCore.cs

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -47,11 +47,6 @@ internal sealed class PngEncoderCore : IDisposable
4747
/// </summary>
4848
private readonly byte[] chunkDataBuffer = new byte[16];
4949

50-
/// <summary>
51-
/// Reusable CRC for validating chunks.
52-
/// </summary>
53-
private readonly Crc32 crc = new Crc32();
54-
5550
/// <summary>
5651
/// The encoder options
5752
/// </summary>
@@ -1120,18 +1115,16 @@ private void WriteChunk(Stream stream, PngChunkType type, byte[] data, int offse
11201115

11211116
stream.Write(this.buffer, 0, 8);
11221117

1123-
this.crc.Reset();
1124-
1125-
this.crc.Update(this.buffer.AsSpan(4, 4)); // Write the type buffer
1118+
uint crc = Crc32.Calculate(this.buffer.AsSpan(4, 4)); // Write the type buffer
11261119

11271120
if (data != null && length > 0)
11281121
{
11291122
stream.Write(data, offset, length);
11301123

1131-
this.crc.Update(data.AsSpan(offset, length));
1124+
crc = Crc32.Calculate(crc, data.AsSpan(offset, length));
11321125
}
11331126

1134-
BinaryPrimitives.WriteUInt32BigEndian(this.buffer, (uint)this.crc.Value);
1127+
BinaryPrimitives.WriteUInt32BigEndian(this.buffer, crc);
11351128

11361129
stream.Write(this.buffer, 0, 4); // write the crc
11371130
}

0 commit comments

Comments
 (0)