aboutsummaryrefslogtreecommitdiff
path: root/src/habit.rs
diff options
context:
space:
mode:
authorAkshay <[email protected]>2020-02-10 15:26:22 +0000
committerAkshay <[email protected]>2020-02-10 15:26:22 +0000
commitd33e960c57fda3fa1c916ad765e32a673524d55e (patch)
treebe1309658c397a61c4c582ca54d7d4e54bad64c3 /src/habit.rs
parent1b4fb7eb887b2fd581db6a6a961a246f01f49e07 (diff)
move structs out
Diffstat (limited to 'src/habit.rs')
-rw-r--r--src/habit.rs63
1 files changed, 63 insertions, 0 deletions
diff --git a/src/habit.rs b/src/habit.rs
new file mode 100644
index 0000000..4f05217
--- /dev/null
+++ b/src/habit.rs
@@ -0,0 +1,63 @@
1use std::collections::HashMap;
2
3use chrono::NaiveDate;
4
5#[derive(Debug)]
6pub struct Habit<T> {
7 name: String,
8 stats: HashMap<NaiveDate, T>,
9}
10
11impl<T> Habit<T>
12where
13 T: Copy,
14{
15 pub fn new(name: &str) -> Habit<T> {
16 return Habit {
17 name: name.to_owned(),
18 stats: HashMap::new(),
19 };
20 }
21
22 pub fn get_name(&self) -> String {
23 return self.name.to_owned();
24 }
25
26 pub fn get_by_date(&self, date: NaiveDate) -> Option<&T> {
27 self.stats.get(&date)
28 }
29
30 pub fn insert_entry(&mut self, date: NaiveDate, val: T) {
31 *self.stats.entry(date).or_insert(val) = val;
32 }
33}
34
35impl Habit<bool> {
36 pub fn toggle(&mut self, date: NaiveDate) {
37 if let Some(v) = self.stats.get_mut(&date) {
38 *v ^= true
39 } else {
40 self.insert_entry(date, true);
41 }
42 }
43}
44
45impl Habit<u32> {
46 pub fn increment(&mut self, date: NaiveDate) {
47 if let Some(v) = self.stats.get_mut(&date) {
48 *v += 1
49 }
50 }
51 pub fn decrement(&mut self, date: NaiveDate) {
52 if let Some(v) = self.stats.get_mut(&date) {
53 if *v >= 1 {
54 *v -= 1;
55 } else {
56 *v = 0;
57 };
58 }
59 }
60 pub fn set(&mut self, date: NaiveDate, val: u32) {
61 *self.stats.entry(date).or_insert(val) = val;
62 }
63}