#drop #resources #linear #derive #macro-derive

dispose

A simple wrapper for values that must be consumed on drop

7 releases (4 breaking)

0.5.0 Jul 31, 2023
0.4.0 Nov 12, 2021
0.3.1 Jul 3, 2021
0.2.1 Oct 20, 2020
0.1.0 Jun 20, 2020

#536 in Rust patterns

Download history 3401/week @ 2024-03-14 3074/week @ 2024-03-21 4286/week @ 2024-03-28 6507/week @ 2024-04-04 9028/week @ 2024-04-11 5646/week @ 2024-04-18 5107/week @ 2024-04-25 7867/week @ 2024-05-02 5645/week @ 2024-05-09 5332/week @ 2024-05-16 9050/week @ 2024-05-23 7207/week @ 2024-05-30 4702/week @ 2024-06-06 7967/week @ 2024-06-13 5877/week @ 2024-06-20 18663/week @ 2024-06-27

38,343 downloads per month
Used in 5 crates (4 directly)

MIT/Apache

19KB
211 lines

A small crate for handling resources that must be consumed at the end of their lifetime.

Since Rust's type system is affine rather than linear, Drop::drop mutably borrows self, rather than consuming it. For the most part, this is fine, but for some cases (such as working with the crate gfx_hal) resources must be consumed on drop. This crate and the dispose_derive crate serve to cover the typical boilerplate for such cases by managing the ManuallyDrop wrapper for you. (See the Dispose derive macro for more info on that)

As a bonus, this crate makes it easy to defer the execution of an FnOnce closure to the end of a scope, which can be done using the defer function.

NOTE: The Dispose trait does not provide a Drop impl by itself. For that, a value implementing Dispose must be wrapped in a Disposable struct.

Examples

use dispose::{Dispose, Disposable};

struct MyStruct;

impl Dispose for MyStruct {
    fn dispose(self) { println!("Goodbye, world!"); }
}

{
    let _my_struct = Disposable::new(MyStruct);
} // prints "Goodbye, world!"

As a design consideration, values implementing Dispose should always be returned wrapped in Disposable or any other wrapper properly implementing Drop. Disposable is recommended as it contains an unsafe leak function to retrieve the inner value, if necessary.

use dispose::{Dispose, Disposable};

mod secrets {

    pub struct Secrets {
        launch_codes: u32,
    }

    impl Secrets {
        pub fn new(launch_codes: u32) -> Disposable<Self> {
            Self { launch_codes }.into()
        }
    }

    impl Dispose for Secrets {
        fn dispose(mut self) { self.launch_codes = 0x0; } // Nice try, hackers!
    }
}

fn main() {
    let secret = secrets::Secrets::new(0xDEADBEEF);
} // secret is properly disposed at the end of the scope

fn BAD() {
    let secret = secrets::Secrets::new(0o1337);

    let mwahaha = unsafe { Disposable::leak(secret) };
} // .dispose() was not called - data has been leaked!

(My lawyers have advised me to note that the above example is not cryptographically secure. Please do not clean up secure memory by simply setting it to zero.)

Dependencies

~0.3–0.8MB
~19K SLoC