Skip to content

Commit 1261194

Browse files
AndyButlandCopilot
andauthored
Permissions: Protect GetIdsFromPathReversed against invalid program exception (#20930)
* Updates to protect GetIdsFromPathReversed against invalid program exception. * Apply suggestions from code review Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
1 parent 04f98a7 commit 1261194

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed

src/Umbraco.Core/Extensions/StringExtensions.cs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,16 +51,23 @@ static StringExtensions()
5151
}
5252

5353
/// <summary>
54-
/// Convert a path to node ids in the order from right to left (deepest to shallowest)
54+
/// Convert a path to node ids in the order from right to left (deepest to shallowest).
5555
/// </summary>
56-
/// <param name="path"></param>
57-
/// <returns></returns>
56+
/// <param name="path">The path string expected as a comma delimited collection of integers.</param>
57+
/// <returns>An array of integers matching the provided path.</returns>
5858
public static int[] GetIdsFromPathReversed(this string path)
5959
{
6060
ReadOnlySpan<char> pathSpan = path.AsSpan();
61+
62+
// Using the explicit enumerator (while/MoveNext) over the SpanSplitEnumerator in a foreach loop to avoid any compiler
63+
// boxing of the ref struct enumerator.
64+
// This prevents potential InvalidProgramException across compilers/JITs ("Cannot create boxed ByRef-like values.").
65+
MemoryExtensions.SpanSplitEnumerator<char> pathSegmentsEnumerator = pathSpan.Split(Constants.CharArrays.Comma);
66+
6167
List<int> nodeIds = [];
62-
foreach (Range rangeOfPathSegment in pathSpan.Split(Constants.CharArrays.Comma))
68+
while (pathSegmentsEnumerator.MoveNext())
6369
{
70+
Range rangeOfPathSegment = pathSegmentsEnumerator.Current;
6471
if (int.TryParse(pathSpan[rangeOfPathSegment], NumberStyles.Integer, CultureInfo.InvariantCulture, out int pathSegment))
6572
{
6673
nodeIds.Add(pathSegment);

tests/Umbraco.Tests.UnitTests/Umbraco.Core/ShortStringHelper/StringExtensionsTests.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -389,9 +389,11 @@ private static void TryIsFullPath(string path, bool expectedIsFull, bool expecte
389389
}
390390
}
391391

392+
[TestCase(null, "")]
393+
[TestCase("", "")]
392394
[TestCase("1,2,3,4,5", "5,4,3,2,1")]
393395
[TestCase("1,2,x,4,5", "5,4,2,1")]
394-
public void GetIdsFromPathReversed(string input, string expected)
396+
public void GetIdsFromPathReversed_ReturnsExpectedResult(string input, string expected)
395397
{
396398
var ids = input.GetIdsFromPathReversed();
397399
Assert.AreEqual(expected, string.Join(",", ids));

0 commit comments

Comments
 (0)