lofty 0.24.0

Audio metadata 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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
use crate::config::ParsingMode;
use crate::error::{ErrorKind, LoftyError, Result};
use crate::macros::{err, parse_mode_choice};

use std::fmt::Display;
use std::io::Read;
use std::str::FromStr;

use byteorder::ReadBytesExt;

/// A subset of the ISO 8601 timestamp format
///
/// # Examples
///
/// ```
/// use lofty::tag::items::Timestamp;
///
/// let timestamp: Timestamp = "2024-06-15T14:30:00".parse().unwrap();
/// assert_eq!(timestamp.year, 2024);
/// assert_eq!(timestamp.month, Some(6));
/// assert_eq!(timestamp.to_string(), "2024-06-15T14:30:00");
/// ```
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Default)]
pub struct Timestamp {
	/// The year component (e.g. 2024)
	pub year: u16,
	/// The month component (1-12)
	pub month: Option<u8>,
	/// The day component (1-31)
	pub day: Option<u8>,
	/// The hour component (0-23)
	pub hour: Option<u8>,
	/// The minute component (0-59)
	pub minute: Option<u8>,
	/// The second component (0-59)
	pub second: Option<u8>,
}

impl PartialOrd for Timestamp {
	fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
		Some(self.cmp(other))
	}
}

impl Ord for Timestamp {
	fn cmp(&self, other: &Self) -> std::cmp::Ordering {
		self.year
			.cmp(&other.year)
			.then(self.month.cmp(&other.month))
			.then(self.day.cmp(&other.day))
			.then(self.hour.cmp(&other.hour))
			.then(self.minute.cmp(&other.minute))
			.then(self.second.cmp(&other.second))
	}
}

impl Display for Timestamp {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(f, "{:04}", self.year)?;

		if let Some(month) = self.month {
			write!(f, "-{:02}", month)?;

			if let Some(day) = self.day {
				write!(f, "-{:02}", day)?;

				if let Some(hour) = self.hour {
					write!(f, "T{:02}", hour)?;

					if let Some(minute) = self.minute {
						write!(f, ":{:02}", minute)?;

						if let Some(second) = self.second {
							write!(f, ":{:02}", second)?;
						}
					}
				}
			}
		}

		Ok(())
	}
}

impl FromStr for Timestamp {
	type Err = LoftyError;

	fn from_str(s: &str) -> Result<Self> {
		Timestamp::parse(&mut s.as_bytes(), ParsingMode::BestAttempt)?
			.ok_or_else(|| LoftyError::new(ErrorKind::BadTimestamp("Timestamp frame is empty")))
	}
}

impl Timestamp {
	/// The maximum length of a timestamp in bytes
	pub const MAX_LENGTH: usize = 19;

	const SEPARATORS: [u8; 3] = [b'-', b'T', b':'];

	/// Read a [`Timestamp`]
	///
	/// NOTES:
	///
	/// * When not using [`ParsingMode::Strict`], this will skip any leading whitespace
	/// * Afterwards, this will take [`Self::MAX_LENGTH`] bytes from the reader. Ensure that it only contains the timestamp
	///
	/// # Errors
	///
	/// * Failure to read from `reader`
	/// * The timestamp is invalid
	pub fn parse<R>(reader: &mut R, parse_mode: ParsingMode) -> Result<Option<Self>>
	where
		R: Read,
	{
		macro_rules! read_segment {
			($expr:expr) => {
				match $expr {
					Ok((_, 0)) => break,
					Ok((val, _)) => Some(val as u8),
					Err(e) => return Err(e),
				}
			};
		}

		let mut c = match reader.read_u8() {
			Ok(val) => val,
			Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
				if parse_mode == ParsingMode::Strict {
					err!(BadTimestamp("Timestamp frame is empty"))
				}

				return Ok(None);
			},
			Err(e) => return Err(e.into()),
		};

		if parse_mode != ParsingMode::Strict {
			while c.is_ascii_whitespace() {
				c = reader.read_u8()?;
			}
		}

		let mut timestamp = Timestamp::default();

		let mut content = Vec::with_capacity(Self::MAX_LENGTH);
		content.push(c);

		reader
			.take(Self::MAX_LENGTH as u64 - 1)
			.read_to_end(&mut content)?;

