Skip to main content

vatsim_api/
types.rs

1//! Core types shared across VATSIM APIs.
2//!
3//! This module contains enums and newtypes that appear in multiple VATSIM
4//! endpoints: [`CertificateId`], [`Facility`], [`ControllerRating`],
5//! [`PilotRating`], and [`MilitaryRating`]. Endpoint-specific structs live in
6//! the [`datafeed`] and [`slurper`] submodules.
7
8pub mod connect;
9pub mod datafeed;
10pub mod slurper;
11
12#[cfg(feature = "serde")]
13use serde::{Deserialize, Deserializer, Serialize, Serializer};
14
15/// A VATSIM user's certificate ID (CID), a unique numeric identifier.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
17#[repr(transparent)]
18#[cfg_attr(feature = "serde", derive(Serialize))]
19#[cfg_attr(feature = "serde", serde(transparent))]
20pub struct CertificateId(u32);
21
22/// ATC facility type as used in the VATSIM data feed and callsign suffixes.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
24pub enum Facility {
25    /// Observer, `OBS`, data feed ID 0. Also the fallback for unrecognized
26    /// callsign suffixes.
27    #[default]
28    Observer,
29    /// Ramp control, `RMP`. Has no data feed ID.
30    Ramp,
31    /// Clearance delivery, `DEL`, data feed ID 2.
32    ClearanceDelivery,
33    /// Ground, `GND`, data feed ID 3.
34    Ground,
35    /// Tower, `TWR`, data feed ID 4.
36    Tower,
37    /// Approach, `APP`, data feed ID 5. The data feed does not distinguish
38    /// approach from departure, so an ID of 5 always maps here.
39    Approach,
40    /// Departure, `DEP`. Has no data feed ID; see [`Facility::Approach`].
41    Departure,
42    /// Enroute (area control center), `CTR`, data feed ID 6.
43    Enroute,
44    /// Flight service station, `FSS`, data feed ID 1.
45    FlightServiceStation,
46    /// Radio, `RDO`. Has no data feed ID.
47    Radio,
48    /// Traffic flow or traffic management, `FMP`. Has no data feed ID.
49    TrafficFlow,
50}
51
52/// VATSIM ATC controller rating, from inactive/suspended through administrator.
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
54pub enum ControllerRating {
55    /// Inactive, `INAC`, ID -1.
56    #[default]
57    Inactive,
58    /// Suspended, `SUS`, ID 0.
59    Suspended,
60    /// Observer, `OBS`, ID 1.
61    Observer,
62    /// Tower trainee, `S1`, ID 2.
63    TowerTrainee,
64    /// Tower controller, `S2`, ID 3.
65    TowerController,
66    /// Senior student, `S3`, ID 4.
67    SeniorStudent,
68    /// Enroute controller, `C1`, ID 5.
69    EnrouteController,
70    /// Controller 2, `C2`, ID 6.
71    #[deprecated(note = "not actively in use on VATSIM")]
72    Controller2,
73    /// Senior controller, `C3`, ID 7.
74    SeniorController,
75    /// Instructor, `I1`, ID 8.
76    Instructor,
77    /// Instructor 2, `I2`, ID 9.
78    #[deprecated(note = "not actively in use on VATSIM")]
79    Instructor2,
80    /// Senior instructor, `I3`, ID 10.
81    SeniorInstructor,
82    /// Supervisor, `SUP`, ID 11.
83    Supervisor,
84    /// Administrator, `ADM`, ID 12.
85    Administrator,
86}
87
88/// VATSIM pilot rating, from basic member through flight examiner.
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
90pub enum PilotRating {
91    /// Basic member, `NEW`, ID 0.
92    #[default]
93    BasicMember,
94    /// Private pilot license, `PPL`, ID 1.
95    PrivatePilotLicense,
96    /// Instrument rating, `IR`, ID 3.
97    InstrumentRating,
98    /// Commercial multi-engine license, `CMEL`, ID 7.
99    CommercialMultiEngineLicense,
100    /// Airline transport pilot license, `ATPL`, ID 15.
101    AirlineTransportPilotLicense,
102    /// Flight instructor, `FI`, ID 31.
103    FlightInstructor,
104    /// Flight examiner, `FE`, ID 63.
105    FlightExaminer,
106}
107
108/// VATSIM military pilot rating.
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
110pub enum MilitaryRating {
111    /// No military rating, `M0`, ID 0.
112    #[default]
113    NoMilitaryRating,
114    /// Military pilot license, `M1`, ID 1.
115    MilitaryPilotLicense,
116    /// Military instrument rating, `M2`, ID 3.
117    MilitaryInstrumentRating,
118    /// Military multi-engine rating, `M3`, ID 7.
119    MilitaryMultiEngineRating,
120    /// Military mission ready pilot, `M4`, ID 15.
121    MilitaryMissionReadyPilot,
122}
123
124impl CertificateId {
125    /// Creates a new [`CertificateId`] from a raw numeric ID.
126    #[must_use]
127    pub const fn new(id: u32) -> Self {
128        Self(id)
129    }
130
131    /// Returns the underlying numeric ID.
132    #[must_use]
133    pub const fn get(self) -> u32 {
134        self.0
135    }
136}
137
138impl std::fmt::Display for CertificateId {
139    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140        self.0.fmt(f)
141    }
142}
143
144impl std::str::FromStr for CertificateId {
145    type Err = std::num::ParseIntError;
146    fn from_str(s: &str) -> Result<Self, Self::Err> {
147        Ok(Self(s.parse()?))
148    }
149}
150
151impl From<u32> for CertificateId {
152    fn from(id: u32) -> Self {
153        Self(id)
154    }
155}
156
157impl From<CertificateId> for u32 {
158    fn from(id: CertificateId) -> Self {
159        id.0
160    }
161}
162
163#[cfg(feature = "serde")]
164impl<'de> Deserialize<'de> for CertificateId {
165    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
166    where
167        D: Deserializer<'de>,
168    {
169        #[derive(Clone, Copy)]
170        struct CertificateIdVisitor;
171        impl serde::de::Visitor<'_> for CertificateIdVisitor {
172            type Value = CertificateId;
173            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174                f.write_str("a CID as a string or integer")
175            }
176            fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<CertificateId, E> {
177                u32::try_from(v)
178                    .map(CertificateId::new)
179                    .map_err(|_| E::invalid_value(serde::de::Unexpected::Signed(v), &self))
180            }
181            fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<CertificateId, E> {
182                u32::try_from(v)
183                    .map(CertificateId::new)
184                    .map_err(|_| E::invalid_value(serde::de::Unexpected::Unsigned(v), &self))
185            }
186            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<CertificateId, E> {
187                v.parse().map_err(E::custom)
188            }
189        }
190        deserializer.deserialize_any(CertificateIdVisitor)
191    }
192}
193
194impl Facility {
195    /// All active facility variants (excludes no deprecated variants).
196    pub const ALL: &'static [Self] = &[
197        Self::Observer,
198        Self::Ramp,
199        Self::ClearanceDelivery,
200        Self::Ground,
201        Self::Tower,
202        Self::Approach,
203        Self::Departure,
204        Self::Enroute,
205        Self::FlightServiceStation,
206        Self::Radio,
207        Self::TrafficFlow,
208    ];
209
210    /// Returns the numeric ID the VATSIM data feed uses for this facility.
211    ///
212    /// The data feed has IDs for only seven facility types, so the four
213    /// variants without one map to their closest equivalent:
214    /// [`Departure`](Self::Departure) to [`Approach`](Self::Approach),
215    /// [`Ramp`](Self::Ramp) to [`Ground`](Self::Ground),
216    /// [`Radio`](Self::Radio) to
217    /// [`FlightServiceStation`](Self::FlightServiceStation), and
218    /// [`TrafficFlow`](Self::TrafficFlow) to [`Observer`](Self::Observer).
219    /// Those four therefore do not survive a round trip through an ID.
220    ///
221    /// [`as_str`](Self::as_str) is lossless and is what this crate's
222    /// [`Serialize`] implementation uses.
223    #[must_use]
224    pub const fn as_id(self) -> i8 {
225        match self {
226            Facility::Observer | Facility::TrafficFlow => 0,
227            Facility::FlightServiceStation | Facility::Radio => 1,
228            Facility::ClearanceDelivery => 2,
229            Facility::Ground | Facility::Ramp => 3,
230            Facility::Tower => 4,
231            Facility::Approach | Facility::Departure => 5,
232            Facility::Enroute => 6,
233        }
234    }
235
236    /// Returns the short string code for this facility (e.g. `"TWR"`, `"APP"`).
237    #[must_use]
238    pub const fn as_str(self) -> &'static str {
239        match self {
240            Facility::Observer => "OBS",
241            Facility::Ramp => "RMP",
242            Facility::ClearanceDelivery => "DEL",
243            Facility::Ground => "GND",
244            Facility::Tower => "TWR",
245            Facility::Approach => "APP",
246            Facility::Departure => "DEP",
247            Facility::Enroute => "CTR",
248            Facility::FlightServiceStation => "FSS",
249            Facility::Radio => "RDO",
250            Facility::TrafficFlow => "FMP",
251        }
252    }
253
254    /// Guesses the [`Facility`] from a callsign suffix (e.g. `"LOWW_TWR"` -> [`Facility::Tower`]).
255    ///
256    /// Returns [`Facility::Observer`] if the suffix is not recognized.
257    #[must_use]
258    pub fn from_callsign(callsign: impl AsRef<str>) -> Self {
259        let facility_suffix = callsign.as_ref().split('_').next_back().unwrap_or_default();
260        Facility::try_from(facility_suffix).unwrap_or_default()
261    }
262}
263
264impl std::fmt::Display for Facility {
265    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
266        f.write_str(self.as_str())
267    }
268}
269
270impl std::str::FromStr for Facility {
271    type Err = crate::error::ParseError;
272    fn from_str(s: &str) -> Result<Self, Self::Err> {
273        let s = s.to_ascii_uppercase();
274        match s.as_str() {
275            "OBS" | "OBSERVER" => Ok(Facility::Observer),
276            "RMP" | "RAMP" => Ok(Facility::Ramp),
277            "DEL" | "DELIVERY" | "CLEARANCE DELIVERY" => Ok(Facility::ClearanceDelivery),
278            "GND" | "GROUND" => Ok(Facility::Ground),
279            "TWR" | "TOWER" => Ok(Facility::Tower),
280            "APP" | "APPROACH" | "APPROACH/DEPARTURE" => Ok(Facility::Approach),
281            "DEP" | "DEPARTURE" => Ok(Facility::Departure),
282            "CTR" | "CENTER" | "CENTRE" | "ENROUTE" => Ok(Facility::Enroute),
283            "FSS" | "FLIGHTSERVICESTATION" | "FLIGHT SERVICE STATION" => {
284                Ok(Facility::FlightServiceStation)
285            }
286            "RDO" | "RADIO" => Ok(Facility::Radio),
287            "TMU"
288            | "TRAFFICMANAGEMENTUNIT"
289            | "TRAFFIC MANAGEMENT UNIT"
290            | "FMP"
291            | "FLOWMANAGEMENTPOSITION"
292            | "FLOW MANAGEMENT POSITION"
293            | "TRAFFICFLOW"
294            | "TRAFFIC FLOW" => Ok(Facility::TrafficFlow),
295            other => Err(Self::Err::UnknownValue {
296                kind: "facility",
297                value: other.to_string(),
298            }),
299        }
300    }
301}
302
303impl TryFrom<&str> for Facility {
304    type Error = crate::error::ParseError;
305    fn try_from(value: &str) -> Result<Self, Self::Error> {
306        value.parse()
307    }
308}
309
310impl TryFrom<String> for Facility {
311    type Error = crate::error::ParseError;
312    fn try_from(value: String) -> Result<Self, Self::Error> {
313        value.as_str().parse()
314    }
315}
316
317impl TryFrom<i8> for Facility {
318    type Error = crate::error::ParseError;
319    fn try_from(value: i8) -> Result<Self, Self::Error> {
320        match value {
321            0 => Ok(Facility::Observer),
322            1 => Ok(Facility::FlightServiceStation),
323            2 => Ok(Facility::ClearanceDelivery),
324            3 => Ok(Facility::Ground),
325            4 => Ok(Facility::Tower),
326            5 => Ok(Facility::Approach),
327            6 => Ok(Facility::Enroute),
328            other => Err(Self::Error::UnknownValue {
329                kind: "facility",
330                value: other.to_string(),
331            }),
332        }
333    }
334}
335
336impl TryFrom<datafeed::FacilityInfo> for Facility {
337    type Error = crate::error::ParseError;
338    fn try_from(value: datafeed::FacilityInfo) -> Result<Self, Self::Error> {
339        value.id.try_into()
340    }
341}
342
343#[cfg(feature = "serde")]
344impl Serialize for Facility {
345    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
346    where
347        S: Serializer,
348    {
349        serializer.serialize_str(self.as_str())
350    }
351}
352
353#[cfg(feature = "serde")]
354impl<'de> Deserialize<'de> for Facility {
355    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
356    where
357        D: Deserializer<'de>,
358    {
359        #[derive(Clone, Copy)]
360        struct FacilityVisitor;
361        impl serde::de::Visitor<'_> for FacilityVisitor {
362            type Value = Facility;
363            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
364                f.write_str("a facility name string or integer ID")
365            }
366            fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<Facility, E> {
367                i8::try_from(v)
368                    .map_err(|_| E::invalid_value(serde::de::Unexpected::Signed(v), &self))
369                    .and_then(|id| Facility::try_from(id).map_err(|e| E::custom(e)))
370            }
371            fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<Facility, E> {
372                self.visit_i64(
373                    i64::try_from(v)
374                        .map_err(|_| E::invalid_value(serde::de::Unexpected::Unsigned(v), &self))?,
375                )
376            }
377            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Facility, E> {
378                v.parse().map_err(E::custom)
379            }
380        }
381        deserializer.deserialize_any(FacilityVisitor)
382    }
383}
384
385impl ControllerRating {
386    /// All active controller rating variants (excludes deprecated ones).
387    pub const ALL: &'static [Self] = &[
388        Self::Inactive,
389        Self::Suspended,
390        Self::Observer,
391        Self::TowerTrainee,
392        Self::TowerController,
393        Self::SeniorStudent,
394        Self::EnrouteController,
395        Self::SeniorController,
396        Self::Instructor,
397        Self::SeniorInstructor,
398        Self::Supervisor,
399        Self::Administrator,
400    ];
401
402    /// Returns the short string code for this rating (e.g. `"S1"`, `"C1"`).
403    #[must_use]
404    pub const fn as_str(self) -> &'static str {
405        match self {
406            ControllerRating::Inactive => "INAC",
407            ControllerRating::Suspended => "SUS",
408            ControllerRating::Observer => "OBS",
409            ControllerRating::TowerTrainee => "S1",
410            ControllerRating::TowerController => "S2",
411            ControllerRating::SeniorStudent => "S3",
412            ControllerRating::EnrouteController => "C1",
413            #[allow(deprecated)]
414            ControllerRating::Controller2 => "C2",
415            ControllerRating::SeniorController => "C3",
416            ControllerRating::Instructor => "I1",
417            #[allow(deprecated)]
418            ControllerRating::Instructor2 => "I2",
419            ControllerRating::SeniorInstructor => "I3",
420            ControllerRating::Supervisor => "SUP",
421            ControllerRating::Administrator => "ADM",
422        }
423    }
424
425    /// Returns the numeric ID used in the VATSIM data feed for this rating.
426    #[must_use]
427    pub const fn as_id(self) -> i8 {
428        match self {
429            ControllerRating::Inactive => -1,
430            ControllerRating::Suspended => 0,
431            ControllerRating::Observer => 1,
432            ControllerRating::TowerTrainee => 2,
433            ControllerRating::TowerController => 3,
434            ControllerRating::SeniorStudent => 4,
435            ControllerRating::EnrouteController => 5,
436            #[allow(deprecated)]
437            ControllerRating::Controller2 => 6,
438            ControllerRating::SeniorController => 7,
439            ControllerRating::Instructor => 8,
440            #[allow(deprecated)]
441            ControllerRating::Instructor2 => 9,
442            ControllerRating::SeniorInstructor => 10,
443            ControllerRating::Supervisor => 11,
444            ControllerRating::Administrator => 12,
445        }
446    }
447}
448
449impl std::str::FromStr for ControllerRating {
450    type Err = crate::error::ParseError;
451    fn from_str(s: &str) -> Result<Self, Self::Err> {
452        let s = s.to_ascii_uppercase();
453        match s.as_str() {
454            "INAC" | "INACTIVE" => Ok(ControllerRating::Inactive),
455            "SUS" | "SUSPENDED" => Ok(ControllerRating::Suspended),
456            "OBS" | "OBSERVER" => Ok(ControllerRating::Observer),
457            "S1" | "TOWER TRAINEE" => Ok(ControllerRating::TowerTrainee),
458            "S2" | "TOWER CONTROLLER" => Ok(ControllerRating::TowerController),
459            "S3" | "SENIOR STUDENT" => Ok(ControllerRating::SeniorStudent),
460            "C1" | "ENROUTE CONTROLLER" => Ok(ControllerRating::EnrouteController),
461            #[allow(deprecated)]
462            "C2" | "CONTROLLER 2 (NOT IN USE)" => Ok(ControllerRating::Controller2),
463            "C3" | "SENIOR CONTROLLER" => Ok(ControllerRating::SeniorController),
464            "I1" | "INSTRUCTOR" => Ok(ControllerRating::Instructor),
465            #[allow(deprecated)]
466            "I2" | "INSTRUCTOR 2 (NOT IN USE)" => Ok(ControllerRating::Instructor2),
467            "I3" | "SENIOR INSTRUCTOR" => Ok(ControllerRating::SeniorInstructor),
468            "SUP" | "SUPERVISOR" => Ok(ControllerRating::Supervisor),
469            "ADM" | "ADMINISTRATOR" => Ok(ControllerRating::Administrator),
470            other => Err(Self::Err::UnknownValue {
471                kind: "controller rating",
472                value: other.to_string(),
473            }),
474        }
475    }
476}
477
478impl TryFrom<&str> for ControllerRating {
479    type Error = crate::error::ParseError;
480    fn try_from(value: &str) -> Result<Self, Self::Error> {
481        value.parse()
482    }
483}
484
485impl TryFrom<String> for ControllerRating {
486    type Error = crate::error::ParseError;
487    fn try_from(value: String) -> Result<Self, Self::Error> {
488        value.as_str().parse()
489    }
490}
491
492impl TryFrom<i8> for ControllerRating {
493    type Error = crate::error::ParseError;
494    fn try_from(value: i8) -> Result<Self, Self::Error> {
495        match value {
496            -1 => Ok(ControllerRating::Inactive),
497            0 => Ok(ControllerRating::Suspended),
498            1 => Ok(ControllerRating::Observer),
499            2 => Ok(ControllerRating::TowerTrainee),
500            3 => Ok(ControllerRating::TowerController),
501            4 => Ok(ControllerRating::SeniorStudent),
502            5 => Ok(ControllerRating::EnrouteController),
503            #[allow(deprecated)]
504            6 => Ok(ControllerRating::Controller2),
505            7 => Ok(ControllerRating::SeniorController),
506            8 => Ok(ControllerRating::Instructor),
507            #[allow(deprecated)]
508            9 => Ok(ControllerRating::Instructor2),
509            10 => Ok(ControllerRating::SeniorInstructor),
510            11 => Ok(ControllerRating::Supervisor),
511            12 => Ok(ControllerRating::Administrator),
512            other => Err(Self::Error::UnknownValue {
513                kind: "controller rating",
514                value: other.to_string(),
515            }),
516        }
517    }
518}
519
520impl TryFrom<datafeed::RatingInfo> for ControllerRating {
521    type Error = crate::error::ParseError;
522    fn try_from(value: datafeed::RatingInfo) -> Result<Self, Self::Error> {
523        value.id.try_into()
524    }
525}
526
527#[cfg(feature = "serde")]
528impl Serialize for ControllerRating {
529    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
530    where
531        S: Serializer,
532    {
533        serializer.serialize_str(self.as_str())
534    }
535}
536
537#[cfg(feature = "serde")]
538impl<'de> Deserialize<'de> for ControllerRating {
539    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
540    where
541        D: Deserializer<'de>,
542    {
543        #[derive(Clone, Copy)]
544        struct RatingVisitor;
545        impl serde::de::Visitor<'_> for RatingVisitor {
546            type Value = ControllerRating;
547            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
548                f.write_str("a controller rating string or integer ID")
549            }
550            fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<ControllerRating, E> {
551                i8::try_from(v)
552                    .map_err(|_| E::invalid_value(serde::de::Unexpected::Signed(v), &self))
553                    .and_then(|id| ControllerRating::try_from(id).map_err(|e| E::custom(e)))
554            }
555            fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<ControllerRating, E> {
556                self.visit_i64(
557                    i64::try_from(v)
558                        .map_err(|_| E::invalid_value(serde::de::Unexpected::Unsigned(v), &self))?,
559                )
560            }
561            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<ControllerRating, E> {
562                v.parse().map_err(E::custom)
563            }
564        }
565        deserializer.deserialize_any(RatingVisitor)
566    }
567}
568
569impl PilotRating {
570    /// All pilot rating variants.
571    pub const ALL: &'static [Self] = &[
572        Self::BasicMember,
573        Self::PrivatePilotLicense,
574        Self::InstrumentRating,
575        Self::CommercialMultiEngineLicense,
576        Self::AirlineTransportPilotLicense,
577        Self::FlightInstructor,
578        Self::FlightExaminer,
579    ];
580
581    /// Returns the numeric ID the VATSIM data feed uses for this rating.
582    ///
583    /// Pilot rating IDs are a bit field, so they run 0, 1, 3, 7, 15, 31, 63
584    /// rather than consecutively.
585    #[must_use]
586    pub const fn as_id(self) -> i8 {
587        match self {
588            PilotRating::BasicMember => 0,
589            PilotRating::PrivatePilotLicense => 1,
590            PilotRating::InstrumentRating => 3,
591            PilotRating::CommercialMultiEngineLicense => 7,
592            PilotRating::AirlineTransportPilotLicense => 15,
593            PilotRating::FlightInstructor => 31,
594            PilotRating::FlightExaminer => 63,
595        }
596    }
597
598    /// Returns the short string code for this rating (e.g. `"PPL"`, `"ATPL"`).
599    #[must_use]
600    pub const fn as_str(self) -> &'static str {
601        match self {
602            PilotRating::BasicMember => "NEW",
603            PilotRating::PrivatePilotLicense => "PPL",
604            PilotRating::InstrumentRating => "IR",
605            PilotRating::CommercialMultiEngineLicense => "CMEL",
606            PilotRating::AirlineTransportPilotLicense => "ATPL",
607            PilotRating::FlightInstructor => "FI",
608            PilotRating::FlightExaminer => "FE",
609        }
610    }
611}
612
613impl std::str::FromStr for PilotRating {
614    type Err = crate::error::ParseError;
615    fn from_str(s: &str) -> Result<Self, Self::Err> {
616        let s = s.to_ascii_uppercase();
617        match s.as_str() {
618            "NEW" | "BASIC MEMBER" => Ok(PilotRating::BasicMember),
619            "PPL" | "PRIVATE PILOT LICENSE" => Ok(PilotRating::PrivatePilotLicense),
620            "IR" | "INSTRUMENT RATING" => Ok(PilotRating::InstrumentRating),
621            "CMEL" | "COMMERCIAL MULTI-ENGINE LICENSE" => {
622                Ok(PilotRating::CommercialMultiEngineLicense)
623            }
624            "ATPL" | "AIRLINE TRANSPORT PILOT LICENSE" => {
625                Ok(PilotRating::AirlineTransportPilotLicense)
626            }
627            "FI" | "FLIGHT INSTRUCTOR" => Ok(PilotRating::FlightInstructor),
628            "FE" | "FLIGHT EXAMINER" => Ok(PilotRating::FlightExaminer),
629            other => Err(Self::Err::UnknownValue {
630                kind: "pilot rating",
631                value: other.to_string(),
632            }),
633        }
634    }
635}
636
637impl TryFrom<&str> for PilotRating {
638    type Error = crate::error::ParseError;
639    fn try_from(value: &str) -> Result<Self, Self::Error> {
640        value.parse()
641    }
642}
643
644impl TryFrom<String> for PilotRating {
645    type Error = crate::error::ParseError;
646    fn try_from(value: String) -> Result<Self, Self::Error> {
647        value.as_str().parse()
648    }
649}
650
651impl TryFrom<i8> for PilotRating {
652    type Error = crate::error::ParseError;
653    fn try_from(value: i8) -> Result<Self, Self::Error> {
654        match value {
655            0 => Ok(PilotRating::BasicMember),
656            1 => Ok(PilotRating::PrivatePilotLicense),
657            3 => Ok(PilotRating::InstrumentRating),
658            7 => Ok(PilotRating::CommercialMultiEngineLicense),
659            15 => Ok(PilotRating::AirlineTransportPilotLicense),
660            31 => Ok(PilotRating::FlightInstructor),
661            63 => Ok(PilotRating::FlightExaminer),
662            other => Err(Self::Error::UnknownValue {
663                kind: "pilot rating",
664                value: other.to_string(),
665            }),
666        }
667    }
668}
669
670impl TryFrom<datafeed::PilotRatingInfo> for PilotRating {
671    type Error = crate::error::ParseError;
672    fn try_from(value: datafeed::PilotRatingInfo) -> Result<Self, Self::Error> {
673        value.id.try_into()
674    }
675}
676
677#[cfg(feature = "serde")]
678impl Serialize for PilotRating {
679    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
680    where
681        S: Serializer,
682    {
683        serializer.serialize_str(self.as_str())
684    }
685}
686
687#[cfg(feature = "serde")]
688impl<'de> Deserialize<'de> for PilotRating {
689    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
690    where
691        D: Deserializer<'de>,
692    {
693        #[derive(Clone, Copy)]
694        struct RatingVisitor;
695        impl serde::de::Visitor<'_> for RatingVisitor {
696            type Value = PilotRating;
697            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
698                f.write_str("a pilot rating string or integer ID")
699            }
700            fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<PilotRating, E> {
701                i8::try_from(v)
702                    .map_err(|_| E::invalid_value(serde::de::Unexpected::Signed(v), &self))
703                    .and_then(|id| PilotRating::try_from(id).map_err(|e| E::custom(e)))
704            }
705            fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<PilotRating, E> {
706                self.visit_i64(
707                    i64::try_from(v)
708                        .map_err(|_| E::invalid_value(serde::de::Unexpected::Unsigned(v), &self))?,
709                )
710            }
711            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<PilotRating, E> {
712                v.parse().map_err(E::custom)
713            }
714        }
715        deserializer.deserialize_any(RatingVisitor)
716    }
717}
718
719impl MilitaryRating {
720    /// All military rating variants.
721    pub const ALL: &'static [Self] = &[
722        Self::NoMilitaryRating,
723        Self::MilitaryPilotLicense,
724        Self::MilitaryInstrumentRating,
725        Self::MilitaryMultiEngineRating,
726        Self::MilitaryMissionReadyPilot,
727    ];
728
729    /// Returns the numeric ID the VATSIM data feed uses for this rating.
730    ///
731    /// Military rating IDs are a bit field, so they run 0, 1, 3, 7, 15 rather
732    /// than consecutively.
733    #[must_use]
734    pub const fn as_id(self) -> i8 {
735        match self {
736            MilitaryRating::NoMilitaryRating => 0,
737            MilitaryRating::MilitaryPilotLicense => 1,
738            MilitaryRating::MilitaryInstrumentRating => 3,
739            MilitaryRating::MilitaryMultiEngineRating => 7,
740            MilitaryRating::MilitaryMissionReadyPilot => 15,
741        }
742    }
743
744    /// Returns the short string code for this rating (e.g. `"M0"`, `"M4"`).
745    #[must_use]
746    pub const fn as_str(self) -> &'static str {
747        match self {
748            MilitaryRating::NoMilitaryRating => "M0",
749            MilitaryRating::MilitaryPilotLicense => "M1",
750            MilitaryRating::MilitaryInstrumentRating => "M2",
751            MilitaryRating::MilitaryMultiEngineRating => "M3",
752            MilitaryRating::MilitaryMissionReadyPilot => "M4",
753        }
754    }
755}
756
757impl std::str::FromStr for MilitaryRating {
758    type Err = crate::error::ParseError;
759    fn from_str(s: &str) -> Result<Self, Self::Err> {
760        let s = s.to_ascii_uppercase();
761        match s.as_str() {
762            "M0" | "NO MILITARY RATING" => Ok(MilitaryRating::NoMilitaryRating),
763            "M1" | "MILITARY PILOT LICENSE" => Ok(MilitaryRating::MilitaryPilotLicense),
764            "M2" | "MILITARY INSTRUMENT RATING" => Ok(MilitaryRating::MilitaryInstrumentRating),
765            "M3" | "MILITARY MULTI-ENGINE RATING" => Ok(MilitaryRating::MilitaryMultiEngineRating),
766            "M4" | "MILITARY MISSION READY PILOT" => Ok(MilitaryRating::MilitaryMissionReadyPilot),
767            other => Err(Self::Err::UnknownValue {
768                kind: "military rating",
769                value: other.to_string(),
770            }),
771        }
772    }
773}
774
775impl TryFrom<&str> for MilitaryRating {
776    type Error = crate::error::ParseError;
777    fn try_from(value: &str) -> Result<Self, Self::Error> {
778        value.parse()
779    }
780}
781
782impl TryFrom<String> for MilitaryRating {
783    type Error = crate::error::ParseError;
784    fn try_from(value: String) -> Result<Self, Self::Error> {
785        value.as_str().parse()
786    }
787}
788
789impl TryFrom<i8> for MilitaryRating {
790    type Error = crate::error::ParseError;
791    fn try_from(value: i8) -> Result<Self, Self::Error> {
792        match value {
793            0 => Ok(MilitaryRating::NoMilitaryRating),
794            1 => Ok(MilitaryRating::MilitaryPilotLicense),
795            3 => Ok(MilitaryRating::MilitaryInstrumentRating),
796            7 => Ok(MilitaryRating::MilitaryMultiEngineRating),
797            15 => Ok(MilitaryRating::MilitaryMissionReadyPilot),
798            other => Err(Self::Error::UnknownValue {
799                kind: "military rating",
800                value: other.to_string(),
801            }),
802        }
803    }
804}
805
806impl TryFrom<datafeed::MilitaryRatingInfo> for MilitaryRating {
807    type Error = crate::error::ParseError;
808    fn try_from(value: datafeed::MilitaryRatingInfo) -> Result<Self, Self::Error> {
809        value.id.try_into()
810    }
811}
812
813#[cfg(feature = "serde")]
814impl Serialize for MilitaryRating {
815    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
816    where
817        S: Serializer,
818    {
819        serializer.serialize_str(self.as_str())
820    }
821}
822
823#[cfg(feature = "serde")]
824impl<'de> Deserialize<'de> for MilitaryRating {
825    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
826    where
827        D: Deserializer<'de>,
828    {
829        #[derive(Clone, Copy)]
830        struct RatingVisitor;
831        impl serde::de::Visitor<'_> for RatingVisitor {
832            type Value = MilitaryRating;
833            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
834                f.write_str("a military rating string or integer ID")
835            }
836            fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<MilitaryRating, E> {
837                i8::try_from(v)
838                    .map_err(|_| E::invalid_value(serde::de::Unexpected::Signed(v), &self))
839                    .and_then(|id| MilitaryRating::try_from(id).map_err(|e| E::custom(e)))
840            }
841            fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<MilitaryRating, E> {
842                self.visit_i64(
843                    i64::try_from(v)
844                        .map_err(|_| E::invalid_value(serde::de::Unexpected::Unsigned(v), &self))?,
845                )
846            }
847            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<MilitaryRating, E> {
848                v.parse().map_err(E::custom)
849            }
850        }
851        deserializer.deserialize_any(RatingVisitor)
852    }
853}