#`::safe-manually-drop`

11 messages · Page 1 of 1 (latest)

swift elk
#

https://docs.rs/safe-manually-drop

A type-level-based (rather than macro-based) equivalent to #1362168564710117476 message: a convenience wrapper type —and trait!— to expose owned access to a field when customizing the drop glue of your type.

#![forbid(unsafe_code)]

use ::safe_manually_drop::{DropManually, SafeManuallyDrop};

struct Defer<F: FnOnce()>(
    SafeManuallyDrop<F, Self>,
);

/// No `unsafe`, no `.unwrap()`s, no macros.
impl<F: FnOnce()> DropManually<F> for Defer<F> {
    fn drop_manually(f: F) {
        f();
    }
}

There is a whole dedicated section in the docs which is blog-post worthy, about Drop::drop() vs. mem::drop() vs. ptr::drop_in_place() ferrisNerd

.

GitHub

ManuallyDrop "owned field" pattern with no unsafe, no .unwrap()s, no macros - danielhenrymantilla/safe-manually-drop.rs

flat patio
#

typical yandros w ferrisCatOwO

past pebble
#

Yay

jolly meteor
swift elk
# jolly meteor So if I wanted multiple owned fields in my drop I need to just wrap the struct i...

Hmm, I thought I had mentioned this somewhere in the docs, and I might have, but it does definitely not stand out enough to be discoverable 😅 I'll try to fix that docs issue soon.
For now, the example just before the https://docs.rs/safe-manually-drop/0.1.0/safe_manually_drop/struct.SafeManuallyDrop.html#explanation section ought to showcase this: yeah, you do need an extra wrapper struct (or worst case scenario, albeit ugly: a tuple)

#
#![forbid(unsafe_code)]

use ::safe_manually_drop::{DropManually, SafeManuallyDrop};

struct DeferGuardFields<T, F : FnOnce(T)> {
    value: T,
    on_drop: F,
}

pub
struct DeferGuard<T, F : FnOnce(T)>(
 // rather than `Option<DeferGuardFields<T, F>>`,
 // or `ManuallyDrop<DeferGuardFields<T, F>>`, use:
    SafeManuallyDrop<DeferGuardFields<T, F>, Self>,
);

impl<T, F : FnOnce(T)>
    DropManually<DeferGuardFields<T, F>>
for
    DeferGuard<T, F>
{
    fn drop_manually(
        DeferGuardFields { value, on_drop }: DeferGuardFields<T, F>,
    )
    {
        on_drop(value);
    }
}

impl<T, F : FnOnce(T)> ::core::ops::Deref for DeferGuard<T, F> {
    type Target = T;

    fn deref(&self) -> &T {
        &self.0.value
    }
}
// And `DerefMut`
jolly meteor
#

Ah yes

swift elk
jolly meteor
#

Since it can make adhoc structs