application: Introduce data model struct and view structs.
[gps-watch.git] / src / application / model.rs
1 /*
2  * Copyright (c) 2020 Tilman Sauerbeck (tilman at code-monkey de)
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining
5  * a copy of this software and associated documentation files (the
6  * "Software"), to deal in the Software without restriction, including
7  * without limitation the rights to use, copy, modify, merge, publish,
8  * distribute, sublicense, and/or sell copies of the Software, and to
9  * permit persons to whom the Software is furnished to do so, subject to
10  * the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be
13  * included in all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22  */
23
24 pub enum Field {
25     UnixTime(u32),
26     Distance(u32),
27 }
28
29 pub struct Model {
30     pub unix_time: u32,
31     pub distance_cm: u32,
32
33     is_dirty: u32,
34 }
35
36 impl Model {
37     pub fn new() -> Model {
38         Model {
39             unix_time: 0,
40             distance_cm: 0,
41             is_dirty: 0,
42         }
43     }
44
45     pub fn reset(&mut self) {
46         if self.distance_cm != 0 {
47             self.distance_cm = 0;
48             self.is_dirty |= Model::dirty_mask(Field::Distance(0));
49         }
50     }
51
52     pub fn update(&mut self, data: Field) {
53         match data {
54             Field::UnixTime(unix_time) => {
55                 if self.unix_time != unix_time {
56                     self.unix_time = unix_time;
57                     self.is_dirty |= Model::dirty_mask(data);
58                 }
59             },
60             Field::Distance(distance_cm) => {
61                 if self.distance_cm != distance_cm {
62                     self.distance_cm = distance_cm;
63                     self.is_dirty |= Model::dirty_mask(data);
64                 }
65             },
66         }
67     }
68
69     pub fn check_and_reset_is_dirty(&mut self, data: Field) -> bool {
70         let mask = Model::dirty_mask(data);
71
72         if (self.is_dirty & mask) == 0 {
73             false
74         } else {
75             self.is_dirty &= !mask;
76
77             true
78         }
79     }
80
81     fn dirty_mask(data: Field) -> u32 {
82         match data {
83             Field::UnixTime(_) => 1,
84             Field::Distance(_) => 2,
85         }
86     }
87 }