镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Leave an OrderedCollection unchanged when its comparer throws during AddRange [patch] - #160

Open
matt-edmondson wants to merge 2 commits into
mainfrom
fix/ordered-collection-addrange-throwing-comparer-158
Open

matt-edmondson wants to merge 2 commits into
mainfrom
fix/ordered-collection-addrange-throwing-comparer-158

Conversation

@matt-edmondson

Copy link
Copy Markdown
Contributor

Fixes #158

What was wrong

For a batch over 16 elements, OrderedCollection<T>.AddRange grew the backing list and then merged in place from the back. The merge is the first place new elements are compared with existing ones, so a comparer that threw there left the list grown and partly overwritten. The collection ended up unsorted, with some elements duplicated and others lost.

Change

  • AddRange now merges into a new T[] and replaces the list contents only after the merge completes, which is what OrderedMap.AddRange already does. Ties still place the added element after the existing one.
  • Two tests:
    • AddRange_ComparerThrowsDuringMerge_LeavesCollectionUnchanged uses the repro from the issue (17 elements, a comparer that throws on 30). It fails on main and passes with the fix.
    • AddRange_ComparerThrowsOnSmallBatch_LeavesCollectionSorted pins the small-batch path: after a throw the collection is still sorted, keeps its original elements, and has no duplicates.

Verification

  • Reverted the fix and reran the two tests: the merge-path test fails. Restored the fix: it passes.
  • Full suite: 581/581 passed.

Generated by Claude Code

…AddRange [patch]

The bulk path of AddRange grew the backing list and merged in place from
the back, so a comparer that threw partway left the collection unsorted,
with some elements duplicated and others lost. Merge into a new array and
swap it in only once the merge finishes, as OrderedMap.AddRange does.

Fixes #158

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017vfJW3k7ndhCVDCcjtiA4W
@sonarqubecloud

Copy link
Copy Markdown

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.

A comparer that throws during OrderedCollection.AddRange (batch > 16) leaves the collection unsorted, with duplicated and lost elements

2 participants