Struct DeferDrop

Source
pub struct DeferDrop<T: Send + 'static> { /* private fields */ }
Expand description

Wrapper type that, when dropped, sends the inner value to a global background thread to be dropped. Useful in cases where a value takes a long time to drop (for instance, a windows file that might block on close, or a large data structure that has to extensively recursively trawl itself).

DeferDrop implements Deref and DerefMut, meaning it can be dereferenced and freely used like a container around its inner type.

§Notes:

Carefully consider whether this pattern is necessary for your use case. Like all worker-thread abstractions, sending the value to a separate thread comes with its own costs, so it should only be done if performance profiling indicates that it’s a performance gain.

There is only one global worker thread. Dropped values are enqueued in an unbounded channel to be consumed by this thread; if you produce more garbage than the thread can handle, this will cause unbounded memory consumption. There is currently no way for the thread to signal or block if it is overwhelmed.

All of the standard non-determinism threading caveats apply here. The objects are guaranteed to be destructed in the order received through a channel, which means that objects sent from a single thread will be destructed in order. However, there is no guarantee about the ordering of interleaved values from different threads. Additionally, there are no guarantees about how long the values will be queued before being dropped, or even that they will be dropped at all. If your main thread terminates before all drops could be completed, they will be silently lost (as though via a mem::forget). This behavior is entirely up to your OS’s thread scheduler. There is no way to receive a signal indicating when a particular object was dropped.

§Example

use defer_drop::DeferDrop;
use std::time::{Instant, Duration};
use std::iter::repeat_with;

let massive_vec: Vec<Vec<i32>> = repeat_with(|| vec![1, 2, 3])
    .take(1_000_000)
    .collect();

let deferred = DeferDrop::new(massive_vec.clone());

fn timer(f: impl FnOnce()) -> Duration {
    let start = Instant::now();
    f();
    Instant::now() - start
}

let drop1 = timer(move || drop(massive_vec));
let drop2 = timer(move || drop(deferred));

assert!(drop2 < drop1);

Implementations§

Source§

impl<T: Send + 'static> DeferDrop<T>

Source

pub fn new(value: T) -> Self

Create a new DeferDrop value.

Examples found in repository?
examples/demo.rs (line 23)
11fn main() {
12    println!("Allocating a ridiculously large vector");
13    let vec1: Vec<Vec<String>> = repeat_with(|| {
14        repeat_with(|| "Hello, World".to_string())
15            .take(1000)
16            .collect()
17    })
18    .take(1000)
19    .collect();
20
21    println!("Duplicating that vector");
22    let vec2 = vec1.clone();
23    let defer_vec1 = DeferDrop::new(vec1);
24
25    println!("Dropping the vectors");
26
27    let vec1_timer = timer(move || drop(defer_vec1));
28    let vec2_timer = timer(move || drop(vec2));
29
30    println!("Duration of deferred drop: {:?}", vec1_timer);
31    println!("Duration of foreground drop: {:?}", vec2_timer);
32}
Source

pub fn into_inner(this: Self) -> T

Unwrap the DeferDrop, returning the inner value. This has the effect of cancelling the deferred drop behavior; ownership of the inner value is transferred to the caller.

Trait Implementations§

Source§

impl<T: Send + 'static> AsMut<T> for DeferDrop<T>

Source§

fn as_mut(&mut self) -> &mut T

Converts this type into a mutable reference of the (usually inferred) input type.
Source§

impl<T: Send + 'static> AsRef<T> for DeferDrop<T>

Source§

fn as_ref(&self) -> &T

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl<T: Clone + Send + 'static> Clone for DeferDrop<T>

Source§

fn clone(&self) -> DeferDrop<T>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Debug + Send + 'static> Debug for DeferDrop<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: Default + Send + 'static> Default for DeferDrop<T>

Source§

fn default() -> DeferDrop<T>

Returns the “default value” for a type. Read more
Source§

impl<T: Send + 'static> Deref for DeferDrop<T>

Source§

type Target = T

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl<T: Send + 'static> DerefMut for DeferDrop<T>

Source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
Source§

impl<'de, T: Deserialize<'de> + Send + 'static> Deserialize<'de> for DeferDrop<T>

Source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl<T: Send + 'static> Drop for DeferDrop<T>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

impl<T: Send + 'static> From<T> for DeferDrop<T>

Source§

fn from(value: T) -> Self

Converts to this type from the input type.
Source§

impl<T: Hash + Send + 'static> Hash for DeferDrop<T>

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl<T: Ord + Send + 'static> Ord for DeferDrop<T>

Source§

fn cmp(&self, other: &DeferDrop<T>) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl<T: PartialEq + Send + 'static> PartialEq for DeferDrop<T>

Source§

fn eq(&self, other: &DeferDrop<T>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl<T: PartialOrd + Send + 'static> PartialOrd for DeferDrop<T>

Source§

fn partial_cmp(&self, other: &DeferDrop<T>) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl<T: Serialize + Send + 'static> Serialize for DeferDrop<T>

Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl<T: Eq + Send + 'static> Eq for DeferDrop<T>

Source§

impl<T: Send + 'static> StructuralPartialEq for DeferDrop<T>

Auto Trait Implementations§

§

impl<T> Freeze for DeferDrop<T>
where T: Freeze,

§

impl<T> RefUnwindSafe for DeferDrop<T>
where T: RefUnwindSafe,

§

impl<T> Send for DeferDrop<T>

§

impl<T> Sync for DeferDrop<T>
where T: Sync,

§

impl<T> Unpin for DeferDrop<T>
where T: Unpin,

§

impl<T> UnwindSafe for DeferDrop<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<!> for T

Source§

fn from(t: !) -> T

Converts to this type from the input type.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,