greg 0.2.5

Simple Unobtrusive Date & Time library
Documentation
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//! *Calendar Time* -- [`Date`], [`Time`], [`Weekday`], formatting & [Time Zones](zone)

mod date;
pub(crate) mod month;
#[macro_use]
mod macros;
#[cfg(feature = "serde")]
mod serde;
mod time;
mod utc;
pub mod zone;

use std::fmt;
use std::str::FromStr;

use crate::{
	Point,
	Span,
	Frame,
	real::Scale
};
use zone::Unsteady;

/// [UTC] is the most basic timezone
///
/// Essentially, this empty type is used to mark the absence of a time zone, used with the [`Calendar`].
/// It also provides `const` versions of some [`Calendar`] methods.
/// These are used internally by the [`Calendar`], which usually just applies or reverts the timezone offset before (and/or after) calling the [`Utc`] version.
///
/// Note again that this crate disrespects [leap seconds], so this struct does not reflect that aspect of UTC.
///
/// [UTC]: https://en.wikipedia.org/wiki/Coordinated_Universal_Time
/// [leap seconds]: https://en.wikipedia.org/wiki/Leap_second
pub struct Utc;

/// Resolves [`DateTime`]s to [`Point`]s and vice-versa, among other things
///
/// Because this crate does not provide a `DateTime<Z: TimeZone>` (for example) type that combines a point in time with an associated timezone, the [`Calendar`] plays a central role in mediating between *[real](crate::real)* and *[calendar](self)* time.
///
/// Different functions are implemented depending on the time zone type `Z` and what guarantees it can make.
/// Specifically, an [`Unsteady`] time zone introduces several edge cases because it does not *map* every [`DateTime`] to a unique [`Point`] -- some are ambiguous and some are skipped.
/// Generally, though, the same functionality is provided for both types of time zones, it is just that the functions need to be different to be explicit about the compromises that are made in order to accommodate the edge cases.
pub struct Calendar<Z>(
	/// A time zone / UTC offset
	pub Z
);

/// [`Date`] & [`Time`]
#[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct DateTime (pub Date, pub Time);

/// Calendar Date
///
/// **Warning**: if you set the fields yourself it is **your** responsibility to ensure that they are valid!
///
/// # Year Zero & Negative Years
///
/// There is some ambiguity regarding negative years (i.e. "BC" or "BCE"), because not everyone agrees on whether there should be a year 0.
/// According to the Wikipedia [article], it is common to go from 1 BC (i.e. `-1`) directly to 1 AD (`+1`).
/// A [message] on the perl mailing list refers to this as the original, "Dionysian" convention in contrast to the "astronomical" convention, which does not skip 0.
/// This library follows the latter because it is more convenient and because ISO8601 includes a year 0 as well (though apparently not negative years, 0 being the lowest).  
/// In practice, this is only relevant when dealing with years before 1 AD and using the "original convention": 0 is 1 BC, -1 is 2 BC, -2 is 3 BC, and so on.
/// Otherwise it doesn't matter.
///
/// [article]: https://en.wikipedia.org/wiki/Year_zero
/// [message]: https://www.nntp.perl.org/group/perl.datetime/2003/02/msg938.html
/// [archived]: https://archive.ph/pGPcY
#[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Date {
	/// Year, may be negative
	pub y: i64,
	/// Month (`1..=12`)
	pub m: u8,
	/// Day (`1..=31`, depending on the month and whether it's a leap year)
	pub d: u8
}

/// Time-of-Day
///
/// **Warning**: if you set the fields yourself it is **your** responsibility to ensure that they are valid!
/// [`Self::is_valid`] can be used to conveniently check.
///
/// Because this library does not respect leap seconds, the `s` field may never be `60`.
#[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct Time {
	/// Hours (`0..24`)
	pub h: u8,
	/// Minutes (`0..60`)
	pub m: u8,
	/// Seconds (`0..60`)
	pub s: u8
}
/// Day of the Week
#[allow(missing_docs)]
#[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum Weekday {
	Monday,
	Tuesday,
	Wednesday,
	Thursday,
	Friday,
	Saturday,
	Sunday
}

