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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
use std::fmt;
use std::ops::{
	Add,
	Sub,
	Mul,
	Div,
	Rem
};
use std::str::FromStr;

use super::{
	Scale,
	Span
};

/// Error encountered parsing [`Span`]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParseSpanError {
	/// Resulting number of seconds overflowed [`u64`]
	Overflow,
	/// Empty string is not a valid [`Span`]
	Empty,
	/// Units must be in order, from highest to lowest (skipping is allowed, repeating isn't)
	OutOfOrderUnit,
	/// Units must be one of `y`, `mo`, `w`, `d`, `h`, `m`, `s` (see [`Span`])
	InvalidUnit,
	/// Every unit must be preceded by an integer amount
	MissingAmount,
	/// Every integer must be followed immediately by a unit
	MissingUnit
}

// Constructors
impl Span {
	/// Same as constructing `Span {seconds}` directly
	pub const fn from_seconds(seconds: u64) -> Self {
		Self {seconds}
	}
}

#[allow(missing_docs)]
impl Span {
	pub const SCALES: [(u64, &'static str, Scale); 7] = [
		(31556952, "y",  Scale::Years),
		( 2629746, "mo", Scale::Months),
		(  604800, "w",  Scale::Weeks),
		(   86400, "d",  Scale::Days),
		(    3600, "h",  Scale::Hours),
		(      60, "m",  Scale::Minutes),
		(       1, "s",  Scale::Seconds)
	];
	pub const WEEK:   Self = Self::from_seconds(604800);
	pub const DAY:    Self = Self::from_seconds( 86400);
	pub const HOUR:   Self = Self::from_seconds(  3600);
	pub const MINUTE: Self = Self::from_seconds(    60);
	pub const SECOND: Self = Self::from_seconds(     1);

	pub const ZERO: Self = Self::from_seconds(0);
}

// Math
impl Span {
	/// Checked addition: computes `self + other`, returning `None` if overflow occurred.
	pub const fn checked_add(self, other: Self) -> Option<Self> {
		match self.seconds.checked_add(other.seconds) {
			Some(s) => Some(Self::from_seconds(s)),
			None => None
		}
	}
	/// Checked subtraction: computes `self - other`, returning `None` if overflow occurred.
	pub const fn checked_sub(self, other: Self) -> Option<Self> {
		match self.seconds.checked_sub(other.seconds) {
			Some(s) => Some(Self::from_seconds(s)),
			None => None
		}
	}

