From 5abcf2b1798c06c3eb3bdcbcffb687d23b25a401 Mon Sep 17 00:00:00 2001 From: Jason Nelson Date: Mon, 11 Jun 2018 12:00:25 -0700 Subject: [PATCH] Add stream extensions for Span --- .../Common/Extensions/StreamExtensions.cs | 29 ++++++++++++++++++- src/ImageSharp/Formats/Bmp/BmpEncoderCore.cs | 10 ++----- src/ImageSharp/Formats/Gif/LzwDecoder.cs | 5 +--- 3 files changed, 31 insertions(+), 13 deletions(-) diff --git a/src/ImageSharp/Common/Extensions/StreamExtensions.cs b/src/ImageSharp/Common/Extensions/StreamExtensions.cs index 7a9a34ac1..d11ba8ca5 100644 --- a/src/ImageSharp/Common/Extensions/StreamExtensions.cs +++ b/src/ImageSharp/Common/Extensions/StreamExtensions.cs @@ -1,7 +1,7 @@ // Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. -using System.Buffers; +using System; using System.IO; namespace SixLabors.ImageSharp @@ -11,6 +11,33 @@ namespace SixLabors.ImageSharp /// internal static class StreamExtensions { +#if NETCOREAPP2_1 + /// + /// Writes data from a stream into the provided buffer. + /// + /// The stream. + /// The buffer. + /// The offset within the buffer to begin writing. + /// The number of bytes to write to the stream. + public static void Write(this Stream stream, Span buffer, int offset, int count) + { + stream.Write(buffer.Slice(offset, count)); + } + + /// + /// Reads data from a stream into the provided buffer. + /// + /// The stream. + /// The buffer.. + /// The offset within the buffer where the bytes are read into. + /// The number of bytes, if available, to read. + /// The actual number of bytes read. + public static int Read(this Stream stream, Span buffer, int offset, int count) + { + return stream.Read(buffer.Slice(offset, count)); + } +#endif + /// /// Skips the number of bytes in the given stream. /// diff --git a/src/ImageSharp/Formats/Bmp/BmpEncoderCore.cs b/src/ImageSharp/Formats/Bmp/BmpEncoderCore.cs index e5bf6d9cb..ed71119d7 100644 --- a/src/ImageSharp/Formats/Bmp/BmpEncoderCore.cs +++ b/src/ImageSharp/Formats/Bmp/BmpEncoderCore.cs @@ -73,18 +73,12 @@ namespace SixLabors.ImageSharp.Formats.Bmp #endif fileHeader.WriteTo(buffer); -#if NETCOREAPP2_1 - stream.Write(buffer.Slice(0, BmpFileHeader.Size)); -#else stream.Write(buffer, 0, BmpFileHeader.Size); -#endif + infoHeader.WriteTo(buffer); -#if NETCOREAPP2_1 - stream.Write(buffer.Slice(0, 40)); -#else stream.Write(buffer, 0, 40); -#endif + this.WriteImage(stream, image.Frames.RootFrame); stream.Flush(); diff --git a/src/ImageSharp/Formats/Gif/LzwDecoder.cs b/src/ImageSharp/Formats/Gif/LzwDecoder.cs index 446ebde9a..6953e8fcd 100644 --- a/src/ImageSharp/Formats/Gif/LzwDecoder.cs +++ b/src/ImageSharp/Formats/Gif/LzwDecoder.cs @@ -239,11 +239,8 @@ namespace SixLabors.ImageSharp.Formats.Gif return 0; } -#if NETCOREAPP2_1 - int count = this.stream.Read(buffer.Slice(0, bufferSize)); -#else int count = this.stream.Read(buffer, 0, bufferSize); -#endif + return count != bufferSize ? 0 : bufferSize; }