]> git.proxmox.com Git - proxmox-backup.git/blob - src/tools/systemd/tm_editor.rs
tools/systemd/tm_editor: move conversion of the year into getter and setter
[proxmox-backup.git] / src / tools / systemd / tm_editor.rs
1 use anyhow::Error;
2
3 use proxmox::tools::time::*;
4
5 pub struct TmEditor {
6 utc: bool,
7 t: libc::tm,
8 }
9
10 impl TmEditor {
11
12 pub fn new(epoch: i64, utc: bool) -> Result<Self, Error> {
13 let t = if utc { gmtime(epoch)? } else { localtime(epoch)? };
14 Ok(Self { utc, t })
15 }
16
17 pub fn into_epoch(mut self) -> Result<i64, Error> {
18 let epoch = if self.utc { timegm(&mut self.t)? } else { timelocal(&mut self.t)? };
19 Ok(epoch)
20 }
21
22 /// increases the day by 'days' and resets all smaller fields to their minimum
23 pub fn add_days(&mut self, days: libc::c_int) -> Result<(), Error> {
24 if days == 0 { return Ok(()); }
25 self.t.tm_hour = 0;
26 self.t.tm_min = 0;
27 self.t.tm_sec = 0;
28 self.t.tm_mday += days;
29 self.normalize_time()
30 }
31
32 pub fn year(&self) -> libc::c_int { self.t.tm_year + 1900 } // see man mktime
33 pub fn hour(&self) -> libc::c_int { self.t.tm_hour }
34 pub fn min(&self) -> libc::c_int { self.t.tm_min }
35 pub fn sec(&self) -> libc::c_int { self.t.tm_sec }
36
37 // Note: tm_wday (0-6, Sunday = 0) => convert to Sunday = 6
38 pub fn day_num(&self) -> libc::c_int {
39 (self.t.tm_wday + 6) % 7
40 }
41
42 pub fn set_time(&mut self, hour: libc::c_int, min: libc::c_int, sec: libc::c_int) -> Result<(), Error> {
43 self.t.tm_hour = hour;
44 self.t.tm_min = min;
45 self.t.tm_sec = sec;
46 self.normalize_time()
47 }
48
49 pub fn set_min_sec(&mut self, min: libc::c_int, sec: libc::c_int) -> Result<(), Error> {
50 self.t.tm_min = min;
51 self.t.tm_sec = sec;
52 self.normalize_time()
53 }
54
55 fn normalize_time(&mut self) -> Result<(), Error> {
56 // libc normalizes it for us
57 if self.utc {
58 timegm(&mut self.t)?;
59 } else {
60 timelocal(&mut self.t)?;
61 }
62 Ok(())
63 }
64
65 pub fn set_sec(&mut self, v: libc::c_int) -> Result<(), Error> {
66 self.t.tm_sec = v;
67 self.normalize_time()
68 }
69
70 pub fn set_min(&mut self, v: libc::c_int) -> Result<(), Error> {
71 self.t.tm_min = v;
72 self.normalize_time()
73 }
74
75 pub fn set_hour(&mut self, v: libc::c_int) -> Result<(), Error> {
76 self.t.tm_hour = v;
77 self.normalize_time()
78 }
79
80 pub fn set_mday(&mut self, v: libc::c_int) -> Result<(), Error> {
81 self.t.tm_mday = v;
82 self.normalize_time()
83 }
84
85 pub fn set_mon(&mut self, v: libc::c_int) -> Result<(), Error> {
86 self.t.tm_mon = v;
87 self.normalize_time()
88 }
89
90 pub fn set_year(&mut self, v: libc::c_int) -> Result<(), Error> {
91 self.t.tm_year = v - 1900;
92 self.normalize_time()
93 }
94 }