1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
use crate::types::DurationParts;

mod impls;
mod r#macro;
mod prelude;
mod types;

#[derive(Copy, Clone)]
pub(crate) struct Duration {
	secs: i64,
	nanos: i32,
}

pub struct FormattedDuration {
	duration: Duration,
	truncate_option: Truncate,
	formatter: Box<dyn Formatter>,
}

pub trait Formatter {
	fn get(&self, truncate: Truncate) -> Box<dyn Unit>;
	fn format(&self, f: &mut std::fmt::Formatter<'_>, parts: DurationParts, truncate: Truncate) -> core::fmt::Result;

	fn format_default(&self, f: &mut std::fmt::Formatter<'_>, parts: DurationParts, truncate: Truncate) -> core::fmt::Result {
		let ref mut started = false;

		if parts.is_empty() {
			self.get(Truncate::Second)
				.format(f, 0, truncate == Truncate::Second, started)?;
			return Ok(());
		}

		if parts.seconds < 0 {
			f.write_str("-")?;
		}

		self.get(Truncate::Year)
			.format(f, parts.years.abs() as u64, truncate == Truncate::Year, started)?;
		if truncate == Truncate::Year {
			return Ok(());
		}

		self.get(Truncate::Month)
			.format(f, parts.months.abs() as u64, truncate == Truncate::Month, started)?;
		if truncate == Truncate::Month {
			return Ok(());
		}

		self.get(Truncate::Day)
			.format(f, parts.days.abs() as u64, truncate == Truncate::Day, started)?;
		if truncate == Truncate::Day {
			return Ok(());
		}

		self.get(Truncate::Hour)
			.format(f, parts.hours.abs() as u64, truncate == Truncate::Hour, started)?;
		if truncate == Truncate::Hour {
			return Ok(());
		}

		self.get(Truncate::Minute)
			.format(f, parts.minutes.abs() as u64, truncate == Truncate::Minute, started)?;
		if truncate == Truncate::Minute {
			return Ok(());
		}

		self.get(Truncate::Second)
			.format(f, parts.seconds.abs() as u64, truncate == Truncate::Second, started)?;
		if truncate == Truncate::Second {
			return Ok(());
		}

		self.get(Truncate::Millis)
			.format(f, parts.millis.abs() as u64, truncate == Truncate::Millis, started)?;
		if truncate == Truncate::Millis {
			return Ok(());
		}

		self.get(Truncate::Micro)
			.format(f, parts.micros.abs() as u64, truncate == Truncate::Micro, started)?;
		if truncate == Truncate::Micro {
			return Ok(());
		}

		self.get(Truncate::Nano)
			.format(f, parts.nanos.abs() as u64, truncate == Truncate::Nano, started)?;

		Ok(())
	}
}

pub trait Unit {
	fn one(&self) -> &'static str;
	fn many(&self) -> &'static str;
	fn format(&self, f: &mut std::fmt::Formatter<'_>, value: u64, allow_zero: bool, started: &mut bool) -> std::fmt::Result;
}

unit!(Year, "year", "years");
unit!(Month, "month", "months");
unit!(Day, "day", "days");
unit!(Hour, "h");
unit!(Minute, "m");
unit!(Second, "s");
unit!(Millis, "ms");
unit!(Micro, "µs");
unit!(Nano, "ns");

#[derive(Debug, Clone, Copy, PartialOrd, PartialEq)]
pub enum Truncate {
	Nano,
	Micro,
	Millis,
	Second,
	Minute,
	Hour,
	Day,
	Month,
	Year,
}

#[cfg(test)]
mod tests {
	use core::time::Duration as StdDuration;

	#[cfg(feature = "chrono")]
	use chrono::Duration as ChronoDuration;
	use time::Duration as TimeDuration;

	use crate::prelude::DurationExt;
	use crate::types::{DefaultFormatter, DurationParts};
	use crate::{unit, Duration, Formatter, Truncate, Unit};

	#[test]
	fn test_nano() {
		let duration = time::Duration::nanoseconds(131_200_001_301_021_123);
		println!("duration: {}", duration);

		let human = duration.human(Truncate::Nano);
		println!("duration: {human}");
		assert_eq!("4years 1month 27days 2h 36m 17s 301ms 21µs 123ns", human.to_string());

		let human2 = duration.human(Truncate::Day);
		println!("duration with days: {human2}");
		assert_eq!("4years 1month 27days", human2.to_string());
	}

	#[test]
	fn test_micro() {
		let duration = time::Duration::microseconds(123);
		println!("duration: {}", duration);

		let human = duration.human(Truncate::Micro);
		println!("duration: {:}", human);

		assert_eq!("123µs", duration.to_string());
		assert_eq!("123µs", human.to_string());
	}

	#[test]
	fn test_millis() {
		let duration = time::Duration::milliseconds(200_200_111);
		println!("duration: {}", duration);

		let human = duration.human_with_format(Truncate::Millis, DefaultFormatter);
		println!("human: {}", human);

		assert_eq!("2d7h36m40s111ms", duration.to_string());
		assert_eq!("2days 7h 36m 40s 111ms", human.to_string());
	}

