Skip to content
This repository was archived by the owner on Dec 21, 2023. It is now read-only.

Commit 76bba75

Browse files
committed
Optimize trimming
1 parent c28beea commit 76bba75

File tree

1 file changed

+17
-25
lines changed

1 file changed

+17
-25
lines changed
Lines changed: 17 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
using System;
2-
using System.Collections.Generic;
3-
using System.Linq;
42
using System.Threading.Tasks;
53
using Microsoft.AspNetCore.Html;
64
using Microsoft.AspNetCore.Mvc.Rendering;
@@ -29,42 +27,36 @@ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutpu
2927
output.Content.SetHtmlContent(code);
3028
}
3129

32-
private string TrimPreceding(string value, char character)
30+
private static string TrimPreceding(string value, char character)
3331
{
3432
var lines = value.Split(Environment.NewLine);
3533
var preceding = CountPreceding(lines, character);
36-
var trimmedLines = from line in lines
37-
select TrimPrecedingLine(line, character, preceding);
34+
for (var i = 0; i < lines.Length; ++i)
35+
{
36+
var line = lines[i];
37+
lines[i] = line.Length >= preceding ? line[preceding..] : string.Empty;
38+
}
3839

39-
return string.Join(Environment.NewLine, trimmedLines);
40+
return string.Join(Environment.NewLine, lines);
4041
}
4142

42-
private int CountPreceding(IEnumerable<string> lines, char leadingCharacter)
43+
private static int CountPreceding(string[] lines, char leadingCharacter)
4344
{
45+
var min = int.MaxValue;
4446
foreach (var line in lines)
4547
{
46-
// Make sure that the line actually starts with the leading character
47-
if (line.StartsWith(leadingCharacter) == false)
48-
continue;
49-
50-
// Determine last index of leading character, return if something else is found
51-
for (var i = 0; i < line.Length; i++)
48+
var lineSpan = line.AsSpan();
49+
for (var i = 0; i < lineSpan.Length; ++i)
5250
{
53-
var character = line[i];
54-
if (character != leadingCharacter)
55-
return i;
51+
if (lineSpan[i] != leadingCharacter)
52+
{
53+
min = i < min ? i : min;
54+
break;
55+
}
5656
}
57-
58-
// Assume that this line is the template for trimming
59-
return line.Length;
6057
}
6158

62-
throw new ArgumentException("No lines match the target leading character.", nameof(lines));
63-
}
64-
65-
private string TrimPrecedingLine(string line, char character, int amount)
66-
{
67-
return line.StartsWith(character) ? new string(line.Skip(amount).ToArray()) : line;
59+
return min;
6860
}
6961
}
7062
}

0 commit comments

Comments
 (0)