add a safe Option-based version

This commit is contained in:
numzero 2026-05-07 20:11:33 +03:00
parent 07ed195069
commit 535bed743d
2 changed files with 47 additions and 0 deletions

View File

@ -1,3 +1,4 @@
pub mod opt;
pub mod ptr; pub mod ptr;
pub use ptr::OwnRef; pub use ptr::OwnRef;

46
src/opt.rs Normal file
View File

@ -0,0 +1,46 @@
#![forbid(unsafe_code)]
use std::ops::{Deref, DerefMut};
pub struct OwnRef<'a, T>(Option<&'a mut Option<T>>);
impl<T> Drop for OwnRef<'_, T> {
fn drop(&mut self) {
let _: T = self.0.take().unwrap().take().unwrap();
}
}
impl<T> Deref for OwnRef<'_, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.0.as_ref().unwrap().as_ref().unwrap()
}
}
impl<T> DerefMut for OwnRef<'_, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.0.as_mut().unwrap().as_mut().unwrap()
}
}
impl<'a, T> OwnRef<'a, T> {
pub fn from_option(p: &'a mut Option<T>) -> Self {
assert!(p.is_some());
Self(Some(p))
}
pub fn into_option(mut self) -> &'a mut Option<T> {
self.0.take().unwrap()
}
}
impl<T> OwnRef<'_, T> {
pub fn take(mut self) -> T {
self.0.take().unwrap().take().unwrap()
}
}
#[cfg(test)]
mod tests {
use super::*;
}