add a safe Option-based version
This commit is contained in:
parent
07ed195069
commit
535bed743d
|
|
@ -1,3 +1,4 @@
|
|||
pub mod opt;
|
||||
pub mod ptr;
|
||||
|
||||
pub use ptr::OwnRef;
|
||||
|
|
|
|||
46
src/opt.rs
Normal file
46
src/opt.rs
Normal 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::*;
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user