		// It is valid for a timestamp to contain no separators, but this will lower our tolerance
		// for common mistakes. We ignore the "T" separator here because it is **ALWAYS** required.
		let timestamp_contains_separators = content
			.iter()
			.any(|&b| b != b'T' && Self::SEPARATORS.contains(&b));

		let reader = &mut &content[..];

		// We need to verify that the year is exactly 4 bytes long. This doesn't matter for other segments.
		let (year, bytes_read) = Self::segment::<4>(reader, None, parse_mode)?;
		if bytes_read != 4 {
			parse_mode_choice!(
				parse_mode,
				STRICT: err!(BadTimestamp(
					"Encountered an invalid year length (should be 4 digits)"
				)),
				DEFAULT: return Ok(None)
			)
		}

		timestamp.year = year;
		if reader.is_empty() {
			return Ok(Some(timestamp));
		}

		#[allow(clippy::never_loop)]
		loop {
			timestamp.month = read_segment!(Self::segment::<2>(
				reader,
				timestamp_contains_separators.then_some(b'-'),
				parse_mode
			));
			timestamp.day = read_segment!(Self::segment::<2>(
				reader,
				timestamp_contains_separators.then_some(b'-'),
				parse_mode
			));
			timestamp.hour = read_segment!(Self::segment::<2>(reader, Some(b'T'), parse_mode));
			timestamp.minute = read_segment!(Self::segment::<2>(
				reader,
				timestamp_contains_separators.then_some(b':'),
				parse_mode
			));
			timestamp.second = read_segment!(Self::segment::<2>(
				reader,
				timestamp_contains_separators.then_some(b':'),
				parse_mode
			));
			break;
		}

		Ok(Some(timestamp))
	}

	fn segment<const SIZE: usize>(
		content: &mut &[u8],
		sep: Option<u8>,
		parse_mode: ParsingMode,
	) -> Result<(u16, usize)> {
		const STOP_PARSING: (u16, usize) = (0, 0);

		if content.is_empty() {
			return Ok(STOP_PARSING);
		}

		if let Some(sep) = sep {
			let byte = content.read_u8()?;
			if byte != sep {
				if parse_mode == ParsingMode::Strict {
					err!(BadTimestamp("Expected a separator"))
				}
				return Ok(STOP_PARSING);
			}
		}

		if content.len() < SIZE {
			if parse_mode == ParsingMode::Strict {
				err!(BadTimestamp("Timestamp segment is too short"))
			}

			return Ok(STOP_PARSING);
		}

		let mut num = None;
		let mut byte_count = 0;
		for i in content[..SIZE].iter().copied() {
			// Common spec violation: Timestamps may use spaces instead of zeros, so the month of June
			// could be written as " 6" rather than "06" for example.
			if i == b' ' {
				if parse_mode == ParsingMode::Strict {
					err!(BadTimestamp("Timestamp contains spaces"))
				}

				byte_count += 1;
				continue;
			}

			// TODO: This is a spec violation for ID3v2, but not for ISO 8601 in general. Maybe consider
			//       making this a warning and allow it for all parsing modes?
			if !i.is_ascii_digit() {
				// Another spec violation, timestamps in the wild may not use a zero or a space, so
				// we would have to treat "06", "6", and " 6" as valid.
				//
				// The easiest way to check for a missing digit is to see if we're just eating into
				// the next segment's separator.
				if sep.is_some()
					&& Self::SEPARATORS.contains(&i)
					&& parse_mode != ParsingMode::Strict
				{
					break;
				}

				err!(BadTimestamp(
					"Timestamp segment contains non-digit characters"
				))
			}

			num = Some(num.unwrap_or(0) * 10 + u16::from(i - b'0'));
			byte_count += 1;
		}

		let Some(parsed_num) = num else {
			assert_ne!(
				parse_mode,
				ParsingMode::Strict,
				"The timestamp segment is empty, the parser should've failed before this point."
			);

			return Ok(STOP_PARSING);
		};

		*content = &content[byte_count..];

		Ok((parsed_num, byte_count))
	}

	pub(crate) fn verify(&self) -> Result<()> {
		fn verify_field(field: Option<u8>, limit: u8, parent: Option<u8>) -> bool {
			if let Some(field) = field {
				return parent.is_some() && field <= limit;
			}
			return true; // Field does not exist, so it's valid
		}

		if self.year > 9999
			|| !verify_field(self.month, 12, Some(self.year as u8))
			|| !verify_field(self.day, 31, self.month)
			|| !verify_field(self.hour, 23, self.day)
			|| !verify_field(self.minute, 59, self.hour)
			|| !verify_field(self.second, 59, self.minute)
		{
			err!(BadTimestamp(
				"Timestamp contains segment(s) that exceed their limits"
			))
		}

		Ok(())
	}
}

