fix: empty slice panics in bead_sort, bogo_sort, comb_sort and wave_sort - #1063
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #1063 +/- ##
==========================================
+ Coverage 95.89% 95.90% +0.01%
==========================================
Files 396 396
Lines 30440 30492 +52
==========================================
+ Hits 29190 29243 +53
+ Misses 1250 1249 -1 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
This pull request has been automatically marked as abandoned because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. |
|
Still relevant and ready for review, all 7 checks are green and Codecov reports every modified line covered. Recapping the impact: four sorts panic on an empty slice where the other 30 in the module no-op. @imp2002 would you have a moment to take a look? |
Pull Request Template
Description
Four algorithms in
src/sorting/panic when handed an empty slice. Sorting nothing shouldbe a no-op, and the other 30 sorts in the module already treat it that way — 20 of them have
an explicit
empty()test. These four were simply never exercised on that input.Each is an unsigned underflow or an unchecked first-element read:
bead_sort—let mut max = a[0];reads element0before checking the slice isnon-empty. Now returns early; there is no bead grid to build.
bogo_sort— the privateis_sortedhelper loopsfor i in 0..len - 1, whichunderflows to
usize::MAXatlen == 0. Rewritten withwindows(2), which naturallyyields nothing below two elements. This also drops a hand-rolled loop in favour of the
same idiom
sorting::is_sortedalready uses.comb_sort—gapis clamped to a minimum of1, sofor i in 0..arr.len() - gapunderflows at
arr.len() == 0. Now returns early for fewer than two elements.wave_sort—for i in (0..n - 1).step_by(2)underflows atn == 0. Now usesn.saturating_sub(1).These are release-mode hazards as well as debug-mode panics: with overflow checks off, the
underflowed bound becomes a near-
usize::MAXloop bound and the sort runs off the end ofthe slice.
Tests
emptyandone_elementcases added to all four, following the module's existingconvention of asserting with the shared
is_sorted/have_same_elementshelpers.bead_sortalso gains anall_zeroescase, since a maximum of0is the other way itsbead grid can end up with zero columns. All new tests run in well under 300ms.
Type of change
Checklist:
cargo clippy --all -- -D warningsjust before my last commit and fixed any issue that was found.cargo fmtjust before my last commit.cargo testjust before my last commit and all tests passed.mod.rsfile within its own folder, and in any parent folder(s).DIRECTORY.mdwith the correct link.COUNTRIBUTING.mdand my code follows its guidelines.