Skip to content
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
11 changes: 11 additions & 0 deletions MudBlazor.Markdown.sln
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MudBlazor.Markdown", "src\M
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MudBlazor.Markdown.Tests", "tests\MudBlazor.Markdown.Tests\MudBlazor.Markdown.Tests.csproj", "{CEE74ADB-80A4-4011-A2C6-68EB7902409A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MudBlazor.Markdown.Benchmarks", "benchmarks\MudBlazor.Markdown.Benchmarks\MudBlazor.Markdown.Benchmarks.csproj", "{F9210A1D-E13C-4805-A080-77DCB9B047CA}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Benchmarks", "Benchmarks", "{014FA7C1-7652-4A13-8BBB-A5CD8B97FB94}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -21,11 +25,18 @@ Global
{CEE74ADB-80A4-4011-A2C6-68EB7902409A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CEE74ADB-80A4-4011-A2C6-68EB7902409A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CEE74ADB-80A4-4011-A2C6-68EB7902409A}.Release|Any CPU.Build.0 = Release|Any CPU
{F9210A1D-E13C-4805-A080-77DCB9B047CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F9210A1D-E13C-4805-A080-77DCB9B047CA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F9210A1D-E13C-4805-A080-77DCB9B047CA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F9210A1D-E13C-4805-A080-77DCB9B047CA}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {8C5169D9-A38F-464C-88CE-F13FDCD37404}
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{F9210A1D-E13C-4805-A080-77DCB9B047CA} = {014FA7C1-7652-4A13-8BBB-A5CD8B97FB94}
EndGlobalSection
EndGlobal
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using BenchmarkDotNet.Attributes;
using Markdig.Syntax;

namespace MudBlazor.Markdown.Benchmarks;

[MemoryDiagnoser]
public class HeadingBlockExBenchmark
{
private HeadingBlock? _headingBlock;

[GlobalSetup]
public void Setup()
{
const int length = 1_000_000;
var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ +:&".ToCharArray();

var value = string.Create(length, chars, static (span, chars) =>
{
span[0] = '#';
span[1] = ' ';

for (var i = 2; i < length; i++)
{
span[i] = chars[Random.Shared.Next(chars.Length)];
}
});

_headingBlock = Markdig.Markdown.Parse(value)
.OfType<HeadingBlock>()
.Single();
}

[Benchmark]
public void Run()
{
if (_headingBlock is null)
throw new InvalidOperationException("HeadingBlock is not initialized.");

_headingBlock.BuildHeadingContent();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="BenchmarkDotNet" Version="0.15.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\MudBlazor.Markdown\MudBlazor.Markdown.csproj" />
</ItemGroup>

<ItemGroup>
<None Remove="*.csproj.DotSettings" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/CodeInspection/NamespaceProvider/NamespaceFoldersToSkip/=benchmarks/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
11 changes: 11 additions & 0 deletions benchmarks/MudBlazor.Markdown.Benchmarks/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using BenchmarkDotNet.Running;

namespace MudBlazor.Markdown.Benchmarks;

internal static class Program
{
private static void Main()
{
BenchmarkRunner.Run<HeadingBlockExBenchmark>();
}
}
88 changes: 36 additions & 52 deletions src/MudBlazor.Markdown/Utils/Extensions/HeadingBlockEx.cs
Original file line number Diff line number Diff line change
@@ -1,69 +1,53 @@
using System.Web;
using System.Buffers;
using System.Net;
using System.Text;
using Markdig.Syntax;
using Markdig.Syntax.Inlines;

namespace MudBlazor;

internal static class HeadingBlockEx
{
private const char JoinChar = '-';
private static readonly string[] EscapeChars = ["+", ":", "&"];
private const char JoinChar = '-', SpaceChar = ' ';
private static readonly SearchValues<char> SplitChars = SearchValues.Create([SpaceChar]);

public static HeadingContent? BuildHeadingContent(this HeadingBlock @this)
{
if (@this.Inline == null)
return null;

var headingId = BuildHeadingId(@this.Inline);
var headingText = BuildHeadingText(@this.Inline);
return new HeadingContent(headingId, headingText);
}

private static string BuildHeadingId(in ContainerInline inline)
{
var slices = inline
.Select(static x => x.GetHeadingIdContent())
.Where(static x => x.Length > 0);

return string.Join(JoinChar, slices);
}

private static string GetHeadingIdContent(this Inline @this)
{
var sliceString = @this.GetInlineContent(toLowerCase: true);
return PrepareHeadingIdContent(sliceString);
}

private static string PrepareHeadingIdContent(this string @this)
{
var words = @this.Split(' ', StringSplitOptions.RemoveEmptyEntries);
var str = string.Join(JoinChar, words);
StringBuilder headingId = new(), headingText = new();

for (var i = 0; i < EscapeChars.Length; i++)
str = str.Replace(EscapeChars[i], string.Empty);

return HttpUtility.UrlEncode(str);
}

private static string BuildHeadingText(in ContainerInline inline)
{
var slices = inline
.Select(static x => x.GetInlineContent())
.Where(static x => x.Length > 0);

return string.Join(' ', slices);
}

private static string GetInlineContent(this Inline @this, bool toLowerCase = false)
{
var slice = @this switch
foreach (var inline in @this.Inline)
{
LiteralInline x => x.Content,
_ => StringSlice.Empty,
};

return toLowerCase
? slice.ToLowerCaseString()
: slice.ToString();
if (inline is not LiteralInline literalInline || literalInline.Content.IsEmpty)
continue;

var span = literalInline.Content.AsSpan();
headingText.Append(span);

while (!span.IsEmpty)
{
var endIndex = span.IndexOfAny(SplitChars);
if (endIndex < 0)
break;

if (endIndex > 0)
{
headingId
.AppendLowerCase(span, endIndex)
.Append(JoinChar);
}

span = span[(endIndex + 1)..];
}

headingId.AppendLowerCase(span);
}

return new HeadingContent(
id: WebUtility.UrlEncode(headingId.ToString()),
text: headingText.ToString()
);
}
}
32 changes: 32 additions & 0 deletions src/MudBlazor.Markdown/Utils/Extensions/StringBuilderEx.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using System.Runtime.CompilerServices;
using System.Text;

namespace MudBlazor;

internal static class StringBuilderEx
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static StringBuilder AppendLowerCase(this StringBuilder @this, in ReadOnlySpan<char> span, in int endIndex)
{
for (var i = 0; i < endIndex; i++)
@this.Append(char.ToLowerInvariant(span[i]));

return @this;
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void AppendLowerCase(this StringBuilder @this, in ReadOnlySpan<char> span)
{
foreach (var @char in span)
@this.Append(char.ToLowerInvariant(@char));
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static StringBuilder Append(this StringBuilder @this, in ReadOnlySpan<char> span, in int endIndex)
{
for (var i = 0; i < endIndex; i++)
@this.Append(span[i]);

return @this;
}
}
22 changes: 0 additions & 22 deletions src/MudBlazor.Markdown/Utils/Extensions/StringSliceEx.cs

This file was deleted.

1 change: 1 addition & 0 deletions src/MudBlazor.Markdown/_Usings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@
using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("MudBlazor.Markdown.Tests")]
[assembly: InternalsVisibleTo("MudBlazor.Markdown.Benchmarks")]
Original file line number Diff line number Diff line change
Expand Up @@ -569,7 +569,7 @@ public void RenderTableWithWeirdFormat()
const string expected =
"""
<article id:ignore class='mud-markdown-body'>
<h3 id='my-table' class='mud-typography mud-typography-h3'>My Table:</h3>
<h3 id='my-table%3A' class='mud-typography mud-typography-h3'>My Table:</h3>
<p class='mud-typography mud-typography-body1'>
<div class='mud-markdown-error'>
| **Column 1** | **Column 2** | **Column 3** |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,29 @@ public void ConvertToLower()
}

[Theory]
[InlineData('+')]
[InlineData(':')]
[InlineData('&')]
public void EscapeCharacters(char inputChar)
[InlineData('+', "%2B")]
[InlineData(':', "%3A")]
[InlineData('&', "%26")]
public void EncodeSpecialCharacters(char inputChar, string expectedChar)
{
const string expectedId = "some--text";
string expectedText = $"some {inputChar} text", value = $"# {expectedText}";
var value = $"# some {inputChar} text";
string expectedId = $"some-{expectedChar}-text", expectedText = $"some {inputChar} text";

var result = CreateFixture(value)
.BuildHeadingContent();

var expected = new HeadingContent(expectedId, expectedText);

result
.Should()
.Be(expected);
}

[Fact]
public void EncodeHtmlCharacters()
{
const string value = "# Some text (日本語)";
const string expectedId = "some-text-(%E6%97%A5%E6%9C%AC%E8%AA%9E)", expectedText = "Some text (日本語)";

var result = CreateFixture(value)
.BuildHeadingContent();
Expand Down