From 29b2c87d4390772f8ebc8bda9d3406255603d7a1 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Thu, 17 Oct 2024 13:22:00 +0200 Subject: [PATCH] Add safety preconditions to alloc/src/collections/binary_heap/mod.rs This diff adds `#[requires(...)]` attributes to the unsafe functions, translating the "SAFETY:" comments into code contracts. These contracts specify the preconditions that must be met for the function to be safely called. --- .../alloc/src/collections/binary_heap/mod.rs | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/library/alloc/src/collections/binary_heap/mod.rs b/library/alloc/src/collections/binary_heap/mod.rs index fe9f1010d327c..bae4cf04401fc 100644 --- a/library/alloc/src/collections/binary_heap/mod.rs +++ b/library/alloc/src/collections/binary_heap/mod.rs @@ -143,6 +143,10 @@ #![allow(missing_docs)] #![stable(feature = "rust1", since = "1.0.0")] +use safety::requires; +#[cfg(kani)] +use crate::kani; + use core::alloc::Allocator; use core::iter::{FusedIterator, InPlaceIterable, SourceIter, TrustedFused, TrustedLen}; use core::mem::{self, swap, ManuallyDrop}; @@ -672,6 +676,7 @@ impl BinaryHeap { /// # Safety /// /// The caller must guarantee that `pos < self.len()`. + #[requires(pos < self.len())] unsafe fn sift_up(&mut self, start: usize, pos: usize) -> usize { // Take out the value at `pos` and create a hole. // SAFETY: The caller guarantees that pos < self.len() @@ -701,6 +706,7 @@ impl BinaryHeap { /// # Safety /// /// The caller must guarantee that `pos < end <= self.len()`. + #[requires(pos < end && end <= self.len())] unsafe fn sift_down_range(&mut self, pos: usize, end: usize) { // SAFETY: The caller guarantees that pos < end <= self.len(). let mut hole = unsafe { Hole::new(&mut self.data, pos) }; @@ -741,6 +747,7 @@ impl BinaryHeap { /// # Safety /// /// The caller must guarantee that `pos < self.len()`. + #[requires(pos < self.len())] unsafe fn sift_down(&mut self, pos: usize) { let len = self.len(); // SAFETY: pos < len is guaranteed by the caller and @@ -757,6 +764,7 @@ impl BinaryHeap { /// # Safety /// /// The caller must guarantee that `pos < self.len()`. + #[requires(pos < self.len())] unsafe fn sift_down_to_bottom(&mut self, mut pos: usize) { let end = self.len(); let start = pos; @@ -1897,3 +1905,37 @@ impl<'a, T: 'a + Ord + Copy, A: Allocator> Extend<&'a T> for BinaryHeap { self.reserve(additional); } } + +#[cfg(kani)] +#[unstable(feature="kani", issue="none")] +mod verify { + use super::*; + + // unsafe fn sift_up(&mut self, start: usize, pos: usize) -> usize + #[kani::proof_for_contract(impl