Skip to main content

nu_protocol/value/
duration.rs

1use chrono::Duration;
2use std::{
3    borrow::Cow,
4    fmt::{Display, Formatter},
5};
6
7use crate::DurationMaxUnit;
8
9#[derive(Clone, Copy)]
10pub enum TimePeriod {
11    Nanos(i64),
12    Micros(i64),
13    Millis(i64),
14    Seconds(i64),
15    Minutes(i64),
16    Hours(i64),
17    Days(i64),
18    Weeks(i64),
19    Months(i64),
20    Years(i64),
21}
22
23impl TimePeriod {
24    pub fn to_text(self) -> Cow<'static, str> {
25        match self {
26            Self::Nanos(n) => format!("{n} ns").into(),
27            Self::Micros(n) => format!("{n} µs").into(),
28            Self::Millis(n) => format!("{n} ms").into(),
29            Self::Seconds(n) => format!("{n} sec").into(),
30            Self::Minutes(n) => format!("{n} min").into(),
31            Self::Hours(n) => format!("{n} hr").into(),
32            Self::Days(n) => format!("{n} day").into(),
33            Self::Weeks(n) => format!("{n} wk").into(),
34            Self::Months(n) => format!("{n} month").into(),
35            Self::Years(n) => format!("{n} yr").into(),
36        }
37    }
38}
39
40impl Display for TimePeriod {
41    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
42        write!(f, "{}", self.to_text())
43    }
44}
45
46pub fn format_duration(duration: i64, max_unit: DurationMaxUnit) -> String {
47    let (sign, periods) = format_duration_as_timeperiod(duration, max_unit);
48
49    let text = periods
50        .into_iter()
51        .map(|p| p.to_text().to_string().replace(' ', ""))
52        .collect::<Vec<String>>();
53
54    format!(
55        "{}{}",
56        if sign == -1 { "-" } else { "" },
57        text.join(" ").trim()
58    )
59}
60
61pub fn format_duration_as_timeperiod(
62    duration: i64,
63    max_unit: DurationMaxUnit,
64) -> (i32, Vec<TimePeriod>) {
65    // Attribution: most of this is taken from chrono-humanize-rs. Thanks!
66    // https://gitlab.com/imp/chrono-humanize-rs/-/blob/master/src/humantime.rs
67    // Current duration doesn't know a date it's based on, weeks is the max time unit it can normalize into.
68    // Don't guess or estimate how many years or months it might contain.
69
70    let sign = if duration >= 0 { 1 } else { -1 };
71    let duration = duration.max(-i64::MAX).abs();
72
73    let dur = Duration::nanoseconds(duration);
74
75    /// Split this a duration into number of whole weeks and the remainder
76    fn split_weeks(duration: Duration) -> (Option<i64>, Duration) {
77        let weeks = duration.num_weeks();
78        normalize_split(weeks, Duration::try_weeks(weeks), duration)
79    }
80
81    /// Split this a duration into number of whole days and the remainder
82    fn split_days(duration: Duration) -> (Option<i64>, Duration) {
83        let days = duration.num_days();
84        normalize_split(days, Duration::try_days(days), duration)
85    }
86
87    /// Split this a duration into number of whole hours and the remainder
88    fn split_hours(duration: Duration) -> (Option<i64>, Duration) {
89        let hours = duration.num_hours();
90        normalize_split(hours, Duration::try_hours(hours), duration)
91    }
92
93    /// Split this a duration into number of whole minutes and the remainder
94    fn split_minutes(duration: Duration) -> (Option<i64>, Duration) {
95        let minutes = duration.num_minutes();
96        normalize_split(minutes, Duration::try_minutes(minutes), duration)
97    }
98
99    /// Split this a duration into number of whole seconds and the remainder
100    fn split_seconds(duration: Duration) -> (Option<i64>, Duration) {
101        let seconds = duration.num_seconds();
102        normalize_split(seconds, Duration::try_seconds(seconds), duration)
103    }
104
105    /// Split this a duration into number of whole milliseconds and the remainder
106    fn split_milliseconds(duration: Duration) -> (Option<i64>, Duration) {
107        let millis = duration.num_milliseconds();
108        normalize_split(millis, Duration::try_milliseconds(millis), duration)
109    }
110
111    /// Split this a duration into number of whole microseconds and the remainder
112    fn split_microseconds(duration: Duration) -> (Option<i64>, Duration) {
113        let micros = duration.num_microseconds().unwrap_or_default();
114        normalize_split(micros, Duration::microseconds(micros), duration)
115    }
116
117    /// Split this a duration into number of whole nanoseconds and the remainder
118    fn split_nanoseconds(duration: Duration) -> (Option<i64>, Duration) {
119        let nanos = duration.num_nanoseconds().unwrap_or_default();
120        normalize_split(nanos, Duration::nanoseconds(nanos), duration)
121    }
122
123    fn normalize_split(
124        wholes: i64,
125        wholes_duration: impl Into<Option<Duration>>,
126        total_duration: Duration,
127    ) -> (Option<i64>, Duration) {
128        match wholes_duration.into() {
129            Some(wholes_duration) if wholes != 0 => {
130                (Some(wholes), total_duration - wholes_duration)
131            }
132            _ => (None, total_duration),
133        }
134    }
135
136    let mut periods = vec![];
137    let mut remainder = dur;
138
139    if max_unit <= DurationMaxUnit::Week {
140        let (weeks, rem) = split_weeks(remainder);
141        remainder = rem;
142        if let Some(weeks) = weeks {
143            periods.push(TimePeriod::Weeks(weeks));
144        }
145    }
146
147    if max_unit <= DurationMaxUnit::Day {
148        let (days, rem) = split_days(remainder);
149        remainder = rem;
150        if let Some(days) = days {
151            periods.push(TimePeriod::Days(days));
152        }
153    }
154
155    if max_unit <= DurationMaxUnit::Hour {
156        let (hours, rem) = split_hours(remainder);
157        remainder = rem;
158        if let Some(hours) = hours {
159            periods.push(TimePeriod::Hours(hours));
160        }
161    }
162
163    if max_unit <= DurationMaxUnit::Minute {
164        let (minutes, rem) = split_minutes(remainder);
165        remainder = rem;
166        if let Some(minutes) = minutes {
167            periods.push(TimePeriod::Minutes(minutes));
168        }
169    }
170
171    if max_unit <= DurationMaxUnit::Second {
172        let (seconds, rem) = split_seconds(remainder);
173        remainder = rem;
174        if let Some(seconds) = seconds {
175            periods.push(TimePeriod::Seconds(seconds));
176        }
177    }
178
179    if max_unit <= DurationMaxUnit::Millisecond {
180        let (millis, rem) = split_milliseconds(remainder);
181        remainder = rem;
182        if let Some(millis) = millis {
183            periods.push(TimePeriod::Millis(millis));
184        }
185    }
186
187    if max_unit <= DurationMaxUnit::Microsecond {
188        let (micros, rem) = split_microseconds(remainder);
189        remainder = rem;
190        if let Some(micros) = micros {
191            periods.push(TimePeriod::Micros(micros));
192        }
193    }
194
195    if max_unit <= DurationMaxUnit::Nanosecond {
196        let (nanos, _rem) = split_nanoseconds(remainder);
197        if let Some(nanos) = nanos {
198            periods.push(TimePeriod::Nanos(nanos));
199        }
200    }
201
202    if periods.is_empty() {
203        periods.push(TimePeriod::Seconds(0));
204    }
205
206    (sign, periods)
207}