Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix truncation if truncationString is null #1547

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
9 changes: 9 additions & 0 deletions src/Humanizer.Tests/TruncatorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,15 @@
public void Truncate(string? input, int length, string? expectedOutput) =>
Assert.Equal(expectedOutput, input.Truncate(length));

[Theory]
[InlineData("short text", 20, null, "short text")]
[InlineData("short text", 20, "trunc", "short text")]
[InlineData("short text", 20, "very long truncation string", "short text")]
[InlineData("Text longer than truncate length", 10, "very long truncation string", "Text longe")]
[InlineData("Text longer than truncate length", 10, "trunc", "Text trunc")]
public void TruncateWithCustomTruncationString(string? input, int length, string? trunactionString, string? expectedOutput) =>
Assert.Equal(expectedOutput, input.Truncate(length, trunactionString));

[Theory]
[InlineData(null, 10, null)]
[InlineData("", 10, "")]
Expand Down
13 changes: 2 additions & 11 deletions src/Humanizer/Truncation/FixedLengthTruncator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class FixedLengthTruncator : ITruncator
return null;
}

if (value.Length == 0)
if (value.Length == 0 || value.Length <= length)
{
return value;
}
Expand All @@ -25,15 +25,6 @@ class FixedLengthTruncator : ITruncator
: value.Substring(value.Length - length);
}

if (truncateFrom == TruncateFrom.Left)
{
return value.Length > length
? StringHumanizeExtensions.Concat(truncationString.AsSpan(), value.AsSpan(value.Length - length + truncationString.Length))
: value;
}

return value.Length > length
? StringHumanizeExtensions.Concat(value.AsSpan(0, length - truncationString.Length), truncationString.AsSpan())
: value;
return truncateFrom == TruncateFrom.Left ? StringHumanizeExtensions.Concat(truncationString.AsSpan(), value.AsSpan(value.Length - length + truncationString.Length)) : StringHumanizeExtensions.Concat(value.AsSpan(0, length - truncationString.Length), truncationString.AsSpan());
}
}