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, Eq, 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, Eq, 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, Eq, 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, Eq, 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, Eq, Copy, Clone, Display)]
202#[serde(try_from = "__HandednessStruct")]
203pub enum Handedness {
204	#[display("L")]
205	Left,
206	#[display("R")]
207	Right,
208	#[display("S")]
209	Switch,
210}
211
212#[derive(Deserialize)]
213#[doc(hidden)]
214struct __HandednessStruct {
215	code: String,
216}
217
218/// Error for handedness parsing
219#[derive(Debug, Error)]
220pub enum HandednessParseError {
221	/// Did not match any of the known handedness variants
222	#[error("Invalid handedness '{0}'")]
223	InvalidHandedness(String),
224}
225
226impl TryFrom<__HandednessStruct> for Handedness {
227	type Error = HandednessParseError;
228
229	fn try_from(value: __HandednessStruct) -> Result<Self, Self::Error> {
230		Ok(match &*value.code {
231			"L" => Self::Left,
232			"R" => Self::Right,
233			"S" => Self::Switch,
234			_ => return Err(HandednessParseError::InvalidHandedness(value.code)),
235		})
236	}
237}
238
239/// Represents a range from one date to another (inclusive on both ends)
240///
241/// # Examples
242/// ```
243/// let range: NaiveDateRange = NaiveDate::from_ymd(1, 1, 2025)..=NaiveDate::from_ymd(12, 31, 2025);
244/// ```
245pub type NaiveDateRange = RangeInclusive<NaiveDate>;
246
247pub(crate) const MLB_API_DATE_FORMAT: &str = "%m/%d/%Y";
248
249/// # Errors
250/// 1. If a string cannot be deserialized
251/// 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.
252pub(crate) fn deserialize_datetime<'de, D: Deserializer<'de>>(deserializer: D) -> Result<NaiveDateTime, D::Error> {
253	let string = String::deserialize(deserializer)?;
254	let fmt = match (string.ends_with('Z'), string.contains('.')) {
255		(false, false) => "%FT%TZ%#z",
256		(false, true) => "%FT%TZ%.3f%#z",
257		(true, false) => "%FT%TZ",
258		(true, true) => "%FT%T%.3fZ",
259	};
260	NaiveDateTime::parse_from_str(&string, fmt).map_err(D::Error::custom)
261}
262
263/// # Errors
264/// 1. If a string cannot be deserialized
265/// 2. If the data does not appear in the format of `/(?:<t parser here>,)*<t parser here>?/g`
266pub(crate) fn deserialize_comma_separated_vec<'de, D: Deserializer<'de>, T: FromStr>(deserializer: D) -> Result<Vec<T>, D::Error>
267where
268	<T as FromStr>::Err: Debug,
269{
270	String::deserialize(deserializer)?
271		.split(", ")
272		.map(|entry| T::from_str(entry))
273		.collect::<Result<Vec<T>, <T as FromStr>::Err>>()
274		.map_err(|e| Error::custom(format!("{e:?}")))
275}
276
277#[derive(Debug, PartialEq, Eq, Copy, Clone, Default)]
278pub enum TeamSide {
279	#[default]
280	Home,
281	Away,
282}
283
284impl Not for TeamSide {
285	type Output = Self;
286
287	fn not(self) -> Self::Output {
288		match self {
289			Self::Home => Self::Away,
290			Self::Away => Self::Home,
291		}
292	}
293}
294
295impl TeamSide {
296	#[must_use]
297	pub const fn is_home(self) -> bool {
298		matches!(self, Self::Home)
299	}
300
301	#[must_use]
302	pub const fn is_away(self) -> bool {
303		matches!(self, Self::Away)
304	}
305}
306
307pub fn deserialize_team_side_from_is_home<'de, D: Deserializer<'de>>(deserializer: D) -> Result<TeamSide, D::Error> {
308	Ok(if bool::deserialize(deserializer)? { TeamSide::Home } else { TeamSide::Away })
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, Eq, 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 const fn as_ref(&self) -> HomeAway<&T> {
344		HomeAway {
345			home: &self.home,
346			away: &self.away,
347		}
348	}
349
350	#[must_use]
351	pub const 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 zip<U>(self, other: HomeAway<U>) -> HomeAway<(T, U)> {
377		HomeAway {
378			home: (self.home, other.home),
379			away: (self.away, other.away),
380		}
381	}
382	
383	#[must_use]
384	pub fn zip_with<U, V, F: FnMut(T, U) -> V>(self, other: HomeAway<U>, mut f: F) -> HomeAway<V> {
385		HomeAway {
386			home: f(self.home, other.home),
387			away: f(self.away, other.away),
388		}
389	}
390
391	#[must_use]
392	pub fn combine<U, F: FnOnce(T, T) -> U>(self, f: F) -> U {
393		f(self.home, self.away)
394	}
395
396	/// Adds home and away values (typically used in stats)
397	#[must_use]
398	pub fn added(self) -> <T as Add>::Output where T: Add {
399		self.home + self.away
400	}
401
402	#[must_use]
403	pub fn both(self, mut f: impl FnMut(T) -> bool) -> bool {
404		f(self.home) && f(self.away)
405	}
406
407	#[must_use]
408	pub fn either(self, mut f: impl FnMut(T) -> bool) -> bool {
409		f(self.home) || f(self.away)
410	}
411}
412
413impl<T> From<(T, T)> for HomeAway<T> {
414	fn from((home, away): (T, T)) -> Self {
415		Self {
416			home,
417			away
418		}
419	}
420}
421
422/// Street address, city, etc.
423///
424/// Pretty much nothing *has* to be supplied so you either get an address, phone number, everything, or just a country.
425#[derive(Debug, Deserialize, PartialEq, Clone, Default)]
426#[serde(rename_all = "camelCase")]
427pub struct Location {
428	pub address_line_1: Option<String>,
429	pub address_line_2: Option<String>,
430	pub address_line_3: Option<String>,
431	pub address_line_4: Option<String>,
432	pub attention: Option<String>,
433	#[serde(alias = "phone")]
434	pub phone_number: Option<String>,
435	pub city: Option<String>,
436	#[serde(alias = "province")]
437	pub state: Option<String>,
438	pub country: Option<String>,
439	#[serde(rename = "stateAbbrev")] pub state_abbreviation: Option<String>,
440	pub postal_code: Option<String>,
441	pub latitude: Option<f64>,
442	pub longitude: Option<f64>,
443	pub azimuth_angle: Option<f64>,
444	pub elevation: Option<u32>,
445}
446
447/// Various information regarding a field.
448#[derive(Debug, Deserialize, PartialEq, Clone)]
449#[serde(rename_all = "camelCase")]
450pub struct FieldInfo {
451	pub capacity: u32,
452	pub turf_type: TurfType,
453	pub roof_type: RoofType,
454	pub left_line: Option<u32>,
455	pub left: Option<u32>,
456	pub left_center: Option<u32>,
457	pub center: Option<u32>,
458	pub right_center: Option<u32>,
459	pub right: Option<u32>,
460	pub right_line: Option<u32>,
461}
462
463/// Different types of turf.
464#[derive(Debug, Deserialize, PartialEq, Eq, Clone, Display)]
465pub enum TurfType {
466	#[serde(rename = "Artificial Turf")]
467	#[display("Artificial Turf")]
468	ArtificialTurf,
469
470	#[serde(rename = "Grass")]
471	#[display("Grass")]
472	Grass,
473}
474
475/// Different types of roof setups.
476#[derive(Debug, Deserialize, PartialEq, Eq, Clone, Display)]
477pub enum RoofType {
478	#[serde(rename = "Retractable")]
479	#[display("Retractable")]
480	Retractable,
481
482	#[serde(rename = "Open")]
483	#[display("Open")]
484	Open,
485
486	#[serde(rename = "Dome")]
487	#[display("Dome")]
488	Dome,
489}
490
491/// Data regarding a timezone, uses [`chrono_tz`].
492#[derive(Debug, Deserialize, PartialEq, Eq, Clone)]
493#[serde(rename_all = "camelCase")]
494pub struct TimeZoneData {
495	#[serde(rename = "id")]
496	pub timezone: chrono_tz::Tz,
497	pub offset: i32,
498	pub offset_at_game_time: i32,
499}
500
501/// More generalized than social media, includes retrosheet, fangraphs, (+ some socials), etc.
502#[derive(Debug, Deserialize, PartialEq, Eq, Clone)]
503pub struct ExternalReference {
504	#[serde(rename = "xrefId")]
505	pub id: String,
506	#[serde(rename = "xrefType")]
507	pub xref_type: String,
508	pub season: Option<SeasonId>,
509}
510
511/// Tracking equipment, Hawk-Eye, `PitchFx`, etc.
512#[derive(Debug, Deserialize, PartialEq, Clone)]
513#[serde(rename_all = "camelCase")]
514pub struct TrackingSystem {
515	pub id: TrackingSystemVendorId,
516	pub description: String,
517	pub pitch_vendor: Option<TrackingSystemVendor>,
518	pub hit_vendor: Option<TrackingSystemVendor>,
519	pub player_vendor: Option<TrackingSystemVendor>,
520	pub skeletal_vendor: Option<TrackingSystemVendor>,
521	pub bat_vendor: Option<TrackingSystemVendor>,
522	pub biomechanics_vendor: Option<TrackingSystemVendor>,
523}
524
525id!(TrackingSystemVendorId { id: u32 });
526
527/// A vendor for specific tracking concepts, such as Hawk-Eye for skeletal data.
528#[derive(Debug, Deserialize, PartialEq, Eq, Clone)]
529pub struct TrackingSystemVendor {
530	pub id: TrackingSystemVendorId,
531	pub description: String,
532	#[serde(rename = "version")]
533	pub details: String,
534}
535
536/// Stat that is either an integer or float.
537///
538/// Used in [`StatLeader`](crate::stats::leaders::StatLeader)
539#[derive(Debug, Copy, Clone)]
540pub enum IntegerOrFloatStat {
541	/// [`integer`](i64) stat, likely counting
542	Integer(i64),
543	/// [`float`](f64) stat, likely rate
544	Float(f64),
545}
546
547impl PartialEq for IntegerOrFloatStat {
548	fn eq(&self, other: &Self) -> bool {
549		match (*self, *other) {
550			(Self::Integer(lhs), Self::Integer(rhs)) => lhs == rhs,
551			(Self::Float(lhs), Self::Float(rhs)) => lhs == rhs,
552
553			#[allow(clippy::cast_precision_loss, reason = "we checked if it's perfectly representable")]
554			#[allow(clippy::cast_possible_truncation, reason = "we checked if it's perfectly representable")]
555			(Self::Integer(int), Self::Float(float)) | (Self::Float(float), Self::Integer(int)) => {
556				// fast way to check if the float is representable perfectly as an integer and if it's within range of `i64`
557				// 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.
558				if float.is_normal() && float.floor() == float && (i64::MIN as f64..-(i64::MIN as f64)).contains(&float) {
559					float as i64 == int
560				} else {
561					false
562				}
563			},
564		}
565	}
566}
567
568impl<'de> Deserialize<'de> for IntegerOrFloatStat {
569	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
570	where
571		D: Deserializer<'de>
572	{
573		struct Visitor;
574
575		impl serde::de::Visitor<'_> for Visitor {
576			type Value = IntegerOrFloatStat;
577
578			fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
579				formatter.write_str("integer, float, or string that can be parsed to either")
580			}
581
582			fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
583			where
584				E: Error,
585			{
586				Ok(IntegerOrFloatStat::Integer(v))
587			}
588
589			fn visit_f64<E>(self, v: f64) -> Result<Self::Value, E>
590			where
591				E: Error,
592			{
593				Ok(IntegerOrFloatStat::Float(v))
594			}
595
596			fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
597			where
598				E: Error,
599			{
600				if v == "-.--" || v == ".---" {
601					Ok(IntegerOrFloatStat::Float(0.0))
602				} else if let Ok(i) = v.parse::<i64>() {
603					Ok(IntegerOrFloatStat::Integer(i))
604				} else if let Ok(f) = v.parse::<f64>() {
605					Ok(IntegerOrFloatStat::Float(f))
606				} else {
607					Err(E::invalid_value(serde::de::Unexpected::Str(v), &self))
608				}
609			}
610		}
611
612		deserializer.deserialize_any(Visitor)
613	}
614}
615
616/// Represents an error parsing an HTTP request
617///
618/// Not a reqwest error, this typically happens from a bad payload like asking for games at a date in BCE.
619#[derive(Debug, Deserialize, Display)]
620#[display("An error occurred parsing the statsapi http request: {message}")]
621pub struct MLBError {
622	pub(crate) message: String,
623}
624
625impl std::error::Error for MLBError {}
626
627/// `rgba({red}, {green}, {blue})` into a type
628#[derive(Debug, Deserialize, PartialEq, Eq, Copy, Clone, Default)]
629#[serde(try_from = "&str")]
630pub struct RGBAColor {
631	pub red: u8,
632	pub green: u8,
633	pub blue: u8,
634	pub alpha: u8,
635}
636
637impl Display for RGBAColor {
638	fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
639		write!(f, "0x{:02x}{:02x}{:02x}{:02x}", self.alpha, self.red, self.green, self.blue)
640	}
641}
642
643/// Spec: `rgba({red}, {green}, {blue})`
644#[derive(Debug, Error)]
645pub enum RGBAColorFromStrError {
646	#[error("Invalid spec")]
647	InvalidFormat,
648	#[error(transparent)]
649	InvalidInt(#[from] ParseIntError),
650	#[error(transparent)]
651	InvalidFloat(#[from] ParseFloatError),
652}
653
654impl<'a> TryFrom<&'a str> for RGBAColor {
655	type Error = <Self as FromStr>::Err;
656
657	fn try_from(value: &'a str) -> Result<Self, Self::Error> {
658		<Self as FromStr>::from_str(value)
659	}
660}
661
662impl FromStr for RGBAColor {
663	type Err = RGBAColorFromStrError;
664
665	/// Spec: `rgba({red}, {green}, {blue})`
666	#[allow(clippy::single_char_pattern, reason = "other patterns are strings, the choice to make that one a char does not denote any special case")]
667	#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss, reason = "intended behaviour with alpha channel")]
668	fn from_str(mut s: &str) -> Result<Self, Self::Err> {
669		s = s.strip_suffix("rgba(").ok_or(Self::Err::InvalidFormat)?;
670		let (red, s) = s.split_once(", ").ok_or(Self::Err::InvalidFormat)?;
671		let red = red.parse::<u8>()?;
672		let (green, s) = s.split_once(", ").ok_or(Self::Err::InvalidFormat)?;
673		let green = green.parse::<u8>()?;
674		let (blue, s) = s.split_once(", ").ok_or(Self::Err::InvalidFormat)?;
675		let blue = blue.parse::<u8>()?;
676		let (alpha, s) = s.split_once(")").ok_or(Self::Err::InvalidFormat)?;
677		let alpha = (alpha.parse::<f32>()? * 255.0).round() as u8;
678		if !s.is_empty() { return Err(Self::Err::InvalidFormat); }
679		Ok(Self {
680			red,
681			green,
682			blue,
683			alpha
684		})
685	}
686}
687
688/// Used in [`HittingHotColdZones`](crate::stats::raw::HittingHotColdZones) and [`PitchingHotColdZones`](crate::stats::raw::PitchingHotColdZones).
689#[derive(Debug, Deserialize, PartialEq, Eq, Copy, Clone, Display, FromStr)]
690#[serde(try_from = "&str")]
691pub enum HeatmapTemperature {
692	Hot,
693	Warm,
694	Lukewarm,
695	Cool,
696	Cold,
697}
698
699impl<'a> TryFrom<&'a str> for HeatmapTemperature {
700	type Error = <Self as FromStr>::Err;
701
702	fn try_from(value: &'a str) -> Result<Self, Self::Error> {
703		<Self as FromStr>::from_str(value)
704	}
705}
706
707pub(crate) fn write_nth(n: usize, f: &mut Formatter<'_>) -> std::fmt::Result {
708	write!(f, "{n}")?;
709	let (tens, ones) = (n / 10, n % 10);
710	let is_teen = (tens % 10) == 1;
711	if is_teen {
712		write!(f, "th")?;
713	} else {
714		write!(f, "{}", match ones {
715			1 => "st",
716			2 => "nd",
717			3 => "rd",
718			_ => "th",
719		})?;
720	}
721	Ok(())
722}
723
724/// # Errors
725/// 1. if format is not `"{hours}:{minutes}:{seconds}"`
726pub fn deserialize_time_delta_from_hms<'de, D: Deserializer<'de>>(deserializer: D) -> Result<TimeDelta, D::Error> {
727	let string = String::deserialize(deserializer)?;
728	let (hour, rest) = string.split_once(':').ok_or_else(|| D::Error::custom("Unable to find `:`"))?;
729	let (minute, second) = rest.split_once(':').ok_or_else(|| D::Error::custom("Unable to find `:`"))?;
730	let hour = hour.parse::<u32>().map_err(D::Error::custom)?;
731	let minute = minute.parse::<u32>().map_err(D::Error::custom)?;
732	let second = second.parse::<u32>().map_err(D::Error::custom)?;
733
734	TimeDelta::new(((hour * 24 + minute) * 60 + second) as _, 0).ok_or_else(|| D::Error::custom("Invalid time quantity, overflow."))
735}
736
737/// AM/PM
738#[derive(Debug, Deserialize, PartialEq, Eq, Copy, Clone, Display, FromStr)]
739#[serde(try_from = "&str")]
740pub enum DayHalf {
741	AM,
742	PM,
743}
744
745impl DayHalf {
746	/// Converts a 12-hour time into it's 24-hour version.
747	#[must_use]
748	pub fn into_24_hour_time(self, mut time: NaiveTime) -> NaiveTime {
749		if (self == Self::PM) ^ (time.hour() == 12) {
750			time += TimeDelta::hours(12);
751		}
752
753		time
754	}
755}
756
757impl<'a> TryFrom<&'a str> for DayHalf {
758	type Error = <Self as FromStr>::Err;
759
760	fn try_from(value: &'a str) -> Result<Self, Self::Error> {
761		<Self as FromStr>::from_str(value)
762	}
763}
764
765#[derive(Debug, Deserialize, PartialEq, Eq, Clone)]
766#[serde(rename_all = "camelCase")]
767pub struct ResourceUsage {
768	pub used: u32,
769	pub remaining: u32,
770}
771
772#[cfg(test)]
773mod tests {
774	use super::*;
775
776	#[test]
777	fn test_ampm() {
778		assert_eq!(NaiveTime::from_hms_opt(0, 0, 0).unwrap(), DayHalf::AM.into_24_hour_time(NaiveTime::from_hms_opt(12, 0, 0).unwrap()));
779		assert_eq!(NaiveTime::from_hms_opt(12, 0, 0).unwrap(), DayHalf::PM.into_24_hour_time(NaiveTime::from_hms_opt(12, 0, 0).unwrap()));
780		assert_eq!(NaiveTime::from_hms_opt(0, 1, 0).unwrap(), DayHalf::AM.into_24_hour_time(NaiveTime::from_hms_opt(12, 1, 0).unwrap()));
781		assert_eq!(NaiveTime::from_hms_opt(12, 1, 0).unwrap(), DayHalf::PM.into_24_hour_time(NaiveTime::from_hms_opt(12, 1, 0).unwrap()));
782		assert_eq!(NaiveTime::from_hms_opt(0, 1, 0).unwrap(), DayHalf::AM.into_24_hour_time(NaiveTime::from_hms_opt(12, 1, 0).unwrap()));
783		assert_eq!(NaiveTime::from_hms_opt(23, 59, 0).unwrap(), DayHalf::PM.into_24_hour_time(NaiveTime::from_hms_opt(11, 59, 0).unwrap()));
784		assert_eq!(NaiveTime::from_hms_opt(1, 1, 0).unwrap(), DayHalf::AM.into_24_hour_time(NaiveTime::from_hms_opt(1, 1, 0).unwrap()));
785	}
786}