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
32 changes: 32 additions & 0 deletions PowerKit.Tests/BinaryWriterExtensionsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,38 @@ namespace PowerKit.Tests;

public class BinaryWriterExtensionsTests
{
[Fact]
public void SkipPadding_Test()
{
// Arrange
using var stream = new MemoryStream();
using var writer = new BinaryWriter(stream);

writer.Write((byte)0x01); // advance to position 1

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

// Assert
stream.Position.Should().Be(4);
stream.ToArray().Should().Equal(0x01, 0x00, 0x00, 0x00);
}

[Fact]
public void SkipPadding_AlreadyAligned_Test()
{
// Arrange
using var stream = new MemoryStream();
using var writer = new BinaryWriter(stream);

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

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

[Fact]
public void WriteNullTerminatedString_Test()
{
Expand Down
4 changes: 4 additions & 0 deletions PowerKit/Extensions/BinaryReaderExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#nullable enable
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text;
Expand All @@ -25,6 +26,9 @@ internal static class BinaryReaderExtensions
/// </summary>
public void SkipPadding(int boundaryBytes = 4)
{
if (boundaryBytes <= 0)
throw new ArgumentOutOfRangeException(nameof(boundaryBytes));

while (!reader.IsEndOfStream && reader.BaseStream.Position % boundaryBytes != 0)
{
_ = reader.ReadByte();
Expand Down
15 changes: 15 additions & 0 deletions PowerKit/Extensions/BinaryWriterExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#nullable enable
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;

Expand All @@ -11,6 +12,20 @@ internal static class BinaryWriterExtensions
{
extension(BinaryWriter writer)
{
/// <summary>
/// Writes zero bytes until the current position is aligned to the specified byte boundary.
/// </summary>
public void SkipPadding(int boundaryBytes = 4)
{
if (boundaryBytes <= 0)
throw new ArgumentOutOfRangeException(nameof(boundaryBytes));

while (writer.BaseStream.Position % boundaryBytes != 0)
{
writer.Write((byte)0);
}
Comment thread
Tyrrrz marked this conversation as resolved.
}

/// <summary>
/// Writes a null-terminated string to the binary writer.
/// </summary>
Expand Down