From 087017f9e8ba84d92a76bec17b2376f72c8e3a27 Mon Sep 17 00:00:00 2001 From: numzero Date: Thu, 7 May 2026 18:58:20 +0300 Subject: [PATCH] a basic owning reference implementation --- .gitignore | 1 + Cargo.lock | 7 ++++++ Cargo.toml | 6 +++++ rustfmt.toml | 1 + src/lib.rs | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 78 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 rustfmt.toml create mode 100644 src/lib.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..c16424d --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ownref" +version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..b84c1a2 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "ownref" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..218e203 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1 @@ +hard_tabs = true diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..fff84a5 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,63 @@ +use std::{ + marker::PhantomData, + mem::ManuallyDrop, + ops::{Deref, DerefMut}, + ptr::{self, NonNull}, +}; + +pub struct OwnRef<'a, T: ?Sized>(Option>, PhantomData<&'a mut T>); + +impl Drop for OwnRef<'_, T> { + fn drop(&mut self) { + let Some(p) = self.0 else { return }; + unsafe { ptr::drop_in_place(p.as_ptr()) }; + } +} + +impl Deref for OwnRef<'_, T> { + type Target = T; + fn deref(&self) -> &Self::Target { + unsafe { self.0.unwrap().as_ref() } + } +} + +impl DerefMut for OwnRef<'_, T> { + fn deref_mut(&mut self) -> &mut Self::Target { + unsafe { self.0.unwrap().as_mut() } + } +} + +impl OwnRef<'_, T> { + pub unsafe fn new_unchecked(p: *mut T) -> Self { + Self(Some(NonNull::new(p).unwrap()), PhantomData) + } +} + +impl<'a, T: ?Sized> OwnRef<'a, T> { + pub unsafe fn from_manually_drop(p: &'a mut ManuallyDrop) -> Self { + unsafe { Self::new_unchecked(p.deref_mut() as *mut _) } + } +} + +impl OwnRef<'_, T> { + pub fn take(mut self) -> T { + let p = self.0.take().unwrap(); + unsafe { p.read() } + } +} + +impl OwnRef<'_, dyn std::any::Any> { + pub fn take(mut self) -> Option { + if !self.is::() { + return None; + } + let p = self.0.take().unwrap(); + let p = p.cast::(); + Some(unsafe { p.read() }) + } +} + +#[cfg(test)] +mod tests { + use super::*; +}