/// [`Iterator`] over [`Frame`]s of a certain [`Scale`] produced by [`Calendar::frames`]
///
/// Depending on the [`Scale`] chosen and the time zone in use, [`Frame`]s will have differing lengths, because the iterator favors lining up the start and end [`Point`]s of the produced [`Frame`]s with what you would expect rather than maintaining the same length for each.
/// Basically, if the [`Frame`] that is to be produced at [`Scale::Days`] happens to fall on the day that clocks are set backwards by one hour (thus making the time from midnight to midnight 25 hours), it does not stubbornly produce a [`Frame`] from midnight to 23:00 local time.
/// Instead, with [`Scale::Days`] (and above), the [`Frame`]s always start and end at midnight local time\*, such that the time is fully (no gaps) and "uniquely" (no overlaps) divided, but not evenly.
///
/// [`Frame`]s may have differing lengths for the following reasons:
/// - obviously, [`Months`](Scale::Months) don't all have the same amount of days,
/// - similarly, leap [`Years`](Scale::Years) exist,
/// - finally, because the time zone is [`Unsteady`], a [`Frame`] may fall on a time zone transition.
///
/// For convenience, [`Frame`]s of duration 0 are skipped.
/// These would occur whenever the time zone transition (i.e. the change in offset) is greater than or equal to the length of the [`Scale`].
/// Though most time zone transitions amount to a single hour, much larger ones (i.e. an entire day) have occurred.
/// In such an edge case, if combined with [`Scale::Minutes`], [`Iterator::next`] would take *significantly* longer to complete.
/// [`Scale::Seconds`] is not affected by this (but why would you ever use it, anyway?).
///
/// Generally, use of [`Scale`]s below [`Scale::Hours`] is discouraged, and using [`Scale::Hours`] is to be done with caution.
/// To be precise: don't ever rely on the duration of the [`Frame`]s being *close* to the [`Scale`].
///
/// \* if it exists.
/// It is theoretically possible that midnight is skipped in a time zone.
pub struct Frames<'c, Z> {
	calendar: &'c Calendar<Z>,
	scale: Scale,
	previous: Point,
	state: State
}

/// Reverse [`Frames`] to go back in time
///
/// This simply wraps [`Frames`] to implement [`Iterator`] with [`Frames::prev`] instead.
pub struct FramesRev<'c, Z>(pub Frames<'c, Z>);

