greg 0.1.2

WIP: datetime library
Documentation
//! *Calendar Time* -- [`Date`], [`Time`], [`Weekday`], formatting & [Time Zones](zone)

mod date;
pub(crate) mod month;
#[macro_use]
mod macros;
mod time;
mod utc;
pub mod zone;

use std::fmt;
use std::num::ParseIntError;
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 an 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 {
	/// Error encountered parsing number segment
	ParseInt(ParseIntError),
	/// 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 FromStr for DateTime {
	type Err = ParseError;
	/// Parse [`Date`] and [`Time`] separated by space or `T`
	///
	/// May also accept strings with too much or too little 0-padding.
	/// Uses [`Date::from_str`] and [`Time::from_str`] 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> {
		if s.is_empty() {return Err(ParseError::Empty)}

		let mut split = s.splitn(2, [' ', 'T']);
		let date = split.next()
			.ok_or(ParseError::Format)?
			.parse()?;
		let time = split.next()
			.ok_or(ParseError::Format)?
			.parse()?;

		Ok(Self (date, time))
	}
}

/*
 *	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_earliest_midnight(*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_earliest_midnight(*date)
			},
			Self::Date(_) => unreachable!(),
			Self::Utc(ref mut utc_point) => {
				*utc_point = *utc_point + Span::from(scale);
				calendar.0.revert_to_earliest(*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_earliest_midnight(*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_earliest_midnight(*date)
			},
			Self::Date(_) => unreachable!(),
			Self::Utc(ref mut utc_point) => {
				*utc_point = *utc_point - Span::from(scale);
				calendar.0.revert_to_earliest(*utc_point)
			},
			Self::Seconds => previous - Span::SECOND
		}
	}
}


/*
 *	FRAMES
 */

impl<'c, Z: Unsteady> Iterator for Frames<'c, 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<'c, Z: Unsteady> Frames<'c, 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<'c, Z: Unsteady> Iterator for FramesRev<'c, Z> {
	type Item = Frame;
	fn next(&mut self) -> Option<Self::Item> {Some(self.0.prev())}
}
impl<'c, Z: Unsteady> FramesRev<'c, 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 fmt::Display for ParseError {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self {
			Self::ParseInt(e) => fmt::Display::fmt(e, f),
			Self::Empty => f.write_str("invalid empty date/time"),
			Self::Format => f.write_str("invalid date/time format"),
			Self::Invalid => f.write_str("invalid date/time")
		}
	}
}

impl From<ParseIntError> for ParseError {
	fn from(e: ParseIntError) -> Self {Self::ParseInt(e)}
}