Skip to content

Commit

Permalink
fix: code clean up, optimizing string comparison
Browse files Browse the repository at this point in the history
  • Loading branch information
egil committed Oct 13, 2024
1 parent 0d16d87 commit ff580f8
Show file tree
Hide file tree
Showing 21 changed files with 119 additions and 104 deletions.
3 changes: 3 additions & 0 deletions src/.editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -225,3 +225,6 @@ dotnet_naming_style.fields_begin_with__.required_prefix = _
dotnet_naming_style.fields_begin_with__.required_suffix =
dotnet_naming_style.fields_begin_with__.word_separator =
dotnet_naming_style.fields_begin_with__.capitalization = camel_case

# MA0012: Do not raise reserved exception type
dotnet_diagnostic.MA0012.severity = none
4 changes: 2 additions & 2 deletions src/AngleSharp.Diffing.Tests/Core/HtmlDifferenceEngineTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,7 @@ private static IEnumerable<Comparison> NoneNodeMatcher(IDiffContext ctx, SourceC
private static Func<IDiffContext, SourceCollection, SourceCollection, IEnumerable<Comparison>> SpecificIndexNodeMatcher(int index)
=> (ctx, controlNodes, testNodes) =>
{
return new List<Comparison> { new Comparison(controlNodes[index], testNodes[index]) };
return new List<Comparison> { new(controlNodes[index], testNodes[index]) };
};

private static IEnumerable<Comparison> OneToOneNodeListMatcher(
Expand All @@ -477,7 +477,7 @@ private static Func<IDiffContext, SourceMap, SourceMap, IEnumerable<AttributeCom
{
return (ctx, ctrlAttrs, testAttrs) => new List<AttributeComparison>
{
new AttributeComparison(ctrlAttrs[matchAttrName], testAttrs[matchAttrName] )
new(ctrlAttrs[matchAttrName], testAttrs[matchAttrName] )
};
}

Expand Down
4 changes: 2 additions & 2 deletions src/AngleSharp.Diffing.Tests/DiffBuilderTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ public void Test001()
[Fact(DisplayName = "Builder throws if null is passed to control and test")]
public void Test002()
{
Should.Throw<ArgumentNullException>(() => DiffBuilder.Compare(null!)).ParamName.ShouldBe(nameof(DiffBuilder.Control));
Should.Throw<ArgumentNullException>(() => DiffBuilder.Compare("").WithTest(null!)).ParamName.ShouldBe(nameof(DiffBuilder.Test));
Should.Throw<ArgumentNullException>(() => DiffBuilder.Compare(null!)).ParamName.ShouldBe("value");
Should.Throw<ArgumentNullException>(() => DiffBuilder.Compare("").WithTest(null!)).ParamName.ShouldBe("value");
}

[Fact(DisplayName = "Calling Build() with DefaultOptions() returns expected diffs")]
Expand Down
2 changes: 1 addition & 1 deletion src/AngleSharp.Diffing.Tests/DiffingTestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ public abstract class DiffingTestBase : IClassFixture<DiffingTestFixture>
private readonly DiffingTestFixture _testFixture;


public static readonly TheoryData<CompareResult> SameAndSkipCompareResult = new TheoryData<CompareResult>
public static readonly TheoryData<CompareResult> SameAndSkipCompareResult = new()
{
CompareResult.Same,
CompareResult.Skip,
Expand Down
6 changes: 3 additions & 3 deletions src/AngleSharp.Diffing.sln
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29230.61
# Visual Studio Version 17
VisualStudioVersion = 17.11.35312.102
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AngleSharp.Diffing", "AngleSharp.Diffing\AngleSharp.Diffing.csproj", "{2BFFA992-22C2-4A65-94D8-CA06E81D2364}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AngleSharp.DiffingTests", "AngleSharp.Diffing.Tests\AngleSharp.DiffingTests.csproj", "{18203D98-66B4-4736-B79A-3B7D02EFA9E8}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{E8E3C8B4-92C3-4DB7-B920-D28651E24A57}"
ProjectSection(SolutionItems) = preProject
..\.editorconfig = ..\.editorconfig
.editorconfig = .editorconfig
..\tools\anglesharp.cake = ..\tools\anglesharp.cake
..\build.cake = ..\build.cake
..\build.ps1 = ..\build.ps1
Expand Down
66 changes: 35 additions & 31 deletions src/AngleSharp.Diffing/AngleSharp.Diffing.csproj
Original file line number Diff line number Diff line change
@@ -1,39 +1,43 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>

<PropertyGroup>
<Description>Provides a complete diffing model of HTML.</Description>
<Product>AngleSharp.Diffing</Product>
<Authors>AngleSharp</Authors>
<PackageId>AngleSharp.Diffing</PackageId>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageProjectUrl>https://anglesharp.github.io</PackageProjectUrl>
<PackageIcon>logo.png</PackageIcon>
<PackageIconUrl>https://raw.github.com/AngleSharp/AngleSharp.Diffing/master/logo.png</PackageIconUrl>
<PackageTags>html html5 css css3 dom library diffing anglesharp diff difference compare comparison testing</PackageTags>
<Copyright>Egil Hansen</Copyright>
<RepositoryUrl>https://github.com/AngleSharp/AngleSharp.Diffing</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
</PropertyGroup>
<PropertyGroup>
<Description>Provides a complete diffing model of HTML.</Description>
<Product>AngleSharp.Diffing</Product>
<Authors>AngleSharp</Authors>
<PackageId>AngleSharp.Diffing</PackageId>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageProjectUrl>https://anglesharp.github.io</PackageProjectUrl>
<PackageIcon>logo.png</PackageIcon>
<PackageIconUrl>https://raw.github.com/AngleSharp/AngleSharp.Diffing/master/logo.png</PackageIconUrl>
<PackageTags>html html5 css css3 dom library diffing anglesharp diff difference compare comparison testing</PackageTags>
<Copyright>Egil Hansen</Copyright>
<RepositoryUrl>https://github.com/AngleSharp/AngleSharp.Diffing</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0" PrivateAssets="All" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0" PrivateAssets="All" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="TunnelVisionLabs.ReferenceAssemblyAnnotator" Version="1.0.0-alpha.160" PrivateAssets="all" />
<PackageDownload Include="Microsoft.NETCore.App.Ref" Version="[5.0.0]" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Meziantou.Analyzer" Version="2.0.169">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<PackageReference Include="TunnelVisionLabs.ReferenceAssemblyAnnotator" Version="1.0.0-alpha.160" PrivateAssets="all" />
<PackageDownload Include="Microsoft.NETCore.App.Ref" Version="[5.0.0]" />
</ItemGroup>

<ItemGroup>
<None Include="..\..\logo.png" Pack="true" PackagePath="\" />
</ItemGroup>
<ItemGroup>
<None Include="..\..\logo.png" Pack="true" PackagePath="\" />
</ItemGroup>

</Project>
3 changes: 3 additions & 0 deletions src/AngleSharp.Diffing/Core/AttributeComparison.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
using System.Runtime.InteropServices;

namespace AngleSharp.Diffing.Core;

/// <summary>
/// A match between two attributes that should be compared.
/// </summary>
/// <param name="Control">Gets the control attribute which the <see cref="Test"/> attribute is supposed to match.</param>
/// <param name="Test">Gets the test attribute which should be compared to the <see cref="Control"/> attribute.</param>
[StructLayout(LayoutKind.Auto)]
public readonly record struct AttributeComparison(in AttributeComparisonSource Control, in AttributeComparisonSource Test)
{
/// <summary>
Expand Down
14 changes: 7 additions & 7 deletions src/AngleSharp.Diffing/Core/CompareResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,39 +15,39 @@ public readonly record struct CompareResult(CompareDecision Decision, IDiff? Dif
/// <summary>
/// Use when the two compared nodes or attributes are the same.
/// </summary>
public static readonly CompareResult Same = new CompareResult(CompareDecision.Same);
public static readonly CompareResult Same = new(CompareDecision.Same);

/// <summary>
/// Use when the comparison should be skipped and any child-nodes or attributes skipped as well.
/// </summary>
public static readonly CompareResult Skip = new CompareResult(CompareDecision.Skip);
public static readonly CompareResult Skip = new(CompareDecision.Skip);

/// <summary>
/// Use when the comparison should skip any child-nodes.
/// </summary>
public static readonly CompareResult SkipChildren = new CompareResult(CompareDecision.SkipChildren);
public static readonly CompareResult SkipChildren = new(CompareDecision.SkipChildren);

/// <summary>
/// Use when the comparison should skip any attributes.
/// </summary>
public static readonly CompareResult SkipAttributes = new CompareResult(CompareDecision.SkipAttributes);
public static readonly CompareResult SkipAttributes = new(CompareDecision.SkipAttributes);

/// <summary>
/// Use when the comparison should skip any attributes.
/// </summary>
public static readonly CompareResult SkipChildrenAndAttributes = new CompareResult(CompareDecision.SkipChildren | CompareDecision.SkipAttributes);
public static readonly CompareResult SkipChildrenAndAttributes = new(CompareDecision.SkipChildren | CompareDecision.SkipAttributes);

/// <summary>
/// Use when the two compared nodes or attributes are the different.
/// </summary>
public static CompareResult Different => new CompareResult(CompareDecision.Different);
public static CompareResult Different => new(CompareDecision.Different);

/// <summary>
/// Use when the two compared nodes or attributes are the different.
/// </summary>
/// <param name="diff">The associated <see cref="IDiff"/> describing the difference.</param>
/// <returns>Returns a <see cref="CompareResult"/> with <see cref="CompareResult.Decision"/> set to <see cref="CompareDecision.Different"/>.</returns>
public static CompareResult FromDiff(IDiff diff) => new CompareResult(CompareDecision.Different, diff);
public static CompareResult FromDiff(IDiff diff) => new(CompareDecision.Different, diff);

/// <summary>
/// Checks if a <see cref="CompareResult"/> is either a <see cref="CompareResult.Same"/> or <see cref="CompareResult.Skip"/>.
Expand Down
3 changes: 3 additions & 0 deletions src/AngleSharp.Diffing/Core/Comparison.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
using System.Runtime.InteropServices;

namespace AngleSharp.Diffing.Core;

/// <summary>
/// Represent a comparison between two nodes.
/// </summary>
/// <param name="Control">Gets the control source in the comparison.</param>
/// <param name="Test">Gets the test source in the comparison.</param>
[StructLayout(LayoutKind.Auto)]
public readonly record struct Comparison(in ComparisonSource Control, in ComparisonSource Test)
{
/// <summary>
Expand Down
File renamed without changes.
21 changes: 0 additions & 21 deletions src/AngleSharp.Diffing/Core/DiffTarget.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,24 +30,3 @@ public enum DiffTarget
/// </summary>
Text
}

/// <summary>
/// Helper methods for working with <see cref="DiffTarget"/>.
/// </summary>
public static class NodeTypeExtensions
{
/// <summary>
/// Gets the diff target based on the node type.
/// </summary>
/// <param name="nodeType">Mode type to get the diff target off.</param>
public static DiffTarget ToDiffTarget(this NodeType nodeType)
{
return nodeType switch
{
NodeType.Element => DiffTarget.Element,
NodeType.Comment => DiffTarget.Comment,
NodeType.Text => DiffTarget.Text,
_ => DiffTarget.Node
};
}
}
16 changes: 0 additions & 16 deletions src/AngleSharp.Diffing/Core/FilterDecision.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,3 @@ public enum FilterDecision
/// </summary>
Exclude
}

/// <summary>
/// Helper methods for <see cref="FilterDecision"/>.
/// </summary>
public static class FilterDecisionExtensions
{
/// <summary>
/// Gets whether the <see cref="FilterDecision"/> is <see cref="FilterDecision.Exclude"/>.
/// </summary>
public static bool IsExclude(this FilterDecision decision) => decision == FilterDecision.Exclude;

/// <summary>
/// Gets whether the <see cref="FilterDecision"/> is <see cref="FilterDecision.Keep"/>.
/// </summary>
public static bool IsKeep(this FilterDecision decision) => decision == FilterDecision.Keep;
}
17 changes: 17 additions & 0 deletions src/AngleSharp.Diffing/Core/FilterDecisionExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
namespace AngleSharp.Diffing.Core;

/// <summary>
/// Helper methods for <see cref="FilterDecision"/>.
/// </summary>
public static class FilterDecisionExtensions
{
/// <summary>
/// Gets whether the <see cref="FilterDecision"/> is <see cref="FilterDecision.Exclude"/>.
/// </summary>
public static bool IsExclude(this FilterDecision decision) => decision == FilterDecision.Exclude;

/// <summary>
/// Gets whether the <see cref="FilterDecision"/> is <see cref="FilterDecision.Keep"/>.
/// </summary>
public static bool IsKeep(this FilterDecision decision) => decision == FilterDecision.Keep;
}
22 changes: 22 additions & 0 deletions src/AngleSharp.Diffing/Core/NodeTypeExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
namespace AngleSharp.Diffing.Core;

/// <summary>
/// Helper methods for working with <see cref="DiffTarget"/>.
/// </summary>
public static class NodeTypeExtensions
{
/// <summary>
/// Gets the diff target based on the node type.
/// </summary>
/// <param name="nodeType">Mode type to get the diff target off.</param>
public static DiffTarget ToDiffTarget(this NodeType nodeType)
{
return nodeType switch
{
NodeType.Element => DiffTarget.Element,
NodeType.Comment => DiffTarget.Comment,
NodeType.Text => DiffTarget.Text,
_ => DiffTarget.Node
};
}
}
4 changes: 2 additions & 2 deletions src/AngleSharp.Diffing/Core/SourceMap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ namespace AngleSharp.Diffing.Core;
[SuppressMessage("Naming", "CA1710:Identifiers should have correct suffix")]
public class SourceMap : IEnumerable<AttributeComparisonSource>
{
private readonly HashSet<string> _matched = new HashSet<string>();
private readonly Dictionary<string, AttributeComparisonSource> _sources = new Dictionary<string, AttributeComparisonSource>();
private readonly HashSet<string> _matched = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, AttributeComparisonSource> _sources = new(StringComparer.OrdinalIgnoreCase);

/// <summary>
/// Gets the type of the sources in the collection.
Expand Down
4 changes: 2 additions & 2 deletions src/AngleSharp.Diffing/DiffBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ public class DiffBuilder
/// <summary>
/// Gets or sets the control markup string.
/// </summary>
public string Control { get => _control; set => _control = value ?? throw new ArgumentNullException(nameof(Control)); }
public string Control { get => _control; set => _control = value ?? throw new ArgumentNullException(nameof(value)); }

/// <summary>
/// Gets or sets the test markup string.
/// </summary>
public string Test { get => _test; set => _test = value ?? throw new ArgumentNullException(nameof(Test)); }
public string Test { get => _test; set => _test = value ?? throw new ArgumentNullException(nameof(value)); }

private DiffBuilder(string control)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,5 @@ public static IEnumerable<ComparisonSource> ToComparisonSourceList(this IEnumera
/// Creates a comparison source from a node.
/// </summary>
public static ComparisonSource ToComparisonSource(this INode node, int index, ComparisonSourceType sourceType, string path = "")
=> new ComparisonSource(node, index, path, sourceType);
=> new(node, index, path, sourceType);
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public static CompareResult Compare(in AttributeComparison comparison, CompareRe
if (ctrlElm.ClassList.Length != testElm.ClassList.Length)
return CompareResult.FromDiff(new AttrDiff(comparison, AttrDiffKind.Value));

return ctrlElm.ClassList.All(x => testElm.ClassList.Contains(x))
return ctrlElm.ClassList.All(x => testElm.ClassList.Contains(x, StringComparer.Ordinal))
? CompareResult.Same
: CompareResult.FromDiff(new AttrDiff(comparison, AttrDiffKind.Value));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ private static bool CompareCssStyleDeclarations(ICssStyleDeclaration control, IC
if (control.Length != test.Length)
return false;

var orderedControl = control.CssText.Split(';').Select(x => x.Trim()).OrderBy(x => x);
var orderedTest = test.CssText.Split(';').Select(x => x.Trim()).OrderBy(x => x);
var orderedControl = control.CssText.Split(';').Select(x => x.Trim()).OrderBy(x => x, StringComparer.Ordinal);
var orderedTest = test.CssText.Split(';').Select(x => x.Trim()).OrderBy(x => x, StringComparer.Ordinal);

return orderedControl.SequenceEqual(orderedTest, StringComparer.Ordinal);
}
Expand Down
Loading

0 comments on commit ff580f8

Please sign in to comment.