use std::cmp;
use crate::depot::heap;
pub(in crate::depot) struct Hole<'a, S: heap::raw::Source> {
pub(in crate::depot) owner: &'a mut S,
pub(in crate::depot) value: S::Value,
pub(in crate::depot) position: usize,
}
impl<S: heap::raw::Source> Hole<'_, S> {
pub(in crate::depot) unsafe fn commit<const PLACE: bool>(self) {
unsafe { self.owner.write::<PLACE>(self.position, self.value) };
}
pub(in crate::depot::heap) unsafe fn shift(&mut self, source: usize) {
unsafe { self.owner.shift(source, self.position) };
self.position = source;
}
pub(in crate::depot::heap) unsafe fn up(
&mut self,
mut compare: impl FnMut(&S, usize, &S::Value) -> cmp::Ordering,
) {
while self.position != 0 {
let parent = (self.position - 1) / 2;
if !compare(self.owner, parent, &self.value).is_lt() {
break;
}
unsafe { self.shift(parent) };
}
}
pub(in crate::depot::heap) unsafe fn down(
&mut self,
len: usize,
mut compare: impl FnMut(&S, usize, &S::Value) -> cmp::Ordering,
) {
while len >= 2 && self.position <= (len - 2) / 2 {
let left = self.position * 2 + 1;
let right = left + 1;
let child = left
+ usize::from(right < len && unsafe { self.owner.compare_at(right, left) }.is_lt());
if !compare(self.owner, child, &self.value).is_gt() {
break;
}
unsafe { self.shift(child) };
}
}
pub(in crate::depot) unsafe fn repair(
&mut self,
len: usize,
mut compare: impl FnMut(&S, usize, &S::Value) -> cmp::Ordering,
) {
if self.position != 0 {
let parent = (self.position - 1) / 2;
if compare(self.owner, parent, &self.value).is_lt() {
unsafe {
self.shift(parent);
self.up(compare);
}
return;
}
}
unsafe { self.down(len, compare) };
}
}