input/
update.rs

1use crate::{Event, Loop};
2
3/// Update arguments, such as delta time in seconds.
4#[derive(Copy, Clone, PartialEq, PartialOrd, Debug, Deserialize, Serialize)]
5pub struct UpdateArgs {
6    /// Delta time in seconds.
7    pub dt: f64,
8}
9
10/// When the application state should be updated.
11pub trait UpdateEvent: Sized {
12    /// Creates an update event.
13    fn from_update_args(args: &UpdateArgs, old_event: &Self) -> Option<Self>;
14    /// Creates an update event with delta time.
15    fn from_dt(dt: f64, old_event: &Self) -> Option<Self> {
16        UpdateEvent::from_update_args(&UpdateArgs { dt }, old_event)
17    }
18    /// Calls closure if this is an update event.
19    fn update<U, F>(&self, f: F) -> Option<U>
20    where
21        F: FnMut(&UpdateArgs) -> U;
22    /// Returns update arguments.
23    fn update_args(&self) -> Option<UpdateArgs> {
24        self.update(|args| *args)
25    }
26}
27
28impl UpdateEvent for Event {
29    fn from_update_args(args: &UpdateArgs, _old_event: &Self) -> Option<Self> {
30        Some(Event::Loop(Loop::Update(*args)))
31    }
32
33    fn update<U, F>(&self, mut f: F) -> Option<U>
34    where
35        F: FnMut(&UpdateArgs) -> U,
36    {
37        match *self {
38            Event::Loop(Loop::Update(ref args)) => Some(f(args)),
39            _ => None,
40        }
41    }
42}
43
44#[cfg(test)]
45mod tests {
46    use super::*;
47
48    #[test]
49    fn test_input_update() {
50        use Event;
51        use UpdateArgs;
52
53        let e: Event = UpdateArgs { dt: 0.0 }.into();
54        let x: Option<Event> = UpdateEvent::from_update_args(&UpdateArgs { dt: 1.0 }, &e);
55        let y: Option<Event> = x
56            .clone()
57            .unwrap()
58            .update(|args| UpdateEvent::from_update_args(args, x.as_ref().unwrap()))
59            .unwrap();
60        assert_eq!(x, y);
61    }
62}