From f2875d86f92c39e8cf1e4a4bb7ac2c5bb000d4b7 Mon Sep 17 00:00:00 2001 From: Matthew Leibowitz Date: Fri, 18 Nov 2016 02:17:27 +0200 Subject: [PATCH] Added an overload for SKData.AsStream that disposes data --- binding/Binding/SKData.cs | 50 +++++++++++++++++++++++---------------- tests/Tests/SKDataTest.cs | 21 ++++++++++++++++ 2 files changed, 51 insertions(+), 20 deletions(-) diff --git a/binding/Binding/SKData.cs b/binding/Binding/SKData.cs index 1081b310..5475279e 100644 --- a/binding/Binding/SKData.cs +++ b/binding/Binding/SKData.cs @@ -95,29 +95,16 @@ namespace SkiaSharp public IntPtr Data => SkiaApi.sk_data_get_data (Handle); - private unsafe class MyUnmanagedMemoryStream : UnmanagedMemoryStream - { - private SKData host; - - public MyUnmanagedMemoryStream (SKData host) - : base((byte *) host.Data, host.Size) - { - this.host = host; - } - - protected override void Dispose (bool disposing) - { - base.Dispose (disposing); - - host = null; - } - } - public Stream AsStream () { - return new MyUnmanagedMemoryStream (this); + return new SKDataStream (this, false); } - + + public Stream AsStream (bool streamDisposesData) + { + return new SKDataStream (this, streamDisposesData); + } + public void SaveTo (Stream target) { if (target == null) @@ -135,6 +122,29 @@ namespace SkiaSharp target.Write (buffer, 0, copyCount); } } + + private class SKDataStream : UnmanagedMemoryStream + { + private SKData host; + private readonly bool disposeHost; + + public unsafe SKDataStream (SKData host, bool disposeHost = false) + : base((byte *) host.Data, host.Size) + { + this.host = host; + this.disposeHost = disposeHost; + } + + protected override void Dispose (bool disposing) + { + base.Dispose (disposing); + + if (disposeHost) { + host?.Dispose (); + } + host = null; + } + } } } diff --git a/tests/Tests/SKDataTest.cs b/tests/Tests/SKDataTest.cs index d8f990b7..ac62b8d6 100644 --- a/tests/Tests/SKDataTest.cs +++ b/tests/Tests/SKDataTest.cs @@ -17,5 +17,26 @@ namespace SkiaSharp.Tests Assert.AreEqual(OddData.Length, data.Size); CollectionAssert.AreEqual(OddData, data.ToArray()); } + + [Test] + public void DataDisposedReturnsInvalidStream() + { + // create data + var data = new SKData(OddData); + + // get the stream + var stream = data.AsStream(); + + // nuke the data + data.Dispose(); + Assert.AreEqual(IntPtr.Zero, data.Handle); + + // read the stream + var buffer = new byte[OddData.Length]; + stream.Read(buffer, 0, buffer.Length); + + // since the data was nuked, they will differ + CollectionAssert.AreNotEqual(OddData, buffer); + } } }