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
use chrono::{Datelike, FixedOffset, Timelike, Utc};
use std::{fmt, str::FromStr};

use crate::{
	lexical::{InvalidDateTime, LexicalFormOf},
	utils::div_rem,
	Datatype, ParseXsd, XsdValue,
};

#[derive(Debug, thiserror::Error)]
#[error("missing timezone")]
pub struct MissingTimezone;

#[derive(Debug, thiserror::Error)]
#[error("invalid timezone")]
pub struct InvalidTimezone(chrono::NaiveDateTime, FixedOffset);

#[derive(Debug, thiserror::Error)]
pub enum TimezoneError {
	#[error(transparent)]
	Missing(#[from] MissingTimezone),

	#[error(transparent)]
	Invalid(#[from] InvalidTimezone),
}

#[derive(Debug, thiserror::Error)]
#[error("invalid datetime value")]
pub struct InvalidDateTimeValue;

#[derive(Debug, Clone, Copy, Hash)]
pub struct DateTime {
	date_time: chrono::NaiveDateTime,
	offset: Option<FixedOffset>,
}

impl DateTime {
	pub fn new(date_time: chrono::NaiveDateTime, offset: Option<FixedOffset>) -> Self {
		Self { date_time, offset }
	}

	/// Returns a `DateTime` which corresponds to the current time and date.
	pub fn now() -> Self {
		Utc::now().into()
	}

	/// Returns a `DateTime` which corresponds to the current time and date,
	/// with millisecond precision (at most).
	pub fn now_ms() -> Self {
		let now = Utc::now();
		let ms = now.timestamp_subsec_millis();
		let ns = ms * 1_000_000;
		now.with_nanosecond(ns).unwrap_or(now).into()
	}

	pub fn into_string(self) -> String {
		self.to_string()
	}
}

impl XsdValue for DateTime {
	fn datatype(&self) -> Datatype {
		Datatype::DateTime
	}
}

impl ParseXsd for DateTime {
	type LexicalForm = crate::lexical::DateTime;
}

impl fmt::Display for DateTime {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(
			f,
			"{}-{:02}-{:02}T{:02}:{:02}:{:02}",
			DisplayYear(self.date_time.year()),
			self.date_time.month(),
			self.date_time.day(),
			self.date_time.hour(),
			self.date_time.minute(),
			self.date_time.second()
		)?;

		format_nanoseconds(self.date_time.nanosecond(), f)?;
		format_timezone(self.offset, f)
	}
}

pub(crate) fn format_nanoseconds(ns: u32, f: &mut fmt::Formatter) -> fmt::Result {
	let mut nano = ns % 1_000_000_000;

	if nano == 0 {
		Ok(())
	} else {
		let mut buffer = *b".000000000";
		let mut i = 10;
		let mut trailing = true;
		let mut end = 10;
		while nano > 0 {
			i -= 1;
			let (rest, d) = div_rem(nano, 10);
			nano = rest;

			if trailing {
				if d == 0 {
					end = i;
					continue;
				} else {
					trailing = false;
				}
			}

			buffer[i] = b'0' + d as u8;
		}

		let string = unsafe { std::str::from_utf8_unchecked(&buffer[..end]) };

		f.write_str(string)
	}
}

pub(crate) fn format_timezone(tz: Option<FixedOffset>, f: &mut fmt::Formatter) -> fmt::Result {
	match tz {
		Some(tz) => {
			if tz.local_minus_utc() == 0 {
				write!(f, "Z")
			} else {
				let tz = if tz.local_minus_utc() > 0 {
					write!(f, "+")?;
					tz.local_minus_utc() as u32
				} else {
					write!(f, "-")?;
					-tz.local_minus_utc() as u32
				};

				let tz_minutes = tz / 60;
				let hours = tz_minutes / 60;
				let minutes = tz_minutes % 60;
				write!(f, "{hours:02}:{minutes:02}")
			}
		}
		None => Ok(()),
	}
}

pub(crate) struct DisplayYear(pub i32);

impl fmt::Display for DisplayYear {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		if self.0.is_negative() {
			write!(f, "-{:04}", -self.0)
		} else {
			write!(f, "{:04}", self.0)
		}
	}
}

#[derive(Debug, thiserror::Error)]
pub enum DateTimeFromStrError {
	#[error("invalid date syntax")]
	Syntax(#[from] InvalidDateTime<String>),

	#[error(transparent)]
	Value(#[from] InvalidDateTimeValue),
}

impl FromStr for DateTime {
	type Err = DateTimeFromStrError;

	fn from_str(s: &str) -> Result<Self, Self::Err> {
		let lexical_value = crate::lexical::DateTime::new(s)
			.map_err(|InvalidDateTime(s)| InvalidDateTime(s.to_owned()))?;
		lexical_value.try_as_value().map_err(Into::into)
	}
}

impl From<chrono::DateTime<FixedOffset>> for DateTime {
	fn from(value: chrono::DateTime<FixedOffset>) -> Self {
		let naive_date_time = value.naive_utc();
		let offset = *value.offset();
		Self::new(naive_date_time, Some(offset))
	}
}

impl From<chrono::DateTime<Utc>> for DateTime {
	fn from(value: chrono::DateTime<Utc>) -> Self {
		let naive_date_time = value.naive_utc();
		let offset = FixedOffset::east_opt(0).unwrap();
		Self::new(naive_date_time, Some(offset))
	}
}

impl TryFrom<DateTime> for chrono::DateTime<FixedOffset> {
	type Error = MissingTimezone;

	fn try_from(value: DateTime) -> Result<Self, MissingTimezone> {
		match value.offset {
			Some(offset) => Ok(value.date_time.and_local_timezone(offset).unwrap()),
			None => Err(MissingTimezone),
		}
	}
}

impl TryFrom<DateTime> for chrono::DateTime<Utc> {
	type Error = TimezoneError;

	fn try_from(value: DateTime) -> Result<Self, TimezoneError> {
		let fixed: chrono::DateTime<FixedOffset> = value.try_into()?;
		Ok(fixed.into())
	}
}

#[cfg(feature = "serde")]
impl serde::Serialize for DateTime {
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: serde::Serializer,
	{
		self.into_string().serialize(serializer)
	}
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for DateTime {
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where
		D: serde::Deserializer<'de>,
	{
		struct Visitor;

		impl<'de> serde::de::Visitor<'de> for Visitor {
			type Value = DateTime;

			fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
				formatter.write_str("a http://www.w3.org/2001/XMLSchema#dateTime")
			}

			fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
			where
				E: serde::de::Error,
			{
				v.parse().map_err(|e| E::custom(e))
			}
		}

		deserializer.deserialize_str(Visitor)
	}
}