	#[test]
	fn test_seconds() {
		let duration = time::Duration::seconds(31_556_952);
		let human = duration.human_with_format(Truncate::Second, DefaultFormatter);
		println!("human: {}", human);
		assert_eq!("1year", human.to_string());
	}

	#[test]
	fn test_minutes() {
		let duration = time::Duration::seconds(556_952);
		let human = duration.human_with_format(Truncate::Minute, DefaultFormatter);
		println!("human: {}", human);
		assert_eq!("6days 10h 42m", human.to_string());
	}

	#[test]
	fn test_hours() {
		let duration = time::Duration::seconds(556_952);
		let human = duration.human_with_format(Truncate::Hour, DefaultFormatter);
		println!("human: {}", human);
		assert_eq!("6days 10h", human.to_string());
	}

	#[test]
	fn test_days() {
		let duration = time::Duration::seconds(556_952);
		let human = duration.human_with_format(Truncate::Day, DefaultFormatter);
		println!("human: {}", human);
		assert_eq!("6days", human.to_string());
	}

	#[test]
	fn test_months() {
		let duration = time::Duration::seconds(556_952);
		let human = duration.human_with_format(Truncate::Month, DefaultFormatter);
		println!("human: {}", human);
		assert_eq!("0months", human.to_string());
	}

	#[test]
	fn test_years() {
		let duration = time::Duration::seconds(456_999_556_952);
		println!("{duration}");

		let human = duration.human_with_format(Truncate::Year, DefaultFormatter);
		println!("human: {human}");
		assert_eq!("14481years", human.to_string());
	}

	#[cfg(feature = "chrono")]
	#[test]
	fn test_chrono_duration() {
		let duration = chrono::Duration::nanoseconds(9223372036854775807);
		let std_duration: StdDuration = duration.to_std().unwrap();
		let time_duration: TimeDuration = time::Duration::try_from(std_duration).unwrap();
		println!("duration: {duration}");
		println!("std duration: {time_duration}");

		let human = duration.human(Truncate::Nano);
		println!("human: {human}");

		assert_eq!("292years 3months 9days 20h 40m 4s 854ms 775µs 807ns", human.to_string());
	}

	#[cfg(feature = "chrono")]
	#[test]
	fn test_convert_chrono_duration() {
		let duration: ChronoDuration = chrono::Duration::nanoseconds(9223372036854775807);
		let converted: Duration = duration.into();
		let duration2: ChronoDuration = converted.into();
		assert_eq!(duration, duration2);
	}

	#[test]
	fn test_convert_time_duration() {
		let duration: TimeDuration = time::Duration::nanoseconds(123_456_789);
		let converted: Duration = duration.into();
		let duration2: TimeDuration = converted.into();
		assert_eq!(duration, duration2);
	}

	#[test]
	fn test_convert_std_time_duration() {
		let duration: StdDuration = StdDuration::new(123_456_789, 999);
		let converted: Duration = duration.into();
		let duration2: StdDuration = converted.into();
		assert_eq!(duration, duration2);
	}

	#[test]
	fn test_custom_formatter() {
		struct MyFormatter;

		unit!(MyYear, " anno", " anni");
		unit!(MyMonth, " mese", " mesi");
		unit!(MyDay, " giorno", " giorni");
		unit!(MyHour, " ora", " ore");
		unit!(MyMinute, " minuto", " minuti");
		unit!(MySecond, " secondo", " secondi");
		unit!(MyMillis, " millisecondo", " millisecondi");
		unit!(MyMicro, " microsecondo", " microsecondi");
		unit!(MyNano, " nanosecondo", " nanosecondi");

		impl Formatter for MyFormatter {
			fn get(&self, truncate: Truncate) -> Box<dyn Unit> {
				match truncate {
					Truncate::Nano => Box::new(MyNano),
					Truncate::Micro => Box::new(MyMicro),
					Truncate::Millis => Box::new(MyMillis),
					Truncate::Second => Box::new(MySecond),
					Truncate::Minute => Box::new(MyMinute),
					Truncate::Hour => Box::new(MyHour),
					Truncate::Day => Box::new(MyDay),
					Truncate::Month => Box::new(MyMonth),
					Truncate::Year => Box::new(MyYear),
				}
			}

			fn format(&self, f: &mut std::fmt::Formatter<'_>, parts: DurationParts, truncate: Truncate) -> std::fmt::Result {
				self.format_default(f, parts, truncate)
			}
		}

		let duration = TimeDuration::nanoseconds(150_345_202_557_001);
		let human_default = duration.human(Truncate::Nano);
		let human = duration.human_with_format(Truncate::Nano, MyFormatter);

		println!("human default: {human_default}");
		println!("human: {human}");

		assert_eq!("1day 17h 45m 45s 202ms 557µs 1ns", human_default.to_string());
		assert_eq!(
			"1 giorno 17 ore 45 minuti 45 secondi 202 millisecondi 557 microsecondi 1 nanosecondo",
			human.to_string()
		);
	}
}