Skip to main content

mlb_api/
types.rs

1//! Shared types across multiple requests
2
3#![allow(clippy::redundant_pub_crate, reason = "re-exported as pub lol")]
4
5use chrono::{Datelike, Local, NaiveDate, NaiveDateTime, NaiveTime, TimeDelta, Timelike};
6use derive_more::{Display, FromStr};
7use serde::de::Error;
8use serde::{Deserialize, Deserializer};
9use std::fmt::{Debug, Display, Formatter};
10use std::num::{ParseFloatError, ParseIntError};
11use std::ops::{Add, RangeInclusive};
12use std::str::FromStr;
13use std::ops::Not;
14use thiserror::Error;
15use crate::season::SeasonId;
16
17/// The copyright at the top of every request
18#[derive(Debug, Deserialize, PartialEq, Clone)]
19#[serde(from = "__CopyrightStruct")]
20pub enum Copyright {
21	/// Typical copyright format
22	Typical {
23		/// Year of the copyright, typically the current year.
24		year: u32,
25	},
26	/// Unknown copyright format
27	UnknownSpec(Box<str>),
28}
29
30#[derive(Deserialize)]
31#[doc(hidden)]
32struct __CopyrightStruct(String);
33
34impl From<__CopyrightStruct> for Copyright {
35	fn from(value: __CopyrightStruct) -> Self {
36		let __CopyrightStruct(value) = value;
37		if let Some(value) = value.strip_prefix("Copyright ") && let Some(value) = value.strip_suffix(" MLB Advanced Media, L.P.  Use of any content on this page acknowledges agreement to the terms posted here http://gdx.mlb.com/components/copyright.txt") && let Ok(year) = value.parse::<u32>() {
38			Self::Typical { year }
39		} else {
40			Self::UnknownSpec(value.into_boxed_str())
41		}
42	}
43}
44
45impl Display for Copyright {
46	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
47		match self {
48			Self::Typical { year } => write!(f, "Copyright {year} MLB Advanced Media, L.P.  Use of any content on this page acknowledges agreement to the terms posted here http://gdx.mlb.com/components/copyright.txt"),
49			Self::UnknownSpec(copyright) => write!(f, "{copyright}"),
50		}
51	}
52}
53
54impl Default for Copyright {
55	#[allow(clippy::cast_sign_loss, reason = "jesus is not alive")]
56	fn default() -> Self {
57		Self::Typical { year: Local::now().year() as _ }
58	}
59}
60
61/// Try to deserialize a type using its [`FromStr`] implementation, fallback to `None` if it doesn't work.
62/// # Errors
63/// If a string cannot be parsed from the deserializer.
64pub fn try_from_str<'de, D: Deserializer<'de>, T: FromStr>(deserializer: D) -> Result<Option<T>, D::Error> {
65	Ok(String::deserialize(deserializer)?.parse::<T>().ok())
66}
67
68/// Deserializes a type using its [`FromStr`] implementation.
69///
70/// # Errors
71/// 1. If a string cannot be parsed from the deserializer.
72/// 2. If the type cannot be parsed from the string.
73pub fn from_str<'de, D: Deserializer<'de>, T: FromStr>(deserializer: D) -> Result<T, D::Error>
74where
75	<T as FromStr>::Err: Debug,
76{
77	String::deserialize(deserializer)?.parse::<T>().map_err(|e| Error::custom(format!("{e:?}")))
78}
79
80/// Deserializes a `"Y"` or `"N"` into a `bool`
81///
82/// # Errors
83/// If the type cannot be parsed into a Y or N string
84pub fn from_yes_no<'de, D: Deserializer<'de>>(deserializer: D) -> Result<bool, D::Error> {
85	#[derive(Deserialize)]
86	#[repr(u8)]
87	enum Boolean {
88		#[serde(rename = "Y")]
89		Yes = 1,
90		#[serde(rename = "N")]
91		No = 0,
92	}
93
94	Ok(match Boolean::deserialize(deserializer)? {
95		Boolean::Yes => true,
96		Boolean::No => false,
97	})
98}
99
100/// Measurement of a person's height
101///
102/// Not using [`uom`] because we want feet and inches, not just one of the measurements.
103#[derive(Debug, PartialEq, Copy, Clone)]
104pub enum HeightMeasurement {
105	/// `{a: u8}' {b: u8}"`
106	FeetAndInches { feet: u8, inches: u8 },
107	/// '{x: u16} cm'
108	Centimeters { cm: u16 },
109}
110
111impl FromStr for HeightMeasurement {
112	type Err = HeightMeasurementParseError;
113
114	/// Spec
115	/// 1. `{x: u16} cm`
116	/// 2. `{a: u8}' {b: u8}"`
117	fn from_str(s: &str) -> Result<Self, Self::Err> {
118		if let Some((feet, Some((inches, "")))) = s.split_once("' ").map(|(feet, rest)| (feet, rest.split_once('"'))) {
119			let feet = feet.parse::<u8>()?;
120			let inches = inches.parse::<u8>()?;
121			Ok(Self::FeetAndInches { feet, inches })
122		} else if let Some((cm, "")) = s.split_once("cm") {
123			let cm = cm.parse::<u16>()?;
124			Ok(Self::Centimeters { cm })
125		} else {
126			Err(HeightMeasurementParseError::UnknownSpec(s.to_owned()))
127		}
128	}
129}
130
131impl<'de> Deserialize<'de> for HeightMeasurement {
132	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
133	where
134		D: Deserializer<'de>
135	{
136		String::deserialize(deserializer)?.parse().map_err(D::Error::custom)
137	}
138}
139
140/// Error for [`<HeightMeasurement as FromStr>::from_str`]
141#[derive(Debug, Error)]
142pub enum HeightMeasurementParseError {
143	/// Failed to parse an integer in the height measurement
144	#[error(transparent)]
145	ParseIntError(#[from] ParseIntError),
146	/// Was neither `{a}' {b}"` or `{x} cm`
147	#[error("Unknown height '{0}'")]
148	UnknownSpec(String),
149}
150
151/// General filter for players in requests
152#[derive(Debug, Display, PartialEq, Copy, Clone, Default)]
153pub enum PlayerPool {
154	/// All players (no filter)
155	#[default]
156	#[display("ALL")]
157	All,
158	/// Qualified PAs or IP for a season, can be checked manually via [`QualificationMultipliers`](crate::season::QualificationMultipliers)
159	#[display("QUALIFIED")]
160	Qualified,
161	/// Rookie season
162	#[display("ROOKIES")]
163	Rookies,
164	/// Qualified && Rookie
165	#[display("QUALIFIED_ROOKIES")]
166	QualifiedAndRookies,
167	/// ?
168	#[display("ORGANIZATION")]
169	Organization,
170	/// ?
171	#[display("ORGANIZATION_NO_MLB")]
172	OrganizationNotMlb,
173	/// Active Player (?)
174	#[display("CURRENT")]
175	Current,
176	/// ?
177	#[display("ALL_CURRENT")]
178	AllCurrent,
179	/// Qualified && Current
180	#[display("QUALIFIED_CURRENT")]
181	QualifiedAndCurrent,
182}
183
184/// Gender
185///
186/// Used on [`Ballplayer`](crate::person::Ballplayer)
187#[derive(Debug, Deserialize, PartialEq, Copy, Clone, Default)]
188pub enum Gender {
189	#[serde(rename = "M")]
190	Male,
191	#[serde(rename = "F")]
192	Female,
193	#[default]
194	#[serde(other)]
195	Other,
196}
197
198/// Handedness
199///
200/// Either for batting or pitching
201#[derive(Debug, Deserialize, PartialEq, Copy, Clone)]
202#[serde(try_from = "__HandednessStruct")]
203pub enum Handedness {
204	Left,
205	Right,
206	Switch,
207}
208
209#[derive(Deserialize)]
210#[doc(hidden)]
211struct __HandednessStruct {
212	code: String,
213}
214
215/// Error for handedness parsing
216#[derive(Debug, Error)]
217pub enum HandednessParseError {
218	/// Did not match any of the known handedness variants
219	#[error("Invalid handedness '{0}'")]
220	InvalidHandedness(String),
221}
222
223impl TryFrom<__HandednessStruct> for Handedness {
224	type Error = HandednessParseError;
225
226	fn try_from(value: __HandednessStruct) -> Result<Self, Self::Error> {
227		Ok(match &*value.code {
228			"L" => Self::Left,
229			"R" => Self::Right,
230			"S" => Self::Switch,
231			_ => return Err(HandednessParseError::InvalidHandedness(value.code)),
232		})
233	}
234}
235
236/// Represents a range from one date to another (inclusive on both ends)
237///
238/// # Examples
239/// ```
240/// let range: NaiveDateRange = NaiveDate::from_ymd(1, 1, 2025)..=NaiveDate::from_ymd(12, 31, 2025);
241/// ```
242pub type NaiveDateRange = RangeInclusive<NaiveDate>;
243
244pub(crate) const MLB_API_DATE_FORMAT: &str = "%m/%d/%Y";
245
246/// # Errors
247/// 1. If a string cannot be deserialized
248/// 2. If the data does not appear in the format `%Y-%m-%dT%H:%M:%SZ(%#z)?`. Why the MLB removes the +00:00 or -00:00 sometimes? I have no clue.
249pub(crate) fn deserialize_datetime<'de, D: Deserializer<'de>>(deserializer: D) -> Result<NaiveDateTime, D::Error> {
250	let string = String::deserialize(deserializer)?;
251	let fmt = match (string.ends_with('Z'), string.contains('.')) {
252		(false, false) => "%FT%TZ%#z",
253		(false, true) => "%FT%TZ%.3f%#z",
254		(true, false) => "%FT%TZ",
255		(true, true) => "%FT%T%.3fZ",
256	};
257	NaiveDateTime::parse_from_str(&string, fmt).map_err(D::Error::custom)
258}
259
260/// # Errors
261/// 1. If a string cannot be deserialized
262/// 2. If the data does not appear in the format of `/(?:<t parser here>,)*<t parser here>?/g`
263pub(crate) fn deserialize_comma_separated_vec<'de, D: Deserializer<'de>, T: FromStr>(deserializer: D) -> Result<Vec<T>, D::Error>
264where
265	<T as FromStr>::Err: Debug,
266{
267	String::deserialize(deserializer)?
268		.split(", ")
269		.map(|entry| T::from_str(entry))
270		.collect::<Result<Vec<T>, <T as FromStr>::Err>>()
271		.map_err(|e| Error::custom(format!("{e:?}")))
272}
273
274#[derive(Debug, PartialEq, Eq, Copy, Clone, Default)]
275pub enum TeamSide {
276	#[default]
277	Home,
278	Away,
279}
280
281impl Not for TeamSide {
282	type Output = Self;
283
284	fn not(self) -> Self::Output {
285		match self {
286			Self::Home => Self::Away,
287			Self::Away => Self::Home,
288		}
289	}
290}
291
292impl TeamSide {
293	#[must_use]
294	pub const fn is_home(self) -> bool {
295		matches!(self, Self::Home)
296	}
297
298	#[must_use]
299	pub const fn is_away(self) -> bool {
300		matches!(self, Self::Away)
301	}
302}
303
304pub fn deserialize_team_side_from_is_home<'de, D: Deserializer<'de>>(deserializer: D) -> Result<TeamSide, D::Error> {
305	Ok(match bool::deserialize(deserializer)? {
306		true => TeamSide::Home,
307		false => TeamSide::Away,
308	})
309}
310
311/// General type that represents two fields where one is home and one is away
312///
313/// Examples:
314/// ```json
315/// {
316///     "home": { "name": "New York Yankees", "id": ... },
317///     "away": { "name": "Boston Red Sox", "id": ... }
318/// }
319/// ```
320#[derive(Debug, Deserialize, PartialEq, Copy, Clone, Default)]
321pub struct HomeAway<T> {
322	pub home: T,
323	pub away: T,
324}
325
326impl<T> HomeAway<T> {
327	/// Constructs a new [`HomeAwaySplit`]
328	#[must_use]
329	pub const fn new(home: T, away: T) -> Self {
330		Self { home, away }
331	}
332
333	/// Choose the value depending on the [`TeamSide`]
334	#[must_use]
335	pub fn choose(self, side: TeamSide) -> T {
336		match side {
337			TeamSide::Home => self.home,
338			TeamSide::Away => self.away,
339		}
340	}
341
342	#[must_use]
343	pub fn as_ref(&self) -> HomeAway<&T> {
344		HomeAway {
345			home: &self.home,
346			away: &self.away,
347		}
348	}
349
350	#[must_use]
351	pub fn as_mut(&mut self) -> HomeAway<&mut T> {
352		HomeAway {
353			home: &mut self.home,
354			away: &mut self.away,
355		}
356	}
357
358	#[must_use]
359	pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> HomeAway<U> {
360		HomeAway {
361			home: f(self.home),
362			away: f(self.away),
363		}
364	}
365
366	/// Switches the home and away sides
367	#[must_use]
368	pub fn swap(self) -> Self {
369		Self {
370			home: self.away,
371			away: self.home,
372		}
373	}
374
375	#[must_use]
376	pub fn combine<U, V, F: FnMut(T, U) -> V>(self, other: HomeAway<U>, mut f: F) -> HomeAway<V> {
377		HomeAway {
378			home: f(self.home, other.home),
379			away: f(self.away, other.away),
380		}
381	}
382
383	/// Adds home and away values (typically used in stats)
384	#[must_use]
385	pub fn added(self) -> <T as Add>::Output where T: Add {
386		self.home + self.away
387	}
388}
389
390impl<T> From<(T, T)> for HomeAway<T> {
391	fn from((home, away): (T, T)) -> Self {
392		Self {
393			home,
394			away
395		}
396	}
397}
398
399/// Street address, city, etc.
400///
401/// Pretty much nothing *has* to be supplied so you either get an address, phone number, everything, or just a country.
402#[derive(Debug, Deserialize, PartialEq, Clone, Default)]
403#[serde(rename_all = "camelCase")]
404pub struct Location {
405	pub address_line_1: Option<String>,
406	pub address_line_2: Option<String>,
407	pub address_line_3: Option<String>,
408	pub address_line_4: Option<String>,
409	pub attention: Option<String>,
410	#[serde(alias = "phone")]
411	pub phone_number: Option<String>,
412	pub city: Option<String>,
413	#[serde(alias = "province")]
414	pub state: Option<String>,
415	pub country: Option<String>,
416	#[serde(rename = "stateAbbrev")] pub state_abbreviation: Option<String>,
417	pub postal_code: Option<String>,
418	pub latitude: Option<f64>,
419	pub longitude: Option<f64>,
420	pub azimuth_angle: Option<f64>,
421	pub elevation: Option<u32>,
422}
423
424/// Various information regarding a field.
425#[derive(Debug, Deserialize, PartialEq, Clone)]
426#[serde(rename_all = "camelCase")]
427pub struct FieldInfo {
428	pub capacity: u32,
429	pub turf_type: TurfType,
430	pub roof_type: RoofType,
431	pub left_line: Option<u32>,
432	pub left: Option<u32>,
433	pub left_center: Option<u32>,
434	pub center: Option<u32>,
435	pub right_center: Option<u32>,
436	pub right: Option<u32>,
437	pub right_line: Option<u32>,
438}
439
440/// Different types of turf.
441#[derive(Debug, Deserialize, PartialEq, Clone, Display)]
442pub enum TurfType {
443	#[serde(rename = "Artificial Turf")]
444	#[display("Artificial Turf")]
445	ArtificialTurf,
446
447	#[serde(rename = "Grass")]
448	#[display("Grass")]
449	Grass,
450}
451
452/// Different types of roof setups.
453#[derive(Debug, Deserialize, PartialEq, Clone, Display)]
454pub enum RoofType {
455	#[serde(rename = "Retractable")]
456	#[display("Retractable")]
457	Retractable,
458
459	#[serde(rename = "Open")]
460	#[display("Open")]
461	Open,
462
463	#[serde(rename = "Dome")]
464	#[display("Dome")]
465	Dome,
466}
467
468/// Data regarding a timezone, uses [`chrono_tz`].
469#[derive(Debug, Deserialize, PartialEq, Clone)]
470#[serde(rename_all = "camelCase")]
471pub struct TimeZoneData {
472	#[serde(rename = "id")]
473	pub timezone: chrono_tz::Tz,
474	pub offset: i32,
475	pub offset_at_game_time: i32,
476}
477
478/// More generalized than social media, includes retrosheet, fangraphs, (+ some socials), etc.
479#[derive(Debug, Deserialize, PartialEq, Clone)]
480pub struct ExternalReference {
481	#[serde(rename = "xrefId")]
482	pub id: String,
483	#[serde(rename = "xrefType")]
484	pub xref_type: String,
485	pub season: Option<SeasonId>,
486}
487
488/// Tracking equipment, Hawk-Eye, PitchFx, etc.
489#[derive(Debug, Deserialize, PartialEq, Clone)]
490#[serde(rename_all = "camelCase")]
491pub struct TrackingSystem {
492	pub id: TrackingSystemVendorId,
493	pub description: String,
494	pub pitch_vendor: Option<TrackingSystemVendor>,
495	pub hit_vendor: Option<TrackingSystemVendor>,
496	pub player_vendor: Option<TrackingSystemVendor>,
497	pub skeletal_vendor: Option<TrackingSystemVendor>,
498	pub bat_vendor: Option<TrackingSystemVendor>,
499	pub biomechanics_vendor: Option<TrackingSystemVendor>,
500}
501
502id!(TrackingSystemVendorId { id: u32 });
503
504/// A vendor for specific tracking concepts, such as Hawk-Eye for skeletal data.
505#[derive(Debug, Deserialize, PartialEq, Clone)]
506pub struct TrackingSystemVendor {
507	pub id: TrackingSystemVendorId,
508	pub description: String,
509	#[serde(rename = "version")]
510	pub details: String,
511}
512
513/// Stat that is either an integer or float.
514///
515/// Used in [`StatLeader`](crate::stats::leaders::StatLeader)
516#[derive(Debug, Copy, Clone)]
517pub enum IntegerOrFloatStat {
518	/// [`integer`](i64) stat, likely counting
519	Integer(i64),
520	/// [`float`](f64) stat, likely rate
521	Float(f64),
522}
523
524impl PartialEq for IntegerOrFloatStat {
525	fn eq(&self, other: &Self) -> bool {
526		match (*self, *other) {
527			(Self::Integer(lhs), Self::Integer(rhs)) => lhs == rhs,
528			(Self::Float(lhs), Self::Float(rhs)) => lhs == rhs,
529
530			#[allow(clippy::cast_precision_loss, reason = "we checked if it's perfectly representable")]
531			#[allow(clippy::cast_possible_truncation, reason = "we checked if it's perfectly representable")]
532			(Self::Integer(int), Self::Float(float)) | (Self::Float(float), Self::Integer(int)) => {
533				// fast way to check if the float is representable perfectly as an integer and if it's within range of `i64`
534				// we inline the f64 casts of i64::MIN and i64::MAX, and change the upper bound to be < as i64::MAX is not perfectly representable.
535				if float.is_normal() && float.floor() == float && (i64::MIN as f64..-(i64::MIN as f64)).contains(&float) {
536					float as i64 == int
537				} else {
538					false
539				}
540			},
541		}
542	}
543}
544
545impl<'de> Deserialize<'de> for IntegerOrFloatStat {
546	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
547	where
548		D: Deserializer<'de>
549	{
550		struct Visitor;
551
552		impl serde::de::Visitor<'_> for Visitor {
553			type Value = IntegerOrFloatStat;
554
555			fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
556				formatter.write_str("integer, float, or string that can be parsed to either")
557			}
558
559			fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
560			where
561				E: Error,
562			{
563				Ok(IntegerOrFloatStat::Integer(v))
564			}
565
566			fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
567			where
568				E: Error,
569			{
570				Ok(IntegerOrFloatStat::Float(v))
571			}
572
573			fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
574			where
575				E: Error,
576			{
577				if v == "-.--" || v == ".---" {
578					Ok(IntegerOrFloatStat::Float(0.0))
579				} else if let Ok(i) = v.parse::<i64>() {
580					Ok(IntegerOrFloatStat::Integer(i))
581				} else if let Ok(f) = v.parse::<f64>() {
582					Ok(IntegerOrFloatStat::Float(f))
583				} else {
584					Err(E::invalid_value(serde::de::Unexpected::Str(v), &self))
585				}
586			}
587		}
588
589		deserializer.deserialize_any(Visitor)
590	}
591}
592
593/// Represents an error parsing an HTTP request
594///
595/// Not a reqwest error, this typically happens from a bad payload like asking for games at a date in BCE.
596#[derive(Debug, Deserialize, Display)]
597#[display("An error occurred parsing the statsapi http request: {message}")]
598pub struct MLBError {
599	pub(crate) message: String,
600}
601
602impl std::error::Error for MLBError {}
603
604/// `rgba({red}, {green}, {blue})` into a type
605#[derive(Debug, Deserialize, PartialEq, Copy, Clone, Default)]
606#[serde(try_from = "&str")]
607pub struct RGBAColor {
608	pub red: u8,
609	pub green: u8,
610	pub blue: u8,
611	pub alpha: u8,
612}
613
614impl Display for RGBAColor {
615	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
616		write!(f, "0x{:02x}{:02x}{:02x}{:02x}", self.alpha, self.red, self.green, self.blue)
617	}
618}
619
620/// Spec: `rgba({red}, {green}, {blue})`
621#[derive(Debug, Error)]
622pub enum RGBAColorFromStrError {
623	#[error("Invalid spec")]
624	InvalidFormat,
625	#[error(transparent)]
626	InvalidInt(#[from] ParseIntError),
627	#[error(transparent)]
628	InvalidFloat(#[from] ParseFloatError),
629}
630
631impl<'a> TryFrom<&'a str> for RGBAColor {
632	type Error = <Self as FromStr>::Err;
633
634	fn try_from(value: &'a str) -> Result<Self, Self::Error> {
635		<Self as FromStr>::from_str(value)
636	}
637}
638
639impl FromStr for RGBAColor {
640	type Err = RGBAColorFromStrError;
641
642	/// Spec: `rgba({red}, {green}, {blue})`
643	#[allow(clippy::single_char_pattern, reason = "other patterns are strings, the choice to make that one a char does not denote any special case")]
644	#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "intended behaviour with alpha channel")]
645	fn from_str(mut s: &str) -> Result<Self, Self::Err> {
646		s = s.strip_suffix("rgba(").ok_or(Self::Err::InvalidFormat)?;
647		let (red, s) = s.split_once(", ").ok_or(Self::Err::InvalidFormat)?;
648		let red = red.parse::<u8>()?;
649		let (green, s) = s.split_once(", ").ok_or(Self::Err::InvalidFormat)?;
650		let green = green.parse::<u8>()?;
651		let (blue, s) = s.split_once(", ").ok_or(Self::Err::InvalidFormat)?;
652		let blue = blue.parse::<u8>()?;
653		let (alpha, s) = s.split_once(")").ok_or(Self::Err::InvalidFormat)?;
654		let alpha = (alpha.parse::<f32>()? * 255.0).round() as u8;
655		if !s.is_empty() { return Err(Self::Err::InvalidFormat); }
656		Ok(Self {
657			red,
658			green,
659			blue,
660			alpha
661		})
662	}
663}
664
665/// Used in [`HittingHotColdZones`](crate::stats::raw::HittingHotColdZones) and [`PitchingHotColdZones`](crate::stats::raw::PitchingHotColdZones).
666#[derive(Debug, Deserialize, PartialEq, Copy, Clone, Display, FromStr)]
667#[serde(try_from = "&str")]
668pub enum HeatmapTemperature {
669	Hot,
670	Warm,
671	Lukewarm,
672	Cool,
673	Cold,
674}
675
676impl<'a> TryFrom<&'a str> for HeatmapTemperature {
677	type Error = <Self as FromStr>::Err;
678
679	fn try_from(value: &'a str) -> Result<Self, Self::Error> {
680		<Self as FromStr>::from_str(value)
681	}
682}
683
684pub(crate) fn write_nth(n: usize, f: &mut Formatter<'_>) -> std::fmt::Result {
685	write!(f, "{n}")?;
686	let (tens, ones) = (n / 10, n % 10);
687	let is_teen = (tens % 10) == 1;
688	if is_teen {
689		write!(f, "th")?;
690	} else {
691		write!(f, "{}", match ones {
692			1 => "st",
693			2 => "nd",
694			3 => "rd",
695			_ => "th",
696		})?;
697	}
698	Ok(())
699}
700
701/// # Errors
702/// 1. if format is not `"{hours}:{minutes}:{seconds}"`
703pub fn deserialize_time_delta_from_hms<'de, D: Deserializer<'de>>(deserializer: D) -> Result<TimeDelta, D::Error> {
704	let string = String::deserialize(deserializer)?;
705	let (hour, rest) = string.split_once(':').ok_or_else(|| D::Error::custom("Unable to find `:`"))?;
706	let (minute, second) = rest.split_once(':').ok_or_else(|| D::Error::custom("Unable to find `:`"))?;
707	let hour = hour.parse::<u32>().map_err(D::Error::custom)?;
708	let minute = minute.parse::<u32>().map_err(D::Error::custom)?;
709	let second = second.parse::<u32>().map_err(D::Error::custom)?;
710
711	TimeDelta::new(((hour * 24 + minute) * 60 + second) as _, 0).ok_or_else(|| D::Error::custom("Invalid time quantity, overflow."))
712}
713
714/// AM/PM
715#[derive(Debug, Deserialize, PartialEq, Copy, Clone, Display, FromStr)]
716#[serde(try_from = "&str")]
717pub enum DayHalf {
718	AM,
719	PM,
720}
721
722impl DayHalf {
723	/// Converts a 12-hour time into it's 24-hour version.
724	#[must_use]
725	pub fn into_24_hour_time(self, mut time: NaiveTime) -> NaiveTime {
726		if (self == Self::PM) ^ (time.hour() == 12) {
727			time += TimeDelta::hours(12);
728		}
729
730		time
731	}
732}
733
734impl<'a> TryFrom<&'a str> for DayHalf {
735	type Error = <Self as FromStr>::Err;
736
737	fn try_from(value: &'a str) -> Result<Self, Self::Error> {
738		<Self as FromStr>::from_str(value)
739	}
740}
741
742#[derive(Debug, Deserialize, PartialEq, Clone)]
743#[serde(rename_all = "camelCase")]
744pub struct ResourceUsage {
745	pub used: u32,
746	pub remaining: u32,
747}
748
749#[cfg(test)]
750mod tests {
751	use super::*;
752
753	#[test]
754	fn test_ampm() {
755		assert_eq!(NaiveTime::from_hms_opt(0, 0, 0).unwrap(), DayHalf::AM.into_24_hour_time(NaiveTime::from_hms_opt(12, 0, 0).unwrap()));
756		assert_eq!(NaiveTime::from_hms_opt(12, 0, 0).unwrap(), DayHalf::PM.into_24_hour_time(NaiveTime::from_hms_opt(12, 0, 0).unwrap()));
757		assert_eq!(NaiveTime::from_hms_opt(0, 1, 0).unwrap(), DayHalf::AM.into_24_hour_time(NaiveTime::from_hms_opt(12, 1, 0).unwrap()));
758		assert_eq!(NaiveTime::from_hms_opt(12, 1, 0).unwrap(), DayHalf::PM.into_24_hour_time(NaiveTime::from_hms_opt(12, 1, 0).unwrap()));
759		assert_eq!(NaiveTime::from_hms_opt(0, 1, 0).unwrap(), DayHalf::AM.into_24_hour_time(NaiveTime::from_hms_opt(12, 1, 0).unwrap()));
760		assert_eq!(NaiveTime::from_hms_opt(23, 59, 0).unwrap(), DayHalf::PM.into_24_hour_time(NaiveTime::from_hms_opt(11, 59, 0).unwrap()));
761		assert_eq!(NaiveTime::from_hms_opt(1, 1, 0).unwrap(), DayHalf::AM.into_24_hour_time(NaiveTime::from_hms_opt(1, 1, 0).unwrap()));
762	}
763}