diff --git a/PowerKit.Tests/BinaryWriterExtensionsTests.cs b/PowerKit.Tests/BinaryWriterExtensionsTests.cs index 537338c..4193510 100644 --- a/PowerKit.Tests/BinaryWriterExtensionsTests.cs +++ b/PowerKit.Tests/BinaryWriterExtensionsTests.cs @@ -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() { diff --git a/PowerKit/Extensions/BinaryReaderExtensions.cs b/PowerKit/Extensions/BinaryReaderExtensions.cs index f91a648..9c1f62f 100644 --- a/PowerKit/Extensions/BinaryReaderExtensions.cs +++ b/PowerKit/Extensions/BinaryReaderExtensions.cs @@ -1,4 +1,5 @@ #nullable enable +using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Text; @@ -25,6 +26,9 @@ internal static class BinaryReaderExtensions /// public void SkipPadding(int boundaryBytes = 4) { + if (boundaryBytes <= 0) + throw new ArgumentOutOfRangeException(nameof(boundaryBytes)); + while (!reader.IsEndOfStream && reader.BaseStream.Position % boundaryBytes != 0) { _ = reader.ReadByte(); diff --git a/PowerKit/Extensions/BinaryWriterExtensions.cs b/PowerKit/Extensions/BinaryWriterExtensions.cs index df829a1..5979f30 100644 --- a/PowerKit/Extensions/BinaryWriterExtensions.cs +++ b/PowerKit/Extensions/BinaryWriterExtensions.cs @@ -1,4 +1,5 @@ #nullable enable +using System; using System.Diagnostics.CodeAnalysis; using System.IO; @@ -11,6 +12,20 @@ internal static class BinaryWriterExtensions { extension(BinaryWriter writer) { + /// + /// Writes zero bytes until the current position is aligned to the specified byte boundary. + /// + public void SkipPadding(int boundaryBytes = 4) + { + if (boundaryBytes <= 0) + throw new ArgumentOutOfRangeException(nameof(boundaryBytes)); + + while (writer.BaseStream.Position % boundaryBytes != 0) + { + writer.Write((byte)0); + } + } + /// /// Writes a null-terminated string to the binary writer. ///