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
//! FHIR Time, Date, DateTime and Instant types.

use std::{cmp::Ordering, str::FromStr};

use serde::{Deserialize, Serialize};
use time::{error::Parse, format_description::well_known::Rfc3339, OffsetDateTime};

use crate::error::DateFormatError;

/// FHIR instant type: <https://hl7.org/fhir/datatypes.html#instant>
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Instant(#[serde(with = "time::serde::rfc3339")] pub OffsetDateTime);

/// FHIR date type: <https://hl7.org/fhir/datatypes.html#date>
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Date {
	/// Date in the format of YYYY
	Year(i32),
	/// Date in the format of YYYY-MM
	YearMonth(i32, time::Month),
	/// Date in the format of YYYY-MM-DD
	Date(time::Date),
}

/// FHIR dateTime type: <https://hl7.org/fhir/datatypes.html#dateTime>
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(untagged)]
pub enum DateTime {
	/// Date that does not contain time or timezone
	Date(Date),
	/// Full date and time
	DateTime(Instant),
}

/// FHIR time type: <https://hl7.org/fhir/datatypes.html#time>
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Time(#[serde(with = "serde_time")] pub time::Time);

/// Serde module for serialize and deserialize function for the type.
mod serde_time {
	use serde::{Deserialize, Serialize};
	use time::{format_description::FormatItem, macros::format_description};

	/// Time format `hh:mm:ss`.
	const TIME_FORMAT: &[FormatItem<'_>] = format_description!("[hour]:[minute]:[second]");
	/// Time format for `hh:mm:ss[.SSS]`.
	const TIME_FORMAT_SUBSEC: &[FormatItem<'_>] = fhir_time_format();

	/// Time format with optional subseconds.
	const fn fhir_time_format() -> &'static [FormatItem<'static>] {
		/// Optional subseconds.
		const OPTIONAL_SUB_SECONDS: FormatItem<'_> =
			FormatItem::Optional(&FormatItem::Compound(format_description!(".[subsecond]")));
		&[FormatItem::Compound(TIME_FORMAT), OPTIONAL_SUB_SECONDS]
	}

	/// Serialize time, using subseconds iff appropriate.
	#[allow(clippy::trivially_copy_pass_by_ref)] // Parameter types are set by serde.
	pub fn serialize<S>(time: &time::Time, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: serde::Serializer,
	{
		let format = if time.nanosecond() == 0 { TIME_FORMAT } else { TIME_FORMAT_SUBSEC };
		time.format(format).map_err(serde::ser::Error::custom)?.serialize(serializer)
	}

	/// Deserialize time, subseconds optional.
	pub fn deserialize<'de, D>(deserializer: D) -> Result<time::Time, D::Error>
	where
		D: serde::Deserializer<'de>,
	{
		let string = String::deserialize(deserializer)?;
		time::Time::parse(&string, TIME_FORMAT_SUBSEC).map_err(serde::de::Error::custom)
	}
}

impl Serialize for Date {
	/// Serialize date.
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: serde::Serializer,
	{
		match &self {
			// Serialize YYYY
			Date::Year(year) => {
				if (1000..10000).contains(year) {
					year.to_string().serialize(serializer)
				} else {
					Err(serde::ser::Error::custom("Year is not 4 digits long"))
				}
			}
			// Serialize YYYY-MM
			Date::YearMonth(year, month) => {
				if (1000..10000).contains(year) {
					serializer.serialize_str(&format!("{year}-{:02}", *month as u8))
				} else {
					Err(serde::ser::Error::custom("Year is not 4 digits long"))
				}
			}
			// Serialize YYYY-MM-DD
			Date::Date(date) => {
				/// Full date format
				const FORMAT: &[time::format_description::FormatItem<'_>] =
					time::macros::format_description!("[year]-[month]-[day]");
				date.format(FORMAT).map_err(serde::ser::Error::custom)?.serialize(serializer)
			}
		}
	}
}

impl FromStr for Date {
	type Err = DateFormatError;

	fn from_str(s: &str) -> Result<Self, Self::Err> {
		// Split date into parts
		// YYYY(1)-MM(2)-DD(3)
		match s.split('-').count() {
			1 => Ok(Date::Year(s.parse::<i32>()?)),
			2 => {
				let (year, month) = s.split_once('-').ok_or(DateFormatError::StringSplit)?;
				// Convert strings into integers
				let year = year.parse::<i32>()?;
				let month = month.parse::<u8>()?;

				Ok(Date::YearMonth(year, month.try_into()?))
			}
			3 => {
				/// Full date format
				const FORMAT: &[time::format_description::FormatItem<'_>] =
					time::macros::format_description!("[year]-[month]-[day]");
				Ok(Date::Date(time::Date::parse(s, FORMAT)?))
			}
			_ => Err(DateFormatError::InvalidDate),
		}
	}
}

impl<'de> Deserialize<'de> for Date {
	/// Deserialize date.
	fn deserialize<D>(deserializer: D) -> Result<Date, D::Error>
	where
		D: serde::Deserializer<'de>,
	{
		let string = String::deserialize(deserializer)?;
		Date::from_str(&string).map_err(serde::de::Error::custom)
	}
}

impl FromStr for DateTime {
	type Err = DateFormatError;

	fn from_str(s: &str) -> Result<Self, Self::Err> {
		if s.contains('T') {
			let instant = Instant::from_str(s)?;
			Ok(DateTime::DateTime(instant))
		} else {
			let date = Date::from_str(s)?;
			Ok(DateTime::Date(date))
		}
	}
}

impl<'de> Deserialize<'de> for DateTime {
	/// Deserialize datetime.
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where
		D: serde::Deserializer<'de>,
	{
		let string = String::deserialize(deserializer)?;
		Self::from_str(&string).map_err(serde::de::Error::custom)
	}
}

impl FromStr for Instant {
	type Err = Parse;

	fn from_str(s: &str) -> Result<Self, Self::Err> {
		Ok(Instant(OffsetDateTime::parse(s, &Rfc3339)?))
	}
}

impl PartialOrd for Date {
	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
		match (self, other) {
			(Date::Date(ld), r) => ld.partial_cmp(r),
			(l, Date::Date(rd)) => l.partial_cmp(rd),
			(Date::Year(ly), Date::Year(ry)) => ly.partial_cmp(ry),
			(Date::Year(ly), Date::YearMonth(ry, _rm)) => ly.partial_cmp(ry),
			(Date::YearMonth(ly, _lm), Date::Year(ry)) => ly.partial_cmp(ry),
			(Date::YearMonth(ly, lm), Date::YearMonth(ry, rm)) => match ly.partial_cmp(ry)? {
				Ordering::Less => Some(Ordering::Less),
				Ordering::Greater => Some(Ordering::Greater),
				Ordering::Equal => (*lm as u8).partial_cmp(&(*rm as u8)),
			},
		}
	}
}

impl PartialOrd for DateTime {
	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
		match (self, other) {
			(DateTime::Date(ld), DateTime::Date(rd)) => ld.partial_cmp(rd),
			(DateTime::Date(ld), DateTime::DateTime(Instant(rdtm))) => ld.partial_cmp(&rdtm.date()),
			(DateTime::DateTime(Instant(ldtm)), DateTime::Date(rd)) => ldtm.date().partial_cmp(rd),
			(DateTime::DateTime(ldtm), DateTime::DateTime(rdtm)) => ldtm.partial_cmp(rdtm),
		}
	}
}

impl PartialEq<time::Date> for Date {
	fn eq(&self, other: &time::Date) -> bool {
		match self {
			Self::Year(year) => *year == other.year(),
			Self::YearMonth(year, month) => *year == other.year() && *month == other.month(),
			Self::Date(date) => date == other,
		}
	}
}

impl PartialEq<Date> for time::Date {
	fn eq(&self, other: &Date) -> bool {
		match other {
			Date::Year(year) => self.year() == *year,
			Date::YearMonth(year, month) => self.year() == *year && self.month() == *month,
			Date::Date(date) => self == date,
		}
	}
}

impl PartialOrd<time::Date> for Date {
	fn partial_cmp(&self, other: &time::Date) -> Option<Ordering> {
		match self {
			Date::Year(year) => year.partial_cmp(&other.year()),
			Date::YearMonth(year, month) => match year.partial_cmp(&other.year())? {
				Ordering::Less => Some(Ordering::Less),
				Ordering::Greater => Some(Ordering::Greater),
				Ordering::Equal => (*month as u8).partial_cmp(&(other.month() as u8)),
			},
			Date::Date(date) => date.partial_cmp(other),
		}
	}
}

impl PartialOrd<Date> for time::Date {
	fn partial_cmp(&self, other: &Date) -> Option<Ordering> {
		match other {
			Date::Year(year) => self.year().partial_cmp(year),
			Date::YearMonth(year, month) => match self.year().partial_cmp(year)? {
				Ordering::Less => Some(Ordering::Less),
				Ordering::Greater => Some(Ordering::Greater),
				Ordering::Equal => (self.month() as u8).partial_cmp(&(*month as u8)),
			},
			Date::Date(date) => self.partial_cmp(date),
		}
	}
}

impl PartialEq<OffsetDateTime> for DateTime {
	fn eq(&self, other: &OffsetDateTime) -> bool {
		match self {
			Self::Date(date) => *date == other.date(),
			Self::DateTime(Instant(datetime)) => datetime == other,
		}
	}
}

impl PartialEq<DateTime> for OffsetDateTime {
	fn eq(&self, other: &DateTime) -> bool {
		match other {
			DateTime::Date(date) => self.date() == *date,
			DateTime::DateTime(Instant(datetime)) => self == datetime,
		}
	}
}

impl PartialOrd<OffsetDateTime> for DateTime {
	fn partial_cmp(&self, other: &OffsetDateTime) -> Option<Ordering> {
		match self {
			DateTime::Date(date) => date.partial_cmp(&other.date()),
			DateTime::DateTime(Instant(datetime)) => datetime.partial_cmp(other),
		}
	}
}

impl PartialOrd<DateTime> for OffsetDateTime {
	fn partial_cmp(&self, other: &DateTime) -> Option<Ordering> {
		match other {
			DateTime::Date(date) => self.date().partial_cmp(date),
			DateTime::DateTime(Instant(datetime)) => self.partial_cmp(datetime),
		}
	}
}