Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
60 changes: 59 additions & 1 deletion PowerKit.Tests/BinaryReaderExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,63 @@ namespace PowerKit.Tests;

public class BinaryReaderExtensionsTests
{
[Fact]
public void IsEndOfStream_Test()
{
// Arrange
var data = new byte[] { 1, 2, 3 };
using var stream = new MemoryStream(data);
using var reader = new BinaryReader(stream);

// Act & Assert
reader.IsEndOfStream.Should().BeFalse();
stream.Position = stream.Length;
reader.IsEndOfStream.Should().BeTrue();
}

[Fact]
public void IsEndOfStream_Empty_Test()
{
// Arrange
using var stream = new MemoryStream();
using var reader = new BinaryReader(stream);

// Act & Assert
reader.IsEndOfStream.Should().BeTrue();
}

[Fact]
public void SkipPadding_Test()
{
// Arrange - 1 byte of data, then 3 padding bytes, then 1 more byte
var data = new byte[] { 0x01, 0x00, 0x00, 0x00, 0x02 };
using var stream = new MemoryStream(data);
using var reader = new BinaryReader(stream);

reader.ReadByte(); // advance to position 1

// Act
reader.SkipPadding(boundaryBytes: 4);

// Assert
stream.Position.Should().Be(4);
}

[Fact]
Comment thread
Tyrrrz marked this conversation as resolved.
public void SkipPadding_AlreadyAligned_Test()
{
// Arrange
var data = new byte[] { 0x01, 0x02, 0x03, 0x04 };
using var stream = new MemoryStream(data);
using var reader = new BinaryReader(stream);

// Act (position 0 is already aligned to 4 bytes)
reader.SkipPadding(boundaryBytes: 4);

// Assert
stream.Position.Should().Be(0);
}

[Fact]
public void SkipZeroes_Test()
{
Expand Down Expand Up @@ -82,6 +139,7 @@ public void ReadNullTerminatedString_Empty_Test()
var result = reader.ReadNullTerminatedString();

// Assert
result.Should().Be("");
result.Should().BeEmpty();
}
}

18 changes: 18 additions & 0 deletions PowerKit/Extensions/BinaryReaderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,24 @@ internal static class BinaryReaderExtensions
{
extension(BinaryReader reader)
{
/// <summary>
/// Gets a value indicating whether the reader has reached the end of the stream.
/// </summary>
public bool IsEndOfStream => reader.BaseStream.CanSeek
? reader.BaseStream.Position >= reader.BaseStream.Length
: reader.PeekChar() == -1;

/// <summary>
/// Skips bytes until the current position is aligned to the specified byte boundary.
/// </summary>
public void SkipPadding(int boundaryBytes = 4)
{
while (!reader.IsEndOfStream && reader.BaseStream.Position % boundaryBytes != 0)
{
_ = reader.ReadByte();
}
}

/// <summary>
/// Skips zero bytes in the stream, up to the specified maximum length.
/// </summary>
Expand Down