use combinators::NaturalOrder;
use std::cmp::Ordering;
use std::fmt;
use std::iter::{FromIterator, FusedIterator};
use std::mem::{size_of, swap, ManuallyDrop};
use std::ops::{Deref, DerefMut};
use std::ptr;
use std::slice;
use std::vec;
use Comparator;
pub struct BinaryHeap<T, U = NaturalOrder> {
data: Vec<T>,
comparator: U,
}
pub struct PeekMut<'a, T, U>
where
T: 'a,
U: 'a + Comparator<T>,
{
heap: &'a mut BinaryHeap<T, U>,
sift: bool,
}
impl<'a, T, U> fmt::Debug for PeekMut<'a, T, U>
where
T: fmt::Debug,
U: Comparator<T>,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("PeekMut").field(&self.heap.data[0]).finish()
}
}
impl<'a, T, U> Drop for PeekMut<'a, T, U>
where
U: Comparator<T>,
{
fn drop(&mut self) {
if self.sift {
self.heap.sift_down(0);
}
}
}
impl<'a, T, U> Deref for PeekMut<'a, T, U>
where
U: Comparator<T>,
{
type Target = T;
fn deref(&self) -> &T {
&self.heap.data[0]
}
}
impl<'a, T, U> DerefMut for PeekMut<'a, T, U>
where
U: Comparator<T>,
{
fn deref_mut(&mut self) -> &mut T {
&mut self.heap.data[0]
}
}
impl<'a, T, U> PeekMut<'a, T, U>
where
U: Comparator<T>,
{
pub fn pop(mut this: PeekMut<'a, T, U>) -> T {
let value = this.heap.pop().unwrap();
this.sift = false;
value
}
}
impl<T: Clone, U: Clone> Clone for BinaryHeap<T, U> {
fn clone(&self) -> Self {
Self {
data: self.data.clone(),
comparator: self.comparator.clone(),
}
}
fn clone_from(&mut self, source: &Self) {
self.data.clone_from(&source.data);
self.comparator.clone_from(&source.comparator);
}
}
impl<T, U> Default for BinaryHeap<T, U>
where
U: Comparator<T> + Default,
{
fn default() -> Self {
Self::with_comparator(U::default())
}
}
impl<T, U> fmt::Debug for BinaryHeap<T, U>
where
T: fmt::Debug + Ord,
U: Comparator<T>,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list().entries(self.iter()).finish()
}
}
impl<T> BinaryHeap<T>
where
T: Ord,
{
pub fn new() -> Self {
Self::default()
}
}
impl<T, U> BinaryHeap<T, U>
where
U: Default,
{
pub fn with_capacity(capacity: usize) -> Self {
Self {
data: Vec::with_capacity(capacity),
comparator: U::default(),
}
}
}
impl<T, U> BinaryHeap<T, U>
where
U: Comparator<T>,
{
pub fn with_comparator(comparator: U) -> Self {
Self {
data: Vec::new(),
comparator,
}
}
pub fn iter(&self) -> Iter<T> {
Iter {
iter: self.data.iter(),
}
}
pub fn peek(&self) -> Option<&T> {
self.data.get(0)
}
pub fn peek_mut(&mut self) -> Option<PeekMut<T, U>> {
if self.is_empty() {
None
} else {
Some(PeekMut {
heap: self,
sift: true,
})
}
}
pub fn capacity(&self) -> usize {
self.data.capacity()
}
pub fn reserve_exact(&mut self, additional: usize) {
self.data.reserve_exact(additional);
}
pub fn reserve(&mut self, additional: usize) {
self.data.reserve(additional);
}
pub fn shrink_to_fit(&mut self) {
self.data.shrink_to_fit();
}
pub fn pop(&mut self) -> Option<T> {
self.data.pop().map(|mut item| {
if !self.is_empty() {
swap(&mut item, &mut self.data[0]);
self.sift_down_to_bottom(0);
}
item
})
}
pub fn push(&mut self, item: T) {
let old_len = self.len();
self.data.push(item);
self.sift_up(0, old_len);
}
pub fn into_vec(self) -> Vec<T> {
self.data
}
pub fn into_sorted_vec(mut self) -> Vec<T> {
let mut end = self.len();
while end > 1 {
end -= 1;
self.data.swap(0, end);
self.sift_down_range(0, end);
}
self.into_vec()
}
fn sift_up(&mut self, start: usize, pos: usize) -> usize {
unsafe {
let mut hole = Hole::new(&mut self.data, pos);
while hole.pos() > start {
let parent = (hole.pos() - 1) / 2;
if self.comparator.compare(&hole.element(), &hole.get(parent)) != Ordering::Greater
{
break;
}
hole.move_to(parent);
}
hole.pos()
}
}
fn sift_down_range(&mut self, pos: usize, end: usize) {
unsafe {
let mut hole = Hole::new(&mut self.data, pos);
let mut child = 2 * pos + 1;
while child < end {
let right = child + 1;
if right < end
&& self.comparator.compare(&hole.get(child), hole.get(right))
!= Ordering::Greater
{
child = right;
}
if self.comparator.compare(&hole.element(), &hole.get(child)) != Ordering::Less {
break;
}
hole.move_to(child);
child = 2 * hole.pos() + 1;
}
}
}
fn sift_down(&mut self, pos: usize) {
let len = self.len();
self.sift_down_range(pos, len);
}
fn sift_down_to_bottom(&mut self, mut pos: usize) {
let end = self.len();
let start = pos;
unsafe {
let mut hole = Hole::new(&mut self.data, pos);
let mut child = 2 * pos + 1;
while child < end {
let right = child + 1;
if right < end
&& self.comparator.compare(&hole.get(child), &hole.get(right))
!= Ordering::Greater
{
child = right;
}
hole.move_to(child);
child = 2 * hole.pos() + 1;
}
pos = hole.pos;
}
self.sift_up(start, pos);
}
pub fn len(&self) -> usize {
self.data.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn drain(&mut self) -> Drain<T> {
Drain {
iter: self.data.drain(..),
}
}
pub fn clear(&mut self) {
self.drain();
}
fn rebuild(&mut self) {
let mut n = self.len() / 2;
while n > 0 {
n -= 1;
self.sift_down(n);
}
}
pub fn append<W>(&mut self, other: &mut BinaryHeap<T, W>)
where
W: Comparator<T>,
{
#[inline(always)]
fn log2_fast(x: usize) -> usize {
8 * size_of::<usize>() - (x.leading_zeros() as usize) - 1
}
#[inline]
fn better_to_rebuild(len1: usize, len2: usize) -> bool {
2 * (len1 + len2) < len2 * log2_fast(len1)
}
if other.is_empty() {
return;
}
if better_to_rebuild(self.len(), other.len()) {
self.data.append(&mut other.data);
self.rebuild();
} else {
self.extend(other.drain());
}
}
}
struct Hole<'a, T: 'a> {
data: &'a mut [T],
elt: ManuallyDrop<T>,
pos: usize,
}
impl<'a, T> Hole<'a, T> {
#[inline]
unsafe fn new(data: &'a mut [T], pos: usize) -> Self {
debug_assert!(pos < data.len());
let elt = ptr::read(&data[pos]);
Hole {
data,
elt: ManuallyDrop::new(elt),
pos,
}
}
#[inline]
fn pos(&self) -> usize {
self.pos
}
#[inline]
fn element(&self) -> &T {
&self.elt
}
#[inline]
unsafe fn get(&self, index: usize) -> &T {
debug_assert!(index != self.pos);
debug_assert!(index < self.data.len());
self.data.get_unchecked(index)
}
#[inline]
unsafe fn move_to(&mut self, index: usize) {
debug_assert!(index != self.pos);
debug_assert!(index < self.data.len());
let index_ptr: *const _ = self.data.get_unchecked(index);
let hole_ptr = self.data.get_unchecked_mut(self.pos);
ptr::copy_nonoverlapping(index_ptr, hole_ptr, 1);
self.pos = index;
}
}
impl<'a, T> Drop for Hole<'a, T> {
#[inline]
fn drop(&mut self) {
unsafe {
let pos = self.pos;
ptr::copy_nonoverlapping(&*self.elt, self.data.get_unchecked_mut(pos), 1);
}
}
}
pub struct Iter<'a, T: 'a> {
iter: slice::Iter<'a, T>,
}
impl<'a, T: 'a + fmt::Debug> fmt::Debug for Iter<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("Iter").field(&self.iter.as_slice()).finish()
}
}
impl<'a, T> Clone for Iter<'a, T> {
fn clone(&self) -> Iter<'a, T> {
Iter {
iter: self.iter.clone(),
}
}
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
#[inline]
fn next(&mut self) -> Option<&'a T> {
self.iter.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl<'a, T> DoubleEndedIterator for Iter<'a, T> {
#[inline]
fn next_back(&mut self) -> Option<&'a T> {
self.iter.next_back()
}
}
impl<'a, T> ExactSizeIterator for Iter<'a, T> {}
impl<'a, T> FusedIterator for Iter<'a, T> {}
pub struct IntoIter<T> {
iter: vec::IntoIter<T>,
}
impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_tuple("IntoIter")
.field(&self.iter.as_slice())
.finish()
}
}
impl<T> Iterator for IntoIter<T> {
type Item = T;
#[inline]
fn next(&mut self) -> Option<T> {
self.iter.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl<T> DoubleEndedIterator for IntoIter<T> {
#[inline]
fn next_back(&mut self) -> Option<T> {
self.iter.next_back()
}
}
impl<T> ExactSizeIterator for IntoIter<T> {}
impl<T> FusedIterator for IntoIter<T> {}
pub struct Drain<'a, T: 'a> {
iter: vec::Drain<'a, T>,
}
impl<'a, T: 'a> Iterator for Drain<'a, T> {
type Item = T;
#[inline]
fn next(&mut self) -> Option<T> {
self.iter.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> {
#[inline]
fn next_back(&mut self) -> Option<T> {
self.iter.next_back()
}
}
impl<'a, T: 'a> ExactSizeIterator for Drain<'a, T> {}
impl<'a, T: 'a> FusedIterator for Drain<'a, T> {}
impl<T, U> From<Vec<T>> for BinaryHeap<T, U>
where
U: Comparator<T> + Default,
{
fn from(vec: Vec<T>) -> Self {
let mut heap = Self {
data: vec,
comparator: U::default(),
};
heap.rebuild();
heap
}
}
impl<T, U> FromIterator<T> for BinaryHeap<T, U>
where
U: Comparator<T> + Default,
{
fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
Self::from(iter.into_iter().collect::<Vec<_>>())
}
}
impl<T, U> IntoIterator for BinaryHeap<T, U> {
type Item = T;
type IntoIter = IntoIter<T>;
fn into_iter(self) -> IntoIter<T> {
IntoIter {
iter: self.data.into_iter(),
}
}
}
impl<'a, T, U> IntoIterator for &'a BinaryHeap<T, U>
where
U: Comparator<T>,
{
type Item = &'a T;
type IntoIter = Iter<'a, T>;
fn into_iter(self) -> Iter<'a, T> {
self.iter()
}
}
impl<T, U> Extend<T> for BinaryHeap<T, U>
where
U: Comparator<T>,
{
#[inline]
fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
let iterator = iter.into_iter();
let (lower, _) = iterator.size_hint();
self.reserve(lower);
for elem in iterator {
self.push(elem);
}
}
}
impl<'a, T, U> Extend<&'a T> for BinaryHeap<T, U>
where
T: 'a + Ord + Copy,
U: Comparator<T>,
{
fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
self.extend(iter.into_iter().cloned());
}
}