wutil/
wrappers.rs

1use core::{
2    mem::ManuallyDrop,
3    ops::{Deref, DerefMut},
4};
5
6/// A wrapper that guarentees that the dropper of the underlying object cannot be safely called.
7#[repr(transparent)]
8pub struct DontDrop<T>(ManuallyDrop<T>);
9
10impl<T> DontDrop<T> {
11    pub const fn new(value: T) -> Self {
12        Self(ManuallyDrop::new(value))
13    }
14
15    /// Gets the underlying value.
16    /// # Safety
17    /// At least one of the following must be upheld
18    /// - The inner value cannot be dropped
19    /// - The circumstances outlined in the safety section of [DontDrop::drop]
20    pub const unsafe fn into_inner(self) -> T {
21        core::mem::ManuallyDrop::into_inner(self.0)
22    }
23
24    /// Drops the underlying value.
25    /// # Safety
26    /// Documentation from the provider of this value may specify
27    /// circumstances where this function is safe to call.
28    pub unsafe fn drop(self) {
29        core::mem::drop(core::mem::ManuallyDrop::into_inner(self.0));
30    }
31}
32
33impl<T> From<T> for DontDrop<T> {
34    fn from(value: T) -> Self {
35        Self::new(value)
36    }
37}
38
39impl<T> AsRef<T> for DontDrop<T> {
40    fn as_ref(&self) -> &T {
41        &self.0
42    }
43}
44
45impl<T> AsMut<T> for DontDrop<T> {
46    fn as_mut(&mut self) -> &mut T {
47        &mut self.0
48    }
49}
50
51impl<T> Deref for DontDrop<T> {
52    type Target = T;
53
54    fn deref(&self) -> &Self::Target {
55        self.as_ref()
56    }
57}
58
59impl<T> DerefMut for DontDrop<T> {
60    fn deref_mut(&mut self) -> &mut Self::Target {
61        self.as_mut()
62    }
63}