From c2b882bb2cbfe672174771fc30a3d69a335bf3a6 Mon Sep 17 00:00:00 2001 From: BoBoBaSs84 <73112377+BoBoBaSs84@users.noreply.github.com> Date: Fri, 8 Mar 2024 20:36:05 +0100 Subject: [PATCH] feat: stream extensions changes: - the `ToByteArray` method added - unit tests added - version bump to `2.2.0` closes #88 --- Directory.Build.props | 2 +- src/BB84.Extensions/StreamExtensions.cs | 23 ++++++++++++++ .../StreamExtensionsTests.cs | 30 +++++++++++++++++++ 3 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 src/BB84.Extensions/StreamExtensions.cs create mode 100644 tests/BB84.ExtensionsTests/StreamExtensionsTests.cs diff --git a/Directory.Build.props b/Directory.Build.props index a560447..1782b51 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -2,7 +2,7 @@ 2 - 1 + 2 0 $(VersionMajor).$(VersionMinor).$(VersionPatch) Development diff --git a/src/BB84.Extensions/StreamExtensions.cs b/src/BB84.Extensions/StreamExtensions.cs new file mode 100644 index 0000000..5b0cdf3 --- /dev/null +++ b/src/BB84.Extensions/StreamExtensions.cs @@ -0,0 +1,23 @@ +namespace BB84.Extensions; + +/// +/// The stream extensions class. +/// +public static partial class StreamExtensions +{ + /// + /// The method will keep reading (and copying into a ) + /// until it runs out of data. + /// + /// The stream to work with. + /// The as array. + public static byte[] ToByteArray(this Stream inputStream) + { + byte[] buffer = new byte[16 * 1024]; + using MemoryStream memoryStream = new(); + int read; + while ((read = inputStream.Read(buffer, 0, buffer.Length)) > 0) + memoryStream.Write(buffer, 0, read); + return memoryStream.ToArray(); + } +} diff --git a/tests/BB84.ExtensionsTests/StreamExtensionsTests.cs b/tests/BB84.ExtensionsTests/StreamExtensionsTests.cs new file mode 100644 index 0000000..202050f --- /dev/null +++ b/tests/BB84.ExtensionsTests/StreamExtensionsTests.cs @@ -0,0 +1,30 @@ +using BB84.Extensions; + +namespace BB84.ExtensionsTests; + +[TestClass] +public sealed partial class StreamExtensionsTests +{ + private readonly static Random Random = new(); + + [DataTestMethod] + [DynamicData(nameof(GetData), DynamicDataSourceType.Method)] + public void ToByteArrayTest(byte[] buffer) + { + MemoryStream stream = new(buffer); + + byte[] result = stream.ToByteArray(); + + Assert.IsTrue(result.SequenceEqual(buffer)); + } + + private static IEnumerable GetData() + { + for (int i = 0; i < 10; i++) + { + byte[] buffer = new byte[10]; + Random.NextBytes(buffer); + yield return new object[] { buffer }; + } + } +}