Fixed Natural Sorting causing an infinite loop

This commit is contained in:
adroslice 2019-11-24 02:45:09 +01:00
parent 0d56d66809
commit 00b4f26a3d

View File

@ -46,16 +46,15 @@ namespace BFR.Operations
files.ReplaceAll(new List<FileModel>(files.Reverse())); files.ReplaceAll(new List<FileModel>(files.Reverse()));
} }
// Code taken and slightly modified from https://git.lastassault.de/speatzle/BulkFileRenamer // Using code from stackoverflow
// https://stackoverflow.com/questions/248603/natural-sort-order-in-c-sharp
public static int CompareNatural(string strA, string strB) => public static int CompareNatural(string strA, string strB) =>
CompareNatural(strA, strB, CultureInfo.CurrentCulture, CompareOptions.IgnoreCase); CompareNatural(strA, strB, CultureInfo.CurrentCulture, CompareOptions.IgnoreCase);
public static int CompareNatural(string strA, string strB, CultureInfo culture, CompareOptions options) public static int CompareNatural(string strA, string strB, CultureInfo culture, CompareOptions options)
{ {
var cmp = culture.CompareInfo; var cmp = culture.CompareInfo;
var (iA, iB) = (0, 0); var (iA, iB, softResult, softResultWeight) = (0, 0, 0, 0);
var softResult = 0;
var softResultWeight = 0;
while (iA < strA.Length && iB < strB.Length) while (iA < strA.Length && iB < strB.Length)
{ {
var isDigitA = char.IsDigit(strA[iA]); var isDigitA = char.IsDigit(strA[iA]);
@ -64,8 +63,7 @@ namespace BFR.Operations
return cmp.Compare(strA, iA, strB, iB, options); return cmp.Compare(strA, iA, strB, iB, options);
else if (!isDigitA && !isDigitB) else if (!isDigitA && !isDigitB)
{ {
var jA = iA + 1; var (jA, jB) = (iA + 1, iB + 1);
var jB = iB + 1;
while (jA < strA.Length && !char.IsDigit(strA[jA])) jA++; while (jA < strA.Length && !char.IsDigit(strA[jA])) jA++;
while (jB < strB.Length && !char.IsDigit(strB[jB])) jB++; while (jB < strB.Length && !char.IsDigit(strB[jB])) jB++;
var cmpResult = cmp.Compare(strA, iA, jA - iA, strB, iB, jB - iB, options); var cmpResult = cmp.Compare(strA, iA, jA - iA, strB, iB, jB - iB, options);
@ -81,7 +79,8 @@ namespace BFR.Operations
softResultWeight = 1; softResultWeight = 1;
} }
} }
(iA, jA) = (iB, jB); iA = jA;
iB = jB;
} }
else else
{ {
@ -90,7 +89,7 @@ namespace BFR.Operations
var (jA, jB) = (iA, iB); var (jA, jB) = (iA, iB);
while (jA < strA.Length && strA[jA] == zeroA) jA++; while (jA < strA.Length && strA[jA] == zeroA) jA++;
while (jB < strB.Length && strB[jB] == zeroB) jB++; while (jB < strB.Length && strB[jB] == zeroB) jB++;
int resultIfSameLength = 0; var resultIfSameLength = 0;
do do
{ {
isDigitA = jA < strA.Length && char.IsDigit(strA[jA]); isDigitA = jA < strA.Length && char.IsDigit(strA[jA]);
@ -106,8 +105,7 @@ namespace BFR.Operations
jA++; jA++;
jB++; jB++;
} }
} } while (isDigitA && isDigitB);
while (isDigitA && isDigitB);
if (isDigitA != isDigitB) if (isDigitA != isDigitB)
return isDigitA ? 1 : -1; return isDigitA ? 1 : -1;
else if (resultIfSameLength != 0) else if (resultIfSameLength != 0)