Added an overload for SKData.AsStream that disposes data
This commit is contained in:
Родитель
ce2573c99a
Коммит
f2875d86f9
|
@ -95,27 +95,14 @@ 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)
|
||||
|
@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Загрузка…
Ссылка в новой задаче