Regarding your code, I feel a little bad about just shooting down your implementation out of the gate, so here are some (hopefully constructive) comments.
I do think there is some unsafe
that doesn't look necessary. For instance, sort_heap
is an unsafe fn
, which seems unnecessary (maybe a holdover from earlier versions?). Removing unsafe
from sort_heap
lets you shrink the scope of unsafe
in partial_sort
. Speaking of partial_sort
, I think the effort you go to
unsafe {
for i in last..v.len() {
if is_less(v.get_unchecked(i), v.get_unchecked(0)) {
v.swap(0, i);
...
to avoid bounds checks is probably not pulling its weight here, since v.swap
will check them anyway (there's no swap_unchecked
) and additional checks against the same bounds are very likely to be optimized away. I'd suspect the following is no slower:
for x in &v[last..] {
if is_less(x, &v[0]) {
...
In adjust_heap
almost the entire function body is wrapped in a single unsafe
block that isn't marked with any comments about safety, despite the fact that adjust_heap
itself is a safe function, so it's hard to really audit effectively because it's all tightly coupled.
There is some ambiguity about the "proper" scope for unsafe
. Some people feel that you should put an unsafe
block around all the closely related code that can easily lead to unsafety. I tend to think that unsafe
should normally be about as small as the compiler will allow, which lets you more easily audit one block at a time. Four one-line unsafe
blocks is better, in my opinion, than one big one, since those four little ones almost certainly have slightly different reasons why they are really safe. But people can reasonably differ on this subject.
One more thing about adjust_heap
is that it actually should be marked unsafe
because it's possible to pass a len
that's larger than v.len()
and cause unsafety with it. Yeah, it's an internal API, but it should be possible to make adjust_heap
safe to call, so I recommend doing that.
I'm dozing off, so I have to go to sleep, but hopefully this helps some!