Struct drop_tracker::DropItem
source · [−]pub struct DropItem { /* private fields */ }Expand description
An item that will notify the parent DropTracker once it gets dropped.
DropItem instances are created by DropTracker::track. Items do not store any information
about the key that was passed to track. To check whether an item is alive or has been
dropped, use DropTracker::state or see the documentation for DropTracker for
alternatives.
DropItem does not implement the Clone trait as it would introduce ambiguity with respect
to understanding what has been dropped and what is alive.
Double drop
DropItem instances can be dropped twice or more. Doing so will cause a panic, but will not
cause undefined behavior (unless you’re calling drop on an invalid memory location). The panic
on double drop is an useful feature to detect logic errors in destructors.
Equality, ordering and hashing
The DropItem instances returned by DropTracker::track() do not implement any of the
standard traits like PartialEq, PartialOrd or Hash. This is a deliberate choice
to keep the implementation simple and to avoid enforcing a particular behavior of items.
If you wish to implement standard traits on items or associate data to them, consider using the new type pattern.
Here is an example of how the new type pattern can be used to place DropItem instances inside
a HashSet:
use std::borrow::Borrow;
use std::hash::{Hash, Hasher};
use drop_tracker::DropItem;
#[derive(Debug)]
struct StringDropItem {
s: String,
_d: DropItem,
}
impl PartialEq for StringDropItem {
fn eq(&self, other: &Self) -> bool {
self.s == other.s
}
}
impl Eq for StringDropItem {
}
impl Hash for StringDropItem {
fn hash<H: Hasher>(&self, state: &mut H) {
self.s.hash(state)
}
}
impl Borrow<str> for StringDropItem {
fn borrow(&self) -> &str {
&self.s
}
}
// Now DropItems can be used inside HashSet
use std::collections::HashSet;
use drop_tracker::DropTracker;
let mut tracker = DropTracker::new();
let mut set = HashSet::from([
StringDropItem { s: String::from("first"), _d: tracker.track(1) },
StringDropItem { s: String::from("second"), _d: tracker.track(2) },
StringDropItem { s: String::from("third"), _d: tracker.track(3) },
]);
set.remove("third");
tracker.state(&1).alive().expect("first should be alive");
tracker.state(&2).alive().expect("second should be alive");
tracker.state(&3).dropped().expect("third should be dropped");Trait Implementations
Auto Trait Implementations
impl RefUnwindSafe for DropItem
impl Send for DropItem
impl Sync for DropItem
impl Unpin for DropItem
impl UnwindSafe for DropItem
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more