summaryrefslogtreecommitdiffstats
path: root/servo/components/style/rule_tree/unsafe_box.rs
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-19 00:47:55 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-19 00:47:55 +0000
commit26a029d407be480d791972afb5975cf62c9360a6 (patch)
treef435a8308119effd964b339f76abb83a57c29483 /servo/components/style/rule_tree/unsafe_box.rs
parentInitial commit. (diff)
downloadfirefox-upstream/124.0.1.tar.xz
firefox-upstream/124.0.1.zip
Adding upstream version 124.0.1.upstream/124.0.1
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'servo/components/style/rule_tree/unsafe_box.rs')
-rw-r--r--servo/components/style/rule_tree/unsafe_box.rs74
1 files changed, 74 insertions, 0 deletions
diff --git a/servo/components/style/rule_tree/unsafe_box.rs b/servo/components/style/rule_tree/unsafe_box.rs
new file mode 100644
index 0000000000..eaa441d7b2
--- /dev/null
+++ b/servo/components/style/rule_tree/unsafe_box.rs
@@ -0,0 +1,74 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
+
+#![allow(unsafe_code)]
+
+use std::mem::ManuallyDrop;
+use std::ops::Deref;
+use std::ptr;
+
+/// An unsafe box, derefs to `T`.
+pub(super) struct UnsafeBox<T> {
+ inner: ManuallyDrop<Box<T>>,
+}
+
+impl<T> UnsafeBox<T> {
+ /// Creates a new unsafe box.
+ pub(super) fn from_box(value: Box<T>) -> Self {
+ Self {
+ inner: ManuallyDrop::new(value),
+ }
+ }
+
+ /// Creates a new box from a pointer.
+ ///
+ /// # Safety
+ ///
+ /// The input should point to a valid `T`.
+ pub(super) unsafe fn from_raw(ptr: *mut T) -> Self {
+ Self {
+ inner: ManuallyDrop::new(Box::from_raw(ptr)),
+ }
+ }
+
+ /// Creates a new unsafe box from an existing one.
+ ///
+ /// # Safety
+ ///
+ /// There is no refcounting or whatever else in an unsafe box, so this
+ /// operation can lead to double frees.
+ pub(super) unsafe fn clone(this: &Self) -> Self {
+ Self {
+ inner: ptr::read(&this.inner),
+ }
+ }
+
+ /// Returns a mutable reference to the inner value of this unsafe box.
+ ///
+ /// # Safety
+ ///
+ /// Given `Self::clone`, nothing prevents anyone from creating
+ /// multiple mutable references to the inner value, which is completely UB.
+ pub(crate) unsafe fn deref_mut(this: &mut Self) -> &mut T {
+ &mut this.inner
+ }
+
+ /// Drops the inner value of this unsafe box.
+ ///
+ /// # Safety
+ ///
+ /// Given this doesn't consume the unsafe box itself, this has the same
+ /// safety caveats as `ManuallyDrop::drop`.
+ pub(super) unsafe fn drop(this: &mut Self) {
+ ManuallyDrop::drop(&mut this.inner)
+ }
+}
+
+impl<T> Deref for UnsafeBox<T> {
+ type Target = T;
+
+ fn deref(&self) -> &Self::Target {
+ &self.inner
+ }
+}