#[cfg(test)]
mod tests {
	use crate::config::ParsingMode;
	use crate::tag::items::timestamp::Timestamp;

	fn expected() -> Timestamp {
		// 2024-06-03T14:08:49
		Timestamp {
			year: 2024,
			month: Some(6),
			day: Some(3),
			hour: Some(14),
			minute: Some(8),
			second: Some(49),
		}
	}

	#[test_log::test]
	fn timestamp_decode() {
		let content = "2024-06-03T14:08:49";
		let parsed_timestamp =
			Timestamp::parse(&mut content.as_bytes(), ParsingMode::Strict).unwrap();

		assert_eq!(parsed_timestamp, Some(expected()));
	}

	#[test_log::test]
	fn timestamp_decode_no_zero() {
		// Zeroes are not used
		let content = "2024-6-3T14:8:49";

		let parsed_timestamp =
			Timestamp::parse(&mut content.as_bytes(), ParsingMode::BestAttempt).unwrap();

		assert_eq!(parsed_timestamp, Some(expected()));
	}

	#[test_log::test]
	fn timestamp_decode_zero_substitution() {
		// Zeros are replaced by spaces
		let content = "2024- 6- 3T14: 8:49";

		let parsed_timestamp =
			Timestamp::parse(&mut content.as_bytes(), ParsingMode::BestAttempt).unwrap();

		assert_eq!(parsed_timestamp, Some(expected()));
	}

	#[test_log::test]
	fn timestamp_encode() {
		let encoded = expected().to_string();
		assert_eq!(encoded, "2024-06-03T14:08:49");
	}

	#[test_log::test]
	fn timestamp_encode_invalid() {
		let mut timestamp = expected();

		// Hour, minute, and second have a dependency on day
		timestamp.day = None;
		assert_eq!(timestamp.to_string().len(), 7);
	}

