clock_cli/
utils.rs

1// Copyright (C) 2020 Tianyi Shi
2//
3// This file is part of clock-cli-rs.
4//
5// clock-cli-rs is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// clock-cli-rs is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with clock-cli-rs.  If not, see <http://www.gnu.org/licenses/>.
17
18use chrono::Duration;
19
20pub type BoxedError = Box<dyn std::error::Error>;
21
22pub trait PrettyDuration {
23    fn pretty(&self) -> String;
24    fn pretty_s(&self) -> String;
25}
26impl PrettyDuration for Duration {
27    /// Pretty-prints a chrono::Duration in the form `HH:MM:SS.xxx`
28    fn pretty(&self) -> String {
29        let s = self.num_seconds();
30        let ms = self.num_milliseconds() - 1000 * s;
31        let (h, s) = (s / 3600, s % 3600);
32        let (m, s) = (s / 60, s % 60);
33        format!("{:02}:{:02}:{:02}.{:03}", h, m, s, ms)
34    }
35
36    /// Pretty-prints a chrono::Duration in the form `HH:MM:SS.xxx`
37    fn pretty_s(&self) -> String {
38        let mut s = self.num_seconds();
39        let ms = self.num_milliseconds() - 1000 * s;
40        if ms > 500 {
41            s += 1;
42        }
43        let (h, s) = (s / 3600, s % 3600);
44        let (m, s) = (s / 60, s % 60);
45        format!("{:02}:{:02}:{:02}", h, m, s)
46    }
47}