whatwg_datetime/components/
timezone_offset.rs

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
use crate::parse_format;
use crate::tokens::Token;
use crate::utils::collect_ascii_digits;

/// A time-zone offset, with a signed number of hours and minutes.
///
/// # Examples
/// ```
/// use whatwg_datetime::{parse_timezone_offset, TimeZoneOffset};
///
/// assert_eq!(parse_timezone_offset("-07:00"), TimeZoneOffset::new_opt(-7, 0));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TimeZoneOffset {
	pub(crate) hour: i32,
	pub(crate) minute: i32,
}

impl TimeZoneOffset {
	#[inline]
	pub(crate) fn new(hour: i32, minute: i32) -> Self {
		Self { hour, minute }
	}

	/// Creates a new `TimeZoneOffset` from a signed number of hours and minutes.
	///
	/// This asserts that:
	///  - hours are in between -23 and 23, inclusive,
	///  - minutes are in between 0 and 59, inclusive
	///
	/// # Examples
	/// ```
	/// use whatwg_datetime::TimeZoneOffset;
	///
	/// assert!(TimeZoneOffset::new_opt(-7, 0).is_some());
	/// assert!(TimeZoneOffset::new_opt(23, 59).is_some());
	/// assert!(TimeZoneOffset::new_opt(24, 0).is_none()); // Hours must be between [-23, 23]
	/// assert!(TimeZoneOffset::new_opt(1, 60).is_none()); // Minutes must be between [0, 59]
	/// ```
	pub fn new_opt(hours: i32, minutes: i32) -> Option<Self> {
		if !(-23..=23).contains(&hours) {
			return None;
		}

		if !(0..=59).contains(&minutes) {
			return None;
		}

		Some(Self::new(hours, minutes))
	}

	/// A minute component. This is a number from 0 to 59, inclusive.
	///
	/// # Examples
	/// ```
	/// use whatwg_datetime::TimeZoneOffset;
	///
	/// let tz_offset = TimeZoneOffset::new_opt(-7, 0).unwrap();
	/// assert_eq!(tz_offset.minute(), 0);
	/// ```
	#[inline]
	pub const fn minute(&self) -> i32 {
		self.minute
	}

	/// A hour component. This is a number from -23 to 23, inclusive.
	///
	/// # Examples
	/// ```
	/// use whatwg_datetime::TimeZoneOffset;
	///
	/// let tz_offset = TimeZoneOffset::new_opt(-7, 0).unwrap();
	/// assert_eq!(tz_offset.hour(), -7);
	/// ```
	#[inline]
	pub const fn hour(&self) -> i32 {
		self.hour
	}
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TimeZoneSign {
	Positive,
	Negative,
}

impl TryFrom<char> for TimeZoneSign {
	type Error = ();
	fn try_from(value: char) -> Result<Self, Self::Error> {
		match value {
			Token::PLUS => Ok(TimeZoneSign::Positive),
			Token::MINUS => Ok(TimeZoneSign::Negative),
			_ => Err(()),
		}
	}
}

/// Parse a time-zone offset, with a signed number of hours and minutes
///
/// This follows the rules for [parsing a time-zone offset string][whatwg-html-parse]
/// per [WHATWG HTML Standard § 2.3.5.6 Time zones][whatwg-html-tzoffset].
///
/// # Examples
/// ```
/// use whatwg_datetime::{parse_timezone_offset, TimeZoneOffset};
///
/// // Parse a local datetime string with a date,
/// // a T delimiter, anda  time with fractional seconds
/// assert_eq!(
///     parse_timezone_offset("-07:00"),
///     TimeZoneOffset::new_opt(-7, 0)
/// );
/// ```
///
/// [whatwg-html-tzoffset]: https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#time-zones
/// [whatwg-html-parse]: https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#parse-a-time-zone-offset-string
#[inline]
pub fn parse_timezone_offset(s: &str) -> Option<TimeZoneOffset> {
	parse_format(s, parse_timezone_offset_component)
}

/// Low-level function for parsing an individual timezone offset component
/// at a given position
///
/// This follows the rules for [parsing a time-zone offset component][whatwg-html-parse]
/// per [WHATWG HTML Standard § 2.3.5.6 Time zones][whatwg-html-tzoffset].
///
/// > **Note**:
/// > This function exposes a lower-level API than [`parse_timezone_offset`].
/// > More than likely, you will want to use [`parse_timezone_offset`] instead.
///
/// # Examples
/// ```
/// use whatwg_datetime::{parse_timezone_offset_component, TimeZoneOffset};
///
/// let mut position = 0usize;
/// let date = parse_timezone_offset_component("-07:00", &mut position);
///
/// assert_eq!(date, TimeZoneOffset::new_opt(-7, 0));
/// ```
///
/// [whatwg-html-tzoffset]: https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#time-zones
/// [whatwg-html-parse]: https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#parse-a-time-zone-offset-component
pub fn parse_timezone_offset_component(s: &str, position: &mut usize) -> Option<TimeZoneOffset> {
	let char_at = s.chars().nth(*position);

	let mut minutes = 0i32;
	let mut hours = 0i32;

	match char_at {
		Some(Token::Z) => {
			*position += 1;
		}
		Some(Token::PLUS) | Some(Token::MINUS) => {
			let sign = TimeZoneSign::try_from(char_at.unwrap()).ok().unwrap();
			*position += 1;

			let collected = collect_ascii_digits(s, position);
			let collected_len = collected.len();
			if collected_len == 2 {
				hours = collected.parse::<i32>().unwrap();
				if *position > s.len()
					|| s.chars().nth(*position) != Some(Token::COLON)
				{
					return None;
				} else {
					*position += 1;
				}

				let parsed_mins = collect_ascii_digits(s, position);
				if parsed_mins.len() != 2 {
					return None;
				}

				minutes = parsed_mins.parse::<i32>().unwrap();
			} else if collected_len == 4 {
				let (hour_str, min_str) = collected.split_at(2);
				hours = hour_str.parse::<i32>().unwrap();
				minutes = min_str.parse::<i32>().unwrap();
			} else {
				return None;
			}

			if !(0..=23).contains(&hours) {
				return None;
			}

			if !(0..=59).contains(&minutes) {
				return None;
			}

			if sign == TimeZoneSign::Negative {
				hours *= -1;
				minutes *= -1;
			}
		}
		_ => (),
	}

	Some(TimeZoneOffset::new(hours, minutes))
}

#[cfg(test)]
mod tests {
	#[rustfmt::skip]
	use super::{
		parse_timezone_offset,
		parse_timezone_offset_component,
		TimeZoneOffset,
		TimeZoneSign,
	};

