Skip to content

Instantly share code, notes, and snippets.

Created June 3, 2016 17:23
Show Gist options
  • Save anonymous/8220ac01829d7e753a37b719563e16cd to your computer and use it in GitHub Desktop.
Save anonymous/8220ac01829d7e753a37b719563e16cd to your computer and use it in GitHub Desktop.
Shared via Rust Playground
macro_rules! defer {
($x:expr) => {
let _x = {
struct Deferred<F: Fn()>(F);
impl<F: Fn()> Drop for Deferred<F> {
fn drop(&mut self) {
self.0();
}
}
Deferred(||$x)
};
}
}
use std::ops::{Deref, DerefMut};
pub struct Guard<T, F> where
F: FnMut(&mut T)
{
__dropfn: F,
__value: T,
}
pub fn guard<T, F>(v: T, dropfn: F) -> Guard<T, F> where
F: FnMut(&mut T)
{
Guard{__value: v, __dropfn: dropfn}
}
impl<T, F> Deref for Guard<T, F> where
F: FnMut(&mut T)
{
type Target = T;
fn deref(&self) -> &T
{
&self.__value
}
}
impl<T, F> DerefMut for Guard<T, F> where
F: FnMut(&mut T)
{
fn deref_mut(&mut self) -> &mut T
{
&mut self.__value
}
}
impl<T, F> Drop for Guard<T, F> where
F: FnMut(&mut T)
{
fn drop(&mut self) {
(self.__dropfn)(&mut self.__value)
}
}
fn incr(i : &mut i32) {*i += 1;}
fn main() {
let x = Box::new(5);
{
defer!(println!("Defer 1: {:?}",x));
//*x += 1;
defer!(println!("Defer 2"));
println!("x: {:?}", x);
}
let mut y = guard(x, |x|println!("y is now: {:?}",x));
**y += 4;
println!("y = {:?}", *y);
incr(&mut y);
let mut z = guard(1, |x|println!("z is now: {:?}",x));
*z += 3;
//let b : Box<str> = box *"x";
//let a : _ = &*box b;
}
/*
let _x = {
#[derive(Debug)]
struct Deferred<F: FnOnce()>(F);
impl<F: FnOnce()> Drop for Deferred<F> {
fn drop(&mut self) {
//println!("Dropping {:?}", $x);
replace(&mut self.0, ||{} as F)();
}
}
Deferred(|| println!("Drop {:?}",x))
};
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment