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
71
72
73
74
75
76
77
78
79
80
81
82
83
use std::any::Any;
use { GenericEvent, RenderArgs, RENDER };
pub trait RenderEvent {
fn from_render_args(args: &RenderArgs, old_event: &Self) -> Option<Self>;
fn render<U, F>(&self, f: F) -> Option<U>
where F: FnMut(&RenderArgs) -> U;
fn render_args(&self) -> Option<RenderArgs> {
self.render(|args| args.clone())
}
}
impl<T: GenericEvent> RenderEvent for T {
fn from_render_args(args: &RenderArgs, old_event: &Self) -> Option<Self> {
GenericEvent::from_args(RENDER, args as &Any, old_event)
}
fn render<U, F>(&self, mut f: F) -> Option<U>
where F: FnMut(&RenderArgs) -> U
{
if self.event_id() != RENDER {
return None;
}
self.with_args(|any| {
if let Some(args) = any.downcast_ref::<RenderArgs>() {
Some(f(args))
} else {
panic!("Expected RenderArgs")
}
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use test::Bencher;
#[test]
fn test_event_render() {
use Event;
use RenderArgs;
let e = Event::Render(RenderArgs { ext_dt: 0.0, width: 0, height: 0,
draw_width: 0, draw_height: 0 });
let x: Option<Event> = RenderEvent::from_render_args(
&RenderArgs {
ext_dt: 1.0,
width: 10,
height: 10,
draw_width: 10,
draw_height: 10,
}, &e
);
let y: Option<Event> = x.clone().unwrap().render(|args|
RenderEvent::from_render_args(args, x.as_ref().unwrap())).unwrap();
assert_eq!(x, y);
}
#[bench]
fn bench_event_render(bencher: &mut Bencher) {
use Event;
use RenderArgs;
let e = Event::Render(RenderArgs { ext_dt: 0.0, width: 0, height: 0,
draw_width: 0, draw_height: 0 });
let args = RenderArgs {
ext_dt: 1.0,
width: 10,
height: 10,
draw_width: 10,
draw_height: 10,
};
bencher.iter(|| {
let _: Option<Event> = RenderEvent::from_render_args(&args, &e);
});
}
}