Skip to content

Fix natural numeric ordering for chunks beyond Int32 range - #42

Merged
matt-edmondson merged 2 commits into
mainfrom
copilot/fix-naturalstringcomparer-numeric-order
Sep 13, 2026
Merged

matt-edmondson merged 2 commits into
mainfrom
copilot/fix-naturalstringcomparer-numeric-order

Conversation

Copilot AI commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

NaturalStringComparer treated large digit runs as plain strings when int.TryParse overflowed, which inverted ordering for values like 9999999999 vs 10000000000. This change makes numeric chunk comparison size-unbounded and adds a regression case at the Int32 boundary.

  • Comparer logic

    • Replaced int.TryParse-based numeric comparison with digit-chunk comparison that:
      • trims leading zeros
      • compares normalized chunk length first
      • falls back to ordinal digit comparison when lengths match
    • Preserves natural numeric ordering for arbitrarily large numeric substrings.
  • Regression coverage

    • Extended Compare_LargeNumbers_HandledCorrectly with a boundary-crossing case:
      • "file9999999999" sorts before "file10000000000".
private static int CompareNumericChunks(string xChunk, string yChunk)
{
    string xTrimmed = xChunk.TrimStart('0');
    string yTrimmed = yChunk.TrimStart('0');

    if (xTrimmed.Length == 0) xTrimmed = "0";
    if (yTrimmed.Length == 0) yTrimmed = "0";

    int lengthComparison = xTrimmed.Length.CompareTo(yTrimmed.Length);
    if (lengthComparison != 0) return lengthComparison;

    return string.Compare(xTrimmed, yTrimmed, StringComparison.Ordinal);
}

Co-authored-by: matt-edmondson <19528727+matt-edmondson@users.noreply.github.com>
Copilot AI changed the title [WIP] Fix numeric chunk ordering in NaturalStringComparer Fix natural numeric ordering for chunks beyond Int32 range Sep 13, 2026
@matt-edmondson
matt-edmondson marked this pull request as ready for review September 13, 2026 11:53
@sonarqubecloud

Copy link
Copy Markdown

@matt-edmondson
matt-edmondson merged commit 2db315a into main Sep 13, 2026
12 checks passed
@matt-edmondson
matt-edmondson deleted the copilot/fix-naturalstringcomparer-numeric-order branch September 13, 2026 12:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

NaturalStringComparer mis-orders numeric chunks of 10+ digits due to Int32 overflow fallback

2 participants