	fn broken_timestamps() -> [(&'static [u8], Timestamp); 7] {
		[
			(
				b"2024-",
				Timestamp {
					year: 2024,
					..Timestamp::default()
				},
			),
			(
				b"2024-06-",
				Timestamp {
					year: 2024,
					month: Some(6),
					..Timestamp::default()
				},
			),
			(
				b"2024--",
				Timestamp {
					year: 2024,
					..Timestamp::default()
				},
			),
			(
				b"2024-  -",
				Timestamp {
					year: 2024,
					..Timestamp::default()
				},
			),
			(
				b"2024-06-03T",
				Timestamp {
					year: 2024,
					month: Some(6),
					day: Some(3),
					..Timestamp::default()
				},
			),
			(
				b"2024:06",
				Timestamp {
					year: 2024,
					..Timestamp::default()
				},
			),
			(
				b"2024-0-",
				Timestamp {
					year: 2024,
					month: Some(0),
					..Timestamp::default()
				},
			),
		]
	}

	#[test_log::test]
	fn reject_broken_timestamps_strict() {
		for (timestamp, _) in broken_timestamps() {
			let parsed_timestamp = Timestamp::parse(&mut &timestamp[..], ParsingMode::Strict);
			assert!(parsed_timestamp.is_err());
		}
	}

	#[test_log::test]
	fn accept_broken_timestamps_best_attempt() {
		for (timestamp, partial_result) in broken_timestamps() {
			let parsed_timestamp = Timestamp::parse(&mut &timestamp[..], ParsingMode::BestAttempt);
			assert!(parsed_timestamp.is_ok());
			assert_eq!(
				parsed_timestamp.unwrap(),
				Some(partial_result),
				"{}",
				timestamp.escape_ascii()
			);
		}
	}

	#[test_log::test]
	fn timestamp_decode_partial() {
		let partial_timestamps: [(&[u8], Timestamp); 6] = [
			(
				b"2024",
				Timestamp {
					year: 2024,
					..Timestamp::default()
				},
			),
			(
				b"2024-06",
				Timestamp {
					year: 2024,
					month: Some(6),
					..Timestamp::default()
				},
			),
			(
				b"2024-06-03",
				Timestamp {
					year: 2024,
					month: Some(6),
					day: Some(3),
					..Timestamp::default()
				},
			),
			(
				b"2024-06-03T14",
				Timestamp {
					year: 2024,
					month: Some(6),
					day: Some(3),
					hour: Some(14),
					..Timestamp::default()
				},
			),
			(
				b"2024-06-03T14:08",
				Timestamp {
					year: 2024,
					month: Some(6),
					day: Some(3),
					hour: Some(14),
					minute: Some(8),
					..Timestamp::default()
				},
			),
			(b"2024-06-03T14:08:49", expected()),
		];

		for (data, expected) in partial_timestamps {
			let parsed_timestamp = Timestamp::parse(&mut &data[..], ParsingMode::Strict).unwrap();
			assert_eq!(parsed_timestamp, Some(expected));
		}
	}

	#[test_log::test]
	fn empty_timestamp() {
		let empty_timestamp =
			Timestamp::parse(&mut "".as_bytes(), ParsingMode::BestAttempt).unwrap();
		assert!(empty_timestamp.is_none());

		let empty_timestamp_strict = Timestamp::parse(&mut "".as_bytes(), ParsingMode::Strict);
		assert!(empty_timestamp_strict.is_err());
	}

	#[test_log::test]
	fn timestamp_no_separators() {
		let timestamp = "20240603T140849";
		let parsed_timestamp =
			Timestamp::parse(&mut timestamp.as_bytes(), ParsingMode::BestAttempt).unwrap();
		assert_eq!(parsed_timestamp, Some(expected()));
	}

	#[test_log::test]
	fn timestamp_decode_partial_no_separators() {
		let partial_timestamps: [(&[u8], Timestamp); 6] = [
			(
				b"2024",
				Timestamp {
					year: 2024,
					..Timestamp::default()
				},
			),
			(
				b"202406",
				Timestamp {
					year: 2024,
					month: Some(6),
					..Timestamp::default()
				},
			),
			(
				b"20240603",
				Timestamp {
					year: 2024,
					month: Some(6),
					day: Some(3),
					..Timestamp::default()
				},
			),
			(
				b"20240603T14",
				Timestamp {
					year: 2024,
					month: Some(6),
					day: Some(3),
					hour: Some(14),
					..Timestamp::default()
				},
			),
			(
				b"20240603T1408",
				Timestamp {
					year: 2024,
					month: Some(6),
					day: Some(3),
					hour: Some(14),
					minute: Some(8),
					..Timestamp::default()
				},
			),
			(b"20240603T140849", expected()),
		];

		for (data, expected) in partial_timestamps {
			let parsed_timestamp = Timestamp::parse(&mut &data[..], ParsingMode::Strict)
				.unwrap_or_else(|e| panic!("{e}: {}", std::str::from_utf8(data).unwrap()));
			assert_eq!(parsed_timestamp, Some(expected));
		}
	}

	#[test_log::test]
	fn timestamp_no_time_marker() {
		let timestamp = "2024-06-03 14:08:49";

		let parsed_timestamp_strict =
			Timestamp::parse(&mut timestamp.as_bytes(), ParsingMode::Strict);
		assert!(parsed_timestamp_strict.is_err());

		let parsed_timestamp_best_attempt =
			Timestamp::parse(&mut timestamp.as_bytes(), ParsingMode::BestAttempt).unwrap();
		assert_eq!(
			parsed_timestamp_best_attempt,
			Some(Timestamp {
				year: 2024,
				month: Some(6),
				day: Some(3),
				..Timestamp::default()
			})
		);
	}

	#[test_log::test]
	fn timestamp_whitespace() {
		let timestamp = "\t\t\t2024-06-03";

		let parsed_timestamp_strict =
			Timestamp::parse(&mut timestamp.as_bytes(), ParsingMode::Strict);
		assert!(parsed_timestamp_strict.is_err());

		let parsed_timestamp_best_attempt =
			Timestamp::parse(&mut timestamp.as_bytes(), ParsingMode::BestAttempt).unwrap();
		assert_eq!(
			parsed_timestamp_best_attempt,
			Some(Timestamp {
				year: 2024,
				month: Some(6),
				day: Some(3),
				..Timestamp::default()
			})
		);
	}
}