Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions PowerKit.Tests/MemoryWriteStreamTests.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.IO;
using FluentAssertions;
using PowerKit.Tests.Utils;
Expand Down Expand Up @@ -29,4 +30,32 @@ public void MemoryWriteStream_Test()
seekable.CanSeek.Should().BeTrue();
destination.ToArray().Should().Equal(data);
}

[Fact]
public void MemoryWriteStream_FlushTwice_Throws()
{
// Arrange
using var destination = new MemoryStream();
using var seekable = new MemoryWriteStream(destination);

seekable.Write([1, 2, 3]);
seekable.Flush();

// Act & Assert
seekable.Invoking(s => s.Flush()).Should().Throw<InvalidOperationException>();
}

[Fact]
public void MemoryWriteStream_FlushThenDispose_DoesNotThrow()
{
// Arrange
using var destination = new MemoryStream();
var seekable = new MemoryWriteStream(destination);

seekable.Write([1, 2, 3]);
seekable.Flush();

// Act & Assert
seekable.Invoking(s => s.Dispose()).Should().NotThrow();
}
}
Comment thread
Tyrrrz marked this conversation as resolved.
24 changes: 24 additions & 0 deletions PowerKit/MemoryWriteStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ namespace PowerKit;
public class MemoryWriteStream(Stream source) : Stream
{
private readonly MemoryStream _buffer = new();
private bool _flushed;
Comment thread
Tyrrrz marked this conversation as resolved.
Outdated
private bool _disposing;
Comment thread
Tyrrrz marked this conversation as resolved.
Outdated

/// <inheritdoc />
public override bool CanRead => false;
Expand All @@ -38,9 +40,31 @@ public override long Position
/// <inheritdoc />
public override void Flush()
{
if (_flushed)
{
if (_disposing)
return;

throw new InvalidOperationException(
$"{nameof(MemoryWriteStream)} has already been flushed."
);
}

_buffer.Position = 0;
_buffer.CopyTo(source);
source.Flush();
_flushed = true;
}

/// <inheritdoc />
protected override void Dispose(bool disposing)
{
// Set and clear _disposing so that the implicit Flush() called by base.Dispose()
// is treated as non-manual. The flag must be reset afterwards so that any erroneous
// Flush() calls made after disposal still throw rather than silently returning.
_disposing = true;
base.Dispose(disposing);
_disposing = false;
}
Comment thread
Tyrrrz marked this conversation as resolved.

/// <inheritdoc />
Expand Down