Humanizr / Humanizer

Humanizer meets all your .NET needs for manipulating and displaying strings, enums, dates, times, timespans, numbers and quantities
Other
8.66k stars 964 forks source link

FixedLengthTruncator throws exception in some cases #1546

Open bambuca opened 1 week ago

bambuca commented 1 week ago

"Short".Truncate(100, null); will throw exception:

In the Truncate method this code casues error, because value is shorter than lenght and thus value.Substring(0, legth) throws exception

https://github.com/Humanizr/Humanizer/blob/main/src/Humanizer/Truncation/FixedLengthTruncator.cs , line 21-26 if (truncationString == null || truncationString.Length > length) { return truncateFrom == TruncateFrom.Right ? value.Substring(0, length) : value.Substring(value.Length - length); }

hangy commented 1 week ago

Do you have a short repro for this? "Short".Truncate(100, null) doesn't even compile for me, as the overloads are ambiguous. "Short".Truncate(100) correctly returns "Short". There are actually test cases for a case when the input string is shorter than the length.

bambuca commented 1 week ago

Sorry, my bad. The null parameter should be (string)null. See here https://dotnetfiddle.net/qZcZ7f

In FixedLengthTruncator.cs, you correctly check if (value.Length > length) in most cases. However, this check is missing when truncationString == null. In that case, you call value.Substring(0, length), which can fail if value is shorter than the specified length.

I crated PR for that #1547