1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use std::any::Any;
use GenericEvent;
use AfterRenderArgs;
use AFTER_RENDER;
pub trait AfterRenderEvent {
fn from_after_render_args(args: &AfterRenderArgs, old_event: &Self) -> Option<Self>;
fn after_render<U, F>(&self, f: F) -> Option<U>
where F: FnMut(&AfterRenderArgs) -> U;
fn after_render_args(&self) -> Option<AfterRenderArgs> {
self.after_render(|args| args.clone())
}
}
impl<T: GenericEvent> AfterRenderEvent for T {
fn from_after_render_args(args: &AfterRenderArgs, old_event: &T) -> Option<Self> {
GenericEvent::from_args(AFTER_RENDER, args as &Any, old_event)
}
fn after_render<U, F>(&self, mut f: F) -> Option<U>
where F: FnMut(&AfterRenderArgs) -> U
{
if self.event_id() != AFTER_RENDER {
return None;
}
self.with_args(|any| {
if let Some(args) = any.downcast_ref::<AfterRenderArgs>() {
Some(f(args))
} else {
panic!("Expected AfterRenderArgs")
}
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use test::Bencher;
#[test]
fn test_event_after_render() {
use Event;
use AfterRenderArgs;
let e = Event::AfterRender(AfterRenderArgs);
let x: Option<Event> = AfterRenderEvent::from_after_render_args(
&AfterRenderArgs, &e);
let y: Option<Event> = x.clone().unwrap().after_render(|args|
AfterRenderEvent::from_after_render_args(args, x.as_ref().unwrap())).unwrap();
assert_eq!(x, y);
}
#[bench]
fn bench_event_after_render(bencher: &mut Bencher) {
use Event;
use AfterRenderArgs;
let e = Event::AfterRender(AfterRenderArgs);
let args = AfterRenderArgs;
bencher.iter(|| {
let _: Option<Event> = AfterRenderEvent::from_after_render_args(&args, &e);
});
}
}