Skip to content

Commit

Permalink
Merge pull request #1201 from SixLabors/js/fast-hash
Browse files Browse the repository at this point in the history
Add Hardware Accelerated Checksums
  • Loading branch information
JimBobSquarePants authored May 18, 2020
2 parents 17ec6ee + f6f6b51 commit 4002a97
Show file tree
Hide file tree
Showing 17 changed files with 720 additions and 306 deletions.
14 changes: 4 additions & 10 deletions src/ImageSharp/Formats/Png/PngDecoderCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,6 @@ internal sealed class PngDecoderCore
/// </summary>
private readonly byte[] buffer = new byte[4];

/// <summary>
/// Reusable CRC for validating chunks.
/// </summary>
private readonly Crc32 crc = new Crc32();

/// <summary>
/// The global configuration.
/// </summary>
Expand Down Expand Up @@ -1159,18 +1154,17 @@ private bool TryReadChunk(out PngChunk chunk)
/// <param name="chunk">The <see cref="PngChunk"/>.</param>
private void ValidateChunk(in PngChunk chunk)
{
uint crc = this.ReadChunkCrc();
uint inputCrc = this.ReadChunkCrc();

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

this.crc.Reset();
this.crc.Update(chunkType);
this.crc.Update(chunk.Data.GetSpan());
uint validCrc = Crc32.Calculate(chunkType);
validCrc = Crc32.Calculate(validCrc, chunk.Data.GetSpan());

if (this.crc.Value != crc)
if (validCrc != inputCrc)
{
string chunkTypeName = Encoding.ASCII.GetString(chunkType);
PngThrowHelper.ThrowInvalidChunkCrc(chunkTypeName);
Expand Down
13 changes: 3 additions & 10 deletions src/ImageSharp/Formats/Png/PngEncoderCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,6 @@ internal sealed class PngEncoderCore : IDisposable
/// </summary>
private readonly byte[] chunkDataBuffer = new byte[16];

/// <summary>
/// Reusable CRC for validating chunks.
/// </summary>
private readonly Crc32 crc = new Crc32();

/// <summary>
/// The encoder options
/// </summary>
Expand Down Expand Up @@ -1120,18 +1115,16 @@ private void WriteChunk(Stream stream, PngChunkType type, byte[] data, int offse

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

this.crc.Reset();

this.crc.Update(this.buffer.AsSpan(4, 4)); // Write the type buffer
uint crc = Crc32.Calculate(this.buffer.AsSpan(4, 4)); // Write the type buffer

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

this.crc.Update(data.AsSpan(offset, length));
crc = Crc32.Calculate(crc, data.AsSpan(offset, length));
}

BinaryPrimitives.WriteUInt32BigEndian(this.buffer, (uint)this.crc.Value);
BinaryPrimitives.WriteUInt32BigEndian(this.buffer, crc);

stream.Write(this.buffer, 0, 4); // write the crc
}
Expand Down
Loading

0 comments on commit 4002a97

Please sign in to comment.