Skip to content

Commit

Permalink
feat: PadLeft and PadRight
Browse files Browse the repository at this point in the history
  • Loading branch information
linkdotnet committed Sep 20, 2024
1 parent 0a14ea3 commit b71ea72
Show file tree
Hide file tree
Showing 3 changed files with 89 additions and 0 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ All notable changes to **ValueStringBuilder** will be documented in this file. T

## [Unreleased]

### Added
- `PadLeft` and `PadRight` methods

## [1.20.0] - 2024-05-02

### Added
Expand Down
42 changes: 42 additions & 0 deletions src/LinkDotNet.StringBuilder/ValueStringBuilder.Pad.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
namespace LinkDotNet.StringBuilder;

public ref partial struct ValueStringBuilder
{
/// <summary>
/// Pads the left side of the string with the given character.
/// </summary>
/// <param name="totalWidth">Total width of the string after padding.</param>
/// <param name="paddingChar">Character to pad the string with.</param>
public void PadLeft(int totalWidth, char paddingChar)
{
if (totalWidth <= bufferPosition)
{
return;
}

EnsureCapacity(totalWidth);

var padding = totalWidth - bufferPosition;
buffer[..bufferPosition].CopyTo(buffer[padding..]);
buffer[..padding].Fill(paddingChar);
bufferPosition = totalWidth;
}

/// <summary>
/// Pads the right side of the string with the given character.
/// </summary>
/// <param name="totalWidth">Total width of the string after padding.</param>
/// <param name="paddingChar">Character to pad the string with.</param>
public void PadRight(int totalWidth, char paddingChar)
{
if (totalWidth <= bufferPosition)
{
return;
}

EnsureCapacity(totalWidth);

buffer[bufferPosition..totalWidth].Fill(paddingChar);
bufferPosition = totalWidth;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
namespace LinkDotNet.StringBuilder.UnitTests;

public class ValueStringBuilderPadTests
{
[Fact]
public void ShouldPadLeft()
{
using var stringBuilder = new ValueStringBuilder("Hello");

stringBuilder.PadLeft(10, ' ');

stringBuilder.ToString().Should().Be(" Hello");
}

[Fact]
public void ShouldPadRight()
{
using var stringBuilder = new ValueStringBuilder("Hello");

stringBuilder.PadRight(10, ' ');

stringBuilder.ToString().Should().Be("Hello ");
}

[Fact]
public void GivenTotalWidthIsSmallerThanCurrentLength_WhenPadLeft_ThenShouldNotChange()
{
using var stringBuilder = new ValueStringBuilder("Hello");

stringBuilder.PadLeft(3, ' ');

stringBuilder.ToString().Should().Be("Hello");
}

[Fact]
public void GivenTotalWidthIsSmallerThanCurrentLength_WhenPadRight_ThenShouldNotChange()
{
using var stringBuilder = new ValueStringBuilder("Hello");

stringBuilder.PadRight(3, ' ');

stringBuilder.ToString().Should().Be("Hello");
}
}

0 comments on commit b71ea72

Please sign in to comment.