Skip to content

Commit

Permalink
Bug fixes.
Browse files Browse the repository at this point in the history
  • Loading branch information
houseofcat committed Nov 29, 2023
1 parent 0a9849d commit b7391e7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 12 deletions.
29 changes: 17 additions & 12 deletions src/Mnemonic.Strings/AhoCorasick/AhoCorasickStringReplace.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Mnemonic.Strings.Interfaces;
using Cysharp.Text;
using Mnemonic.Strings.Interfaces;
using System;
using System.Collections.Generic;
using System.Diagnostics;
Expand Down Expand Up @@ -73,10 +74,10 @@ public string Replace(ReadOnlySpan<char> input)
if (!_isBuilt) throw new InvalidOperationException(_mustBuildFirstError);
if (input.Length == 0) return default;

var result = new StringBuilder();
using var result = ZString.CreateUtf8StringBuilder();
var currentNode = _root;
var i = 0;
var partialMatchIndexStart = 0;
var partialMatchIndexStart = -1;

while (i < input.Length)
{
Expand All @@ -95,24 +96,27 @@ public string Replace(ReadOnlySpan<char> input)
}
else if (currentNode.IsRoot)
{
DebugView("NoMatchFound", i, currentChar, currentNode.Key, currentNode.Replacement);
result.Append(currentChar);
partialMatchIndexStart = 0;
partialMatchIndexStart = -1;
i++;
}
else if (currentNode.IsEndOfPattern)
{
DebugView("EndOfPatternFound", i, currentChar, currentNode.Key, currentNode.Replacement);
result.Append(currentNode.Replacement);
currentNode = _root;
partialMatchIndexStart = 0;
}
else
{
DebugView("FailureLink", i, currentChar, currentNode.Key, currentNode.Replacement);
result.Append(input[partialMatchIndexStart..i]);
currentNode = currentNode.FailureLinkNode;
partialMatchIndexStart = 0;
partialMatchIndexStart = -1;
}

if (currentNode.IsEndOfPattern)
{
DebugView("EndOfPatternFound", i, currentChar, currentNode.Key, currentNode.Replacement);
result.Append(currentNode.Replacement);
currentNode = _root;
partialMatchIndexStart = -1;
}

}

return result.ToString();
Expand Down Expand Up @@ -146,6 +150,7 @@ private void BuildFailureLink(Queue<TrieNode> queue)
if (currentChildNode.FailureLinkNode.IsEndOfPattern)
{
currentChildNode.IsEndOfPattern = true;
currentChildNode.Replacement = currentNode.Replacement;
}

queue.Enqueue(currentChildNode);
Expand Down
3 changes: 3 additions & 0 deletions src/Mnemonic.Strings/Mnemonic.Strings.csproj
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\common.props" />
<ItemGroup>
<PackageReference Include="ZString" Version="2.5.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Mnemonic.Utilities\Mnemonic.Utilities.csproj" />
</ItemGroup>
Expand Down

0 comments on commit b7391e7

Please sign in to comment.