	/// Break down into a [`Scale`] and count
	///
	/// Returns the biggest [`Scale`] that divides the [`Span`] without a remainder as well as the result of this division.
	/// One exception is the empty [`Span::ZERO`], because the count is `0` for every [`Scale`].
	/// Instead of returning `(Scale::Years, 0)`, which would be counter-intuitive, the zero-second [`Span`] always returns the more natural `(Scale::Seconds, 0)`.
	///
	/// Remember that [`Scale::Years`] and [`Scale::Months`] are special, because they represent an *average*, they do not cleanly divide into weeks, days or even minutes!
	/// See the [`Scale`] documentation for details.
	/// ```
	/// use greg::{Span, Scale};
	///
	/// assert_eq!(Span::from_seconds(600).scale_div(), (Scale::Minutes, 10));
	/// assert_eq!(Span::ZERO.scale_div(), (Scale::Seconds, 0));
	/// let one_and_a_half: Span = "1h30m".parse().unwrap();
	/// assert_eq!(one_and_a_half.scale_div(), (Scale::Minutes, 90));
	///
	/// ```
	pub fn scale_div(self) -> (Scale, u64) {
		if self == Self::ZERO {return (Scale::Seconds, 0)}
		Self::SCALES.iter()
			.find(|(scale_sec, ..)| self.seconds % scale_sec == 0)
			.map(|&(scale_sec, _, scale)| (scale, self.seconds / scale_sec))
			.unwrap()
	}
}

impl Add<Span> for Span {
	type Output = Self;
	fn add(self, rhs: Span) -> Self::Output {
		let seconds = self.seconds + rhs.seconds;
		Self {seconds}
	}
}

impl Sub<Span> for Span {
	type Output = Self;
	fn sub(self, rhs: Span) -> Self::Output {
		let seconds = self.seconds - rhs.seconds;
		Self {seconds}
	}
}

impl Mul<u64> for Span {
	type Output = Self;
	fn mul(mut self, rhs: u64) -> Self::Output {
		self.seconds *= rhs;
		self
	}
}

impl Div<u64> for Span {
	type Output = u64;
	fn div(self, rhs: u64) -> Self::Output {
		self.seconds / rhs
	}
}

impl Div<Scale> for Span {
	type Output = u64;
	fn div(self, rhs: Scale) -> Self::Output {
		self.seconds / rhs.as_seconds()
	}
}

impl Rem<Scale> for Span {
	type Output = Self;
	fn rem(self, rhs: Scale) -> Self::Output {
		Self {seconds: self.seconds % rhs.as_seconds()}
	}
}

impl From<Scale> for Span {
	fn from(scale: Scale) -> Self {Self::from_seconds(scale.as_seconds())}
}

impl Span {
	/// Try to parse terse duration format and panic if invalid
	///
	///```
	/// use greg::Span;
	/// const CHILIAD: Span = Span::parse("1000y");
	///
	/// assert_eq!(Span::parse("0s"), Span::ZERO);
	/// assert_eq!(Span::parse("10s").seconds, 10);
	/// assert_eq!(Span::parse("1m30s").seconds, 90);
	/// let _ = Span::parse("3mo2h10m30s");
	///```
	///
	/// This is mainly useful in `const` contexts, since the panic gets caught at compile-time.
	///
	///```compile_fail
	/// use greg::Span;
	/// const DECADE: Span = Span::parse("10t"); // typo: "t" instead of "y"
	///```
	#[must_use]
	pub const fn parse(from: &str) -> Self {
		match Self::try_parse(from) {
			Ok(span) => span,
			Err(err) => panic!("{}", err.as_str())
		}
	}
	/// Try to parse terse duration format
	///
	///```
	/// use greg::Span;
	///
	/// assert_eq!(Span::try_parse("0s"), Ok(Span::ZERO));
	/// assert_eq!(Span::try_parse("1w"), Ok(Span::WEEK));
	/// assert_eq!(Span::try_parse("1m30s"), Ok(Span::MINUTE + Span::SECOND * 30));
	/// let _ = Span::try_parse("3mo2h10m30s").unwrap();
	///
	/// assert!(Span::try_parse("10 hours").is_err(), "long-form units don't work");
	///```
	pub const fn try_parse(from: &str) -> Result<Self, ParseSpanError> {
		let mut remaining_units = Self::SCALES.len();
		let mut seconds: u64 = 0;
		let mut bytes = from.as_bytes();
		let mut current: Option<u64> = None;
		if from.is_empty() {
			return Err(ParseSpanError::Empty);
		}
		loop {
			let (unit, rest) = match bytes {
				[n @ b'0'..=b'9', rest @ ..] => {
					let new_digit = (*n - b'0') as u64;
					current = match current {
						Some(n) => match n.checked_mul(10) {
							Some(n) => match n.checked_add(new_digit) {
								Some(n) => Some(n),
								None => return Err(ParseSpanError::Overflow)
							},
							None => return Err(ParseSpanError::Overflow)
						},
						None => Some(new_digit)
					};
					bytes = rest;
					continue;
				},
				[b'y', rest @ ..] => (6, rest),
				[b'm', b'o', rest @ ..] => (5, rest),
				[b'w', rest @ ..] => (4, rest),
				[b'd', rest @ ..] => (3, rest),
				[b'h', rest @ ..] => (2, rest),
				[b'm', rest @ ..] => (1, rest),
				[b's', rest @ ..] => (0, rest),
				[_, ..] => return Err(ParseSpanError::InvalidUnit),
				[] if current.is_none() => break,
				[] => return Err(ParseSpanError::MissingUnit)
			};

			if remaining_units <= unit {
				return Err(ParseSpanError::OutOfOrderUnit);
			}
			let Some(num) = current else {
				return Err(ParseSpanError::MissingAmount);
			};
			let Some(mul) = num.checked_mul(Self::SCALES[6 - unit].0) else {
				return Err(ParseSpanError::Overflow);
			};
			let Some(add) = seconds.checked_add(mul) else {
				return Err(ParseSpanError::Overflow);
			};
			seconds = add;
			remaining_units = unit;
			current = None;
			bytes = rest;

		}
		Ok(Self {seconds})
	}
}

impl FromStr for Span {
	type Err = ParseSpanError;
	/// Parse terse duration format
	///
	/// See [`try_parse`](Self::try_parse) for a `const` method and some more details.
	fn from_str(s: &str) -> Result<Self, Self::Err> {
		Self::try_parse(s)
	}
}

impl fmt::Display for Span {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		if self.seconds == 0 {
			return "0s".fmt(f)
		}
		let mut seconds = self.seconds;
		let mut iter = Self::SCALES
			.iter()
			.filter_map(|(scale_seconds, scale_short, _)| {
				let remainder = seconds % scale_seconds;
				let scale_portion = seconds - remainder;
				seconds = remainder;
				(scale_portion > 0)
					.then_some(scale_portion / scale_seconds)
					.map(|scale_count| (scale_count, scale_short))
			})
			.take(f.precision().unwrap_or(Self::SCALES.len()));

		if f.alternate() {
			iter
				.next()
				.map(|(count, unit)| write!(f, "{count}{unit}"))
				.transpose()?;
			iter
				.map(|(count, unit)| write!(f, " {count}{unit}"))
				.reduce(Result::and)
				.transpose()
				.map(|_| ())
		}
		else {
			iter
				.map(|(count, unit)| write!(f, "{count}{unit}"))
				.reduce(Result::and)
				.transpose()
				.map(|_| ())
		}
	}
}
impl fmt::Debug for Span {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		fmt::Display::fmt(self, f)
	}
}

/*
 *	PARSE SPAN ERROR
 */

impl ParseSpanError {
	const fn as_str(&self) -> &'static str {
		match self {
			Self::Overflow => "duration too large",
			Self::Empty => "invalid empty duration",
			Self::InvalidUnit => "invalid unit",
			Self::OutOfOrderUnit => "invalid unit order",
			Self::MissingAmount => "invalid unit without amount",
			Self::MissingUnit => "invalid amount without unit"
		}
	}
}

impl fmt::Display for ParseSpanError {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.as_str().fmt(f)
	}
}


/*
 *	TESTS
 */

#[test]
fn parse_span() {
	let sec_per_year = Span::from(Scale::Years).seconds;
	let sec_per_month = Span::from(Scale::Months).seconds;

	let valid = [
		("0s", 0),
		("10s", 10),
		("1m30s", 90),
		("100000y", 100_000 * sec_per_year),
		("3mo2h10m30s", (3 * sec_per_month) + (2 * 60 * 60) + (10 * 60) + 30),
		("0y0mo0w0d0h0m0s", 0),
		("18446744073709551615s", 18446744073709551615)
	];

	let invalid = [
		"0",
		"10Y",
		"1y2m3d",
		"10s30h",
		"0y0mo0w0d0h0m0s0ns",
		"3 seconds",
		"3 minutes",
		"10min",
		"1h1d",
		"-30s",
		"abc",
		"",
		"99999999999999y",
		"1m18446744073709551615s",
		"18446744073709551616s",
		"0000000000000000000000000000000000000000000000000000000000000",
		"9999999999999999999999999999999999999999999999999999999999999",
		"\n",
		"🤔",
		"ymowdhms",
		"s0"
	];

	for (to_parse, expected) in valid {
		println!("Parsing '{to_parse}', expecting {expected}");
		assert_eq!(
			to_parse.parse(),
			Ok(Span::from_seconds(expected)),
			"failed to parse {to_parse}"
		);
		assert_eq!(Span::parse(to_parse), Span::from_seconds(expected));
	}

	for to_parse in invalid {
		println!("Parsing '{to_parse}', expecting error");
		let err = to_parse.parse::<Span>().unwrap_err();
		println!("Err: '{err}'!)");
		let err = Span::try_parse(to_parse).unwrap_err();
		println!("Err: '{err}'!)");
	}
}

#[test]
fn math() {
	let span = Span::parse("1w2d3h4m5s");

	assert_eq!(span % Scale::Days, Span::parse("3h4m5s"));
	assert_eq!(span % Scale::Years, span);
	assert_eq!(span % Scale::Seconds, Span::ZERO);

	assert_eq!(span / Scale::Days, 9);
	assert_eq!(span / Scale::Years, 0);
	assert_eq!(span / Scale::Seconds, span.seconds);

	assert_eq!(Span::DAY * 10, Span::parse("10d"));
	assert_eq!(Span::WEEK * 5, Span::parse("35d"));
	assert_eq!(Span::MINUTE * 90, Span::parse("1h30m"));

	let span_2 = Span::WEEK
		+ Span::DAY * 2
		+ Span::HOUR * 3
		+ Span::MINUTE * 4
		+ Span::SECOND * 5;
	assert_eq!(span, span_2);
	assert_eq!(Span::DAY - Span::SECOND, Span::parse("23h59m59s"));

	use crate::calendar::Time;
	assert_eq!(
		Span::DAY - Span::SECOND,
		Time::hms_checked(23, 59, 59).as_span()
	);
}