	#[test]
	pub fn test_parse_timezone_sign_tryfrom_char_positive() {
		let parsed = TimeZoneSign::try_from('+');
		assert_eq!(parsed, Ok(TimeZoneSign::Positive));
	}

	#[test]
	pub fn test_parse_timezone_sign_tryfrom_char_negative() {
		let parsed = TimeZoneSign::try_from('-');
		assert_eq!(parsed, Ok(TimeZoneSign::Negative));
	}

	#[test]
	pub fn test_parse_timezone_sign_tryfrom_char_fails() {
		let parsed = TimeZoneSign::try_from('a');
		assert_eq!(parsed, Err(()));
	}

	#[test]
	pub fn test_parse_timezone_offset() {
		let parsed = parse_timezone_offset("+01:00");
		assert_eq!(parsed, Some(TimeZoneOffset::new(1, 0)));
	}

	#[test]
	pub fn test_parse_timezone_offset_z() {
		let parsed = parse_timezone_offset("Z");
		assert_eq!(parsed, Some(TimeZoneOffset::new(0, 0)));
	}

	#[test]
	pub fn test_parse_timezone_offset_plus_1_hour_colon() {
		let mut position = 0usize;
		let parsed = parse_timezone_offset_component("+01:00", &mut position);

		assert_eq!(parsed, Some(TimeZoneOffset::new(1, 0)));
	}

	#[test]
	pub fn test_parse_timezone_offset_neg_1_hour_colon() {
		let mut position = 0usize;
		let parsed = parse_timezone_offset_component("-01:00", &mut position);

		assert_eq!(parsed, Some(TimeZoneOffset::new(-1, 0)));
	}

	#[test]
	pub fn test_parse_timezone_offset_plus_1_hour_no_delim() {
		let mut position = 0usize;
		let parsed = parse_timezone_offset_component("+0100", &mut position);

		assert_eq!(parsed, Some(TimeZoneOffset::new(1, 0)));
	}

	#[test]
	fn parse_timezone_offset_component_neg_1_hour_no_delim() {
		let mut position = 0usize;
		let parsed = parse_timezone_offset_component("-0100", &mut position);

		assert_eq!(parsed, Some(TimeZoneOffset::new(-1, 0)));
	}

	#[test]
	fn parse_timezone_offset_fails_not_colon() {
		let mut position = 0usize;
		let parsed = parse_timezone_offset_component("-01/", &mut position);

		assert_eq!(parsed, None);
	}

	#[test]
	fn parse_timezone_offset_fails_invalid_min_length() {
		let mut position = 0usize;
		let parsed = parse_timezone_offset_component("-010", &mut position);

		assert_eq!(parsed, None);
	}

	#[test]
	fn parse_timezone_offset_fails_colon_invalid_length_empty() {
		let mut position = 0usize;
		let parsed = parse_timezone_offset_component("-01:", &mut position);

		assert_eq!(parsed, None);
	}

	#[test]
	fn parse_timezone_offset_fails_colon_invalid_length() {
		let mut position = 0usize;
		let parsed = parse_timezone_offset_component("-01:0", &mut position);

		assert_eq!(parsed, None);
	}

	#[test]
	fn parse_timezone_offset_fails_invalid_length() {
		let mut position = 0usize;
		let parsed = parse_timezone_offset_component("-01000", &mut position);

		assert_eq!(parsed, None);
	}

	#[test]
	fn parse_timezone_offset_fails_invalid_hour_upper_bound() {
		let mut position = 0usize;
		let parsed = parse_timezone_offset_component("+24:00", &mut position);

		assert_eq!(parsed, None);
	}

	#[test]
	fn parse_timezone_offset_fails_invalid_minute_upper_bound() {
		let mut position = 0usize;
		let parsed = parse_timezone_offset_component("-00:67", &mut position);

		assert_eq!(parsed, None);
	}
}