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
use std::any::Any;
use { GenericEvent, UPDATE };
#[derive(Copy, Clone, PartialEq, Debug)]
pub struct UpdateArgs {
pub dt: f64,
}
pub trait UpdateEvent: Sized {
fn from_update_args(args: &UpdateArgs, old_event: &Self) -> Option<Self>;
fn from_dt(dt: f64, old_event: &Self) -> Option<Self> {
UpdateEvent::from_update_args(&UpdateArgs { dt: dt }, old_event)
}
fn update<U, F>(&self, f: F) -> Option<U>
where F: FnMut(&UpdateArgs) -> U;
fn update_args(&self) -> Option<UpdateArgs> {
self.update(|args| args.clone())
}
}
impl<T> UpdateEvent for T where T: GenericEvent {
fn from_update_args(args: &UpdateArgs, old_event: &Self) -> Option<Self> {
GenericEvent::from_args(UPDATE, args as &Any, old_event)
}
fn update<U, F>(&self, mut f: F) -> Option<U>
where F: FnMut(&UpdateArgs) -> U
{
if self.event_id() != UPDATE {
return None;
}
self.with_args(|any| {
if let Some(args) = any.downcast_ref::<UpdateArgs>() {
Some(f(args))
} else {
panic!("Expected UpdateArgs")
}
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_event_update() {
use Event;
use UpdateArgs;
let e = Event::Update(UpdateArgs { dt: 0.0 });
let x: Option<Event> = UpdateEvent::from_update_args(
&UpdateArgs { dt: 1.0 }, &e);
let y: Option<Event> = x.clone().unwrap().update(|args|
UpdateEvent::from_update_args(args, x.as_ref().unwrap())).unwrap();
assert_eq!(x, y);
}
}