From 3fb692127a9c48b65c44d2c3e9c0c355c2a1d907 Mon Sep 17 00:00:00 2001 From: Jason Nelson Date: Thu, 22 Mar 2018 17:59:38 -0700 Subject: [PATCH] Eliminate buffer allocations for integers in PngEncoderCore.WriteChunk --- src/ImageSharp/Formats/Png/PngEncoderCore.cs | 49 ++++++-------------- 1 file changed, 14 insertions(+), 35 deletions(-) diff --git a/src/ImageSharp/Formats/Png/PngEncoderCore.cs b/src/ImageSharp/Formats/Png/PngEncoderCore.cs index c3750eb09f..333ed44e37 100644 --- a/src/ImageSharp/Formats/Png/PngEncoderCore.cs +++ b/src/ImageSharp/Formats/Png/PngEncoderCore.cs @@ -37,6 +37,11 @@ namespace SixLabors.ImageSharp.Formats.Png /// private readonly byte[] chunkDataBuffer = new byte[16]; + /// + /// Reusable buffer for writing int data. + /// + private readonly byte[] intBuffer = new byte[4]; + /// /// Reusable crc for validating chunks. /// @@ -245,34 +250,6 @@ namespace SixLabors.ImageSharp.Formats.Png this.paeth?.Dispose(); } - /// - /// Writes an integer to the stream. - /// - /// The containing image data. - /// The value to write. - private static void WriteInteger(Stream stream, int value) - { - byte[] buffer = new byte[4]; - - BinaryPrimitives.WriteInt32BigEndian(buffer, value); - - stream.Write(buffer, 0, 4); - } - - /// - /// Writes an unsigned integer to the stream. - /// - /// The containing image data. - /// The value to write. - private static void WriteInteger(Stream stream, uint value) - { - byte[] buffer = new byte[4]; - - BinaryPrimitives.WriteUInt32BigEndian(buffer, value); - - stream.Write(buffer, 0, 4); - } - /// /// Collects a row of grayscale pixels. /// @@ -658,7 +635,9 @@ namespace SixLabors.ImageSharp.Formats.Png /// The of the data to write. private void WriteChunk(Stream stream, string type, byte[] data, int offset, int length) { - WriteInteger(stream, length); + BinaryPrimitives.WriteInt32BigEndian(this.intBuffer, length); + + stream.Write(this.intBuffer, 0, 4); // write the length this.chunkTypeBuffer[0] = (byte)type[0]; this.chunkTypeBuffer[1] = (byte)type[1]; @@ -667,20 +646,20 @@ namespace SixLabors.ImageSharp.Formats.Png stream.Write(this.chunkTypeBuffer, 0, 4); - if (data != null) - { - stream.Write(data, offset, length); - } - this.crc.Reset(); + this.crc.Update(this.chunkTypeBuffer); if (data != null && length > 0) { + stream.Write(data, offset, length); + this.crc.Update(new ReadOnlySpan(data, offset, length)); } - WriteInteger(stream, (uint)this.crc.Value); + BinaryPrimitives.WriteUInt32BigEndian(this.intBuffer, (uint)this.crc.Value); + + stream.Write(intBuffer, 0, 4); // write the crc } } } \ No newline at end of file