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 slice out of range errors #636

Merged
merged 2 commits into from
Mar 29, 2024
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
2 changes: 2 additions & 0 deletions Fluid.Tests/StringFiltersTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,8 @@ public void Slice(object input, object[] arguments, string expected)
[InlineData("hello", new object[] { -5, 100 }, "hello")]
[InlineData("hello", new object[] { 0, -100 }, "")]
[InlineData("hello", new object[] { -100, -100 }, "")]
[InlineData("hello", new object[] { 4, 2 }, "o")]
[InlineData("hello", new object[] { 5, 1 }, "")]
public void SliceOutsideBounds(object input, object[] arguments, string expected)
{
var filterInput = FluidValue.Create(input, TemplateOptions.Default);
Expand Down
5 changes: 3 additions & 2 deletions Fluid/Filters/StringFilters.cs
Original file line number Diff line number Diff line change
Expand Up @@ -239,8 +239,9 @@ public static ValueTask<FluidValue> Slice(FluidValue input, FilterArguments argu
}

var startIndex = requestedStartIndex < 0 ? Math.Max(sourceStringLength + requestedStartIndex, 0) : Math.Min(requestedStartIndex, sourceStringLength);
var length = requestedLength > sourceStringLength ? sourceStringLength : requestedLength;
length = startIndex > 0 && length + startIndex > sourceStringLength ? length - startIndex : length;
var length = requestedLength + startIndex > sourceStringLength
? sourceStringLength - startIndex
: requestedLength;

return new StringValue(sourceString.Substring(startIndex, length));
}
Expand Down