/// Internal state of the [`Frames`] iterator
enum State {
	Date(Date),
	Utc(Point),
	/// Special case because there are no sub-second offsets
	Seconds
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Error encountered parsing [`DateTime`], [`Date`] or [`Time`]
pub enum ParseError {
	/// Integer overflowed parsing number segment
	Overflow,
	/// Empty string is not a valid [`DateTime`], [`Date`] or [`Time`]
	Empty,
	/// Invalid date/time format
	Format,
	/// Invalid date/time
	Invalid
}

/*
 *	DATE TIME
 */

impl fmt::Display for DateTime {
	/// Components separated by a space: `YYYY-MM-DD hh:mm:ss` (i.e. `2022-12-31 12:34:56`)
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		let Self (date, time) = self;
		write!(f, "{date} {time}")
	}
}
impl fmt::Debug for DateTime {
	/// Same as [`Display`](fmt::Display): `YYYY-MM-DD hh:mm:ss` (i.e. `2022-12-31 12:34:56`)
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		fmt::Display::fmt(self, f)
	}
}
impl DateTime {
	/// Try to parse [`Date`] and [`Time`] separated by space or `T`
	///
	/// May also accept dates with too much or too little 0-padding for the year.
	/// Month, day, hour, minute and second segments must be exactly 2 digits.
	///
	/// Note that unlike the [`ymd_hms!`](crate::ymd_hms) macro (which only works on literals), this function (because it uses [`Time::try_parse`]) also allows for the seconds to be omitted.
	/// So this function accepts `hh:mm` [`Time`] components as well as `hh:mm:ss`.
	///
	///```
	/// use greg::calendar::DateTime;
	/// use greg::ymd_hms;
	///
	/// assert_eq!(
	///     DateTime::try_parse("2022-01-01 00:00:00"),
	///     Ok(ymd_hms!(2022-01-01 00:00:00))
	/// );
	/// assert_eq!(
	///     DateTime::try_parse("2020-06-06 10:15"),
	///     Ok(ymd_hms!(2020-06-06 10:15:00))
	/// );
	/// assert_eq!(
	///     DateTime::try_parse("1234-01-23T12:34:56"),
	///     Ok(ymd_hms!(1234-01-23 12:34:56))
	/// );
	///
	/// use greg::calendar::ParseError;
	///
	/// assert_eq!(
	///     DateTime::try_parse("2021-01-01"),
	///     Err(ParseError::Format)
	/// );
	/// assert_eq!(
	///     DateTime::try_parse("09:30:00"),
	///     Err(ParseError::Format)
	/// );
	/// // no leap seconds
	/// assert!(DateTime::try_parse("2016-12-31 23:59:60").is_err());
	/// assert!(DateTime::try_parse("Jan 1st, 2020 2pm").is_err());
	///```
	pub const fn try_parse(from: &str) -> Result<Self, ParseError> {
		let bytes = from.as_bytes();
		let (date_bytes, time_len) = match bytes {
			[d @ .., b'T' | b' ', _, _, b':', _, _, b':', _, _] => (d, 8),
			[d @ .., b'T' | b' ', _, _, b':', _, _] => (d, 5),
			[] => return Err(ParseError::Empty),
			_ => return Err(ParseError::Format)
		};
		let time_bytes = bytes.split_at(bytes.len() - time_len).1;

		let Ok(date_str) = std::str::from_utf8(date_bytes) else {
			return Err(ParseError::Format);
		};
		let Ok(time_str) = std::str::from_utf8(time_bytes) else {
			return Err(ParseError::Format);
		};
		let date_time = Self (
			match Date::try_parse(date_str) {
				Ok(date) => date,
				Err(err) => return Err(err)
			},
			match Time::try_parse(time_str) {
				Ok(time) => time,
				Err(err) => return Err(err)
			},
		);
		Ok(date_time)
	}
	/// Parse [`Date`] and [`Time`] and panic if invalid
	///
	/// Just a convenient wrapper around [`try_parse`](Self::try_parse) (since there's no `.unwrap()` in `const`).
	///
	///```
	/// use greg::calendar::DateTime;
	/// const NYE: DateTime = DateTime::parse("2023-12-31 23:59:59");
	///
	/// assert_eq!(
	///     DateTime::parse("2023-08-17T13:37"),
	///     greg::ymd_hms!(2023-08-17 13:37:00)
	/// );
	/// assert_eq!(
	///     DateTime::parse("2023-12-24 18:00:00"),
	///     greg::ymd_hms!(2023-12-24 18:00:00)
	/// );
	///```
	///
	/// This is mainly useful in `const` contexts, since the panic gets caught at compile-time.
	///
	///```compile_fail
	/// use greg::calendar::DateTime;
	/// // not a leap year
	/// const LEAP: DateTime = DateTime::parse("2023-02-29 05:30");
	///```
	///
	/// See also the [`ymd_hms!`](crate::ymd_hms) macro for defining [`DateTime`]s with literals at compile-time.
	#[must_use]
	pub const fn parse(from: &str) -> Self {
		match Self::try_parse(from) {
			Ok(date_time) => date_time,
			Err(err) => panic!("{}", err.as_str())
		}
	}
}
impl FromStr for DateTime {
	type Err = ParseError;
	/// Parse [`Date`] and [`Time`] separated by space or `T`
	///
	/// May also accept dates with too much or too little 0-padding for the year.
	/// Month, day, hour, minute and second segments must be exactly 2 digits.
	/// Uses [`Date::try_parse`] and [`Time::try_parse`] internally, see the documentation there for details.
	///
	///```
	/// use greg::calendar::DateTime;
	/// use greg::ymd_hms;
	///
	/// assert_eq!(
	///     "2022-01-01 00:00:00".parse(),
	///     Ok(ymd_hms!(2022-01-01 00:00:00))
	/// );
	/// assert_eq!(
	///     "2020-06-06 10:15".parse(),
	///     Ok(ymd_hms!(2020-06-06 10:15:00))
	/// );
	/// assert_eq!(
	///     "1234-01-23T12:34:56".parse(),
	///     Ok(ymd_hms!(1234-01-23 12:34:56))
	/// );
	///
	/// assert!("2021-01-01".parse::<DateTime>().is_err());
	/// assert!("09:30:00".parse::<DateTime>().is_err());
	/// // no leap seconds
	/// assert!("2016-12-31 23:59:60".parse::<DateTime>().is_err());
	/// assert!("Jan 1st, 2020 2pm".parse::<DateTime>().is_err());
	///```
	fn from_str(s: &str) -> Result<Self, Self::Err> {
		Self::try_parse(s)
	}
}

/*
 *	WEEKDAY
 */

impl fmt::Display for Weekday {
	/// Full-length weekday name (i.e. `Thursday`)
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		let day = match self {
			Weekday::Monday => "Monday",
			Weekday::Tuesday => "Tuesday",
			Weekday::Wednesday => "Wednesday",
			Weekday::Thursday => "Thursday",
			Weekday::Friday => "Friday",
			Weekday::Saturday => "Saturday",
			Weekday::Sunday => "Sunday",
		};
		f.write_str(day)
	}
}
impl fmt::Debug for Weekday {
	/// Same as [`Display`](fmt::Display), full-length weekday name (i.e. `Tuesday`)
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		fmt::Display::fmt(self, f)
	}
}

/*
 *	STATE
 */

impl State {
	fn forward<Z: Unsteady>(
		&mut self,
		calendar: &Calendar<Z>,
		scale: Scale,
		previous: Point)
		-> Point
	{
		match self {
			Self::Date(ref mut date) if scale == Scale::Years => {
				date.y += 1;
				calendar.resolve_midnight_lossy(*date)
			},
			Self::Date(ref mut date) if scale == Scale::Months => {
				// TODO: consider optimizing with mod & div
				match date.m == 12 {
					true => {
						date.y += 1;
						date.m = 1;
					},
					false => date.m += 1
				};
				calendar.resolve_midnight_lossy(*date)
			},
			Self::Date(_) => unreachable!(),
			Self::Utc(ref mut utc_point) => {
				*utc_point = *utc_point + Span::from(scale);
				calendar.0.revert_lossy(*utc_point)
			},
			Self::Seconds => previous + Span::SECOND
		}
	}
	fn backward<Z: Unsteady>(
		&mut self,
		calendar: &Calendar<Z>,
		scale: Scale,
		previous: Point)
		-> Point
	{
		match self {
			Self::Date(ref mut date) if scale == Scale::Years => {
				date.y -= 1;
				calendar.resolve_midnight_lossy(*date)
			},
			Self::Date(ref mut date) if scale == Scale::Months => {
				// TODO: consider optimizing with mod & div
				match date.m == 1 {
					true => {
						date.y -= 1;
						date.m = 12;
					},
					false => date.m -= 1
				};
				calendar.resolve_midnight_lossy(*date)
			},
			Self::Date(_) => unreachable!(),
			Self::Utc(ref mut utc_point) => {
				*utc_point = *utc_point - Span::from(scale);
				calendar.0.revert_lossy(*utc_point)
			},
			Self::Seconds => previous - Span::SECOND
		}
	}
}


/*
 *	FRAMES
 */

impl<Z: Unsteady> Iterator for Frames<'_, Z> {
	type Item = Frame;
	fn next(&mut self) -> Option<Self::Item> {
		// If the frame we produced is of 0 duration, we need to loop
		// less "elegant" than recursion, but won't overflow the stack
		loop {
			let start = self.previous;
			let stop = self.state.forward(
				self.calendar,
				self.scale,
				self.previous
			);
			self.previous = stop;
			if start != stop {
				break Some(Frame {start, stop});
			}
			else {continue}
		}
	}
}
impl<'c, Z> Frames<'c, Z> {
	/// Wrap `self` with [`FramesRev`] to get an [`Iterator`] going backwards
	pub fn rev(self) -> FramesRev<'c, Z> {FramesRev(self)}
}

impl<Z: Unsteady> Frames<'_, Z> {
	/// Get the previous [`Frame`] -- the opposite of [`Frames::next`]
	///
	/// Calling this after [`Frames::next`] will give the same [`Frame`] again.
	/// Use [`Frames::rev`] to get an iterator that calls this.
	pub fn prev(&mut self) -> Frame {
		// If the frame we produced is of 0 duration, we need to loop
		// less "elegant" than recursion, but won't overflow the stack
		loop {
			let stop = self.previous;
			let start = self.state.backward(
				self.calendar,
				self.scale,
				self.previous
			);
			self.previous = start;
			if start != stop {
				break Frame {start, stop};
			}
			else {continue}
		}
	}
}

/*
 *	FRAMES REV
 */

impl<Z: Unsteady> Iterator for FramesRev<'_, Z> {
	type Item = Frame;
	fn next(&mut self) -> Option<Self::Item> {Some(self.0.prev())}
}
impl<Z: Unsteady> FramesRev<'_, Z> {
	/// Get the previous [`Frame`] -- the opposite of [`FramesRev::next`]
	///
	/// Naturally, this is the same as [`Frames::next`].
	pub fn prev(&mut self) -> Frame {self.0.next().unwrap()}
}

/*
 *	PARSE ERROR
 */

impl ParseError {
	const fn as_str(&self) -> &'static str {
		match self {
			Self::Overflow => "date/time overflowed integer",
			Self::Empty => "invalid empty date/time",
			Self::Format => "invalid date/time format",
			Self::Invalid => "invalid date/time"
		}
	}
}

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