style/rule_tree/unsafe_box.rs
1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5#![allow(unsafe_code)]
6
7use std::mem::ManuallyDrop;
8use std::ops::Deref;
9use std::ptr;
10
11/// An unsafe box, derefs to `T`.
12pub(super) struct UnsafeBox<T> {
13 inner: ManuallyDrop<Box<T>>,
14}
15
16impl<T> UnsafeBox<T> {
17 /// Creates a new unsafe box.
18 pub(super) fn from_box(value: Box<T>) -> Self {
19 Self {
20 inner: ManuallyDrop::new(value),
21 }
22 }
23
24 /// Creates a new box from a pointer.
25 ///
26 /// # Safety
27 ///
28 /// The input should point to a valid `T`.
29 pub(super) unsafe fn from_raw(ptr: *mut T) -> Self {
30 unsafe {
31 Self {
32 inner: ManuallyDrop::new(Box::from_raw(ptr)),
33 }
34 }
35 }
36
37 /// Creates a new unsafe box from an existing one.
38 ///
39 /// # Safety
40 ///
41 /// There is no refcounting or whatever else in an unsafe box, so this
42 /// operation can lead to double frees.
43 pub(super) unsafe fn clone(this: &Self) -> Self {
44 unsafe {
45 Self {
46 inner: ptr::read(&this.inner),
47 }
48 }
49 }
50
51 /// Returns a mutable reference to the inner value of this unsafe box.
52 ///
53 /// # Safety
54 ///
55 /// Given `Self::clone`, nothing prevents anyone from creating
56 /// multiple mutable references to the inner value, which is completely UB.
57 pub(crate) unsafe fn deref_mut(this: &mut Self) -> &mut T {
58 &mut this.inner
59 }
60
61 /// Drops the inner value of this unsafe box.
62 ///
63 /// # Safety
64 ///
65 /// Given this doesn't consume the unsafe box itself, this has the same
66 /// safety caveats as `ManuallyDrop::drop`.
67 pub(super) unsafe fn drop(this: &mut Self) {
68 unsafe { ManuallyDrop::drop(&mut this.inner) }
69 }
70}
71
72impl<T> Deref for UnsafeBox<T> {
73 type Target = T;
74
75 fn deref(&self) -> &Self::Target {
76 &self.inner
77 }
78}