るいもの戯れ言
#260
2017/01/27 10:47

Rustで、任意の処理をはさみこんで、前後に定型処理を入れるようなことをしたい。例えば処理の時間を測って一定時間を超えていたらタイムアウト処理を呼ぶようなのを考えてみる。


struct Foo {
    i: i32
}

impl Foo {
    fn around_mut<'a, T, F: FnMut(&mut Foo) -> T + 'a>(&mut self, mut f: F) -> T {
        let before = self.get_time();
        let ret = f(self);
        let after = self.get_time();
        if after - before > 1000 {
            self.timeout()
        }
        ret
    }

    fn around<'a, T, F: Fn(&Foo) -> T + 'a>(&self, f: F) ->T {
        let ret = f(self);
        ret
    }

    fn timeout(&self) {
    }

    fn get_time(&self) -> i32 {
        222
    }

    fn inner_mut(&mut self) -> i32 {
        111
    }

    fn outer_mut(&mut self) -> i32 {
        self.around_mut(move |this| {
            this.inner_mut()
        })
    }

    fn inner(&self) -> i32 {
        111
    }

    fn outer(&self) -> i32 {
        self.around(move |this| {
            this.inner()
        })
    }
}

fn main() {
    let mut foo_mut = Foo { i: 123 };
    let ret_mut = foo_mut.outer_mut();
    println!("Ret: {}", ret_mut);

    let foo = Foo { i: 222 };
    let ret = foo.outer();
    println!("Ret: {}", ret);
}

結構難しい... 慣れるものなんだろうか。