36 lines
749 B
Rust
36 lines
749 B
Rust
use std::ops::{Deref, DerefMut};
|
|
|
|
pub struct DynBorrower<'a, T: ?Sized> {
|
|
data: &'a mut T,
|
|
borrowed: &'a mut bool,
|
|
}
|
|
|
|
impl<'a, T: ?Sized> DynBorrower<'a, T> {
|
|
pub fn new(data: &'a mut T, borrowed: &'a mut bool) -> Self {
|
|
if *borrowed {
|
|
panic!("tried to mutably borrow the same thing twice");
|
|
}
|
|
Self { data, borrowed }
|
|
}
|
|
}
|
|
|
|
impl<T: ?Sized> Drop for DynBorrower<'_, T> {
|
|
fn drop(&mut self) {
|
|
*self.borrowed = false;
|
|
}
|
|
}
|
|
|
|
impl<T: ?Sized> Deref for DynBorrower<'_, T> {
|
|
type Target = T;
|
|
|
|
fn deref(&self) -> &Self::Target {
|
|
self.data
|
|
}
|
|
}
|
|
|
|
impl<T: ?Sized> DerefMut for DynBorrower<'_, T> {
|
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
|
self.data
|
|
}
|
|
}
|