google_maps2/directions/request/
unit_system.rs

1//! Contains the `UnitSystem` enum and its associated traits. It is used specify
2//! whether imperial or metric units are used in Directions responses.
3
4use crate::directions::error::Error as DirectionsError;
5use crate::error::Error as GoogleMapsError;
6use phf::phf_map;
7use serde::{Deserialize, Deserializer, Serialize, Serializer};
8
9// -----------------------------------------------------------------------------
10
11/// Specifies the [unit
12/// system](https://developers.google.com/maps/documentation/directions/intro#UnitSystems)
13/// to use when displaying results.
14///
15/// Directions results contain `text` within `distance` fields that may be
16/// displayed to the user to indicate the distance of a particular "step" of the
17/// route. By default, this text uses the unit system of the origin's country or
18/// region.
19///
20/// For example, a route from "Chicago, IL" to "Toronto, ONT" will display
21/// results in miles, while the reverse route will display results in
22/// kilometers. You may override this unit system by setting one explicitly
23/// within the request's `units` parameter, passing one of the following values:
24///
25/// **Note**: this unit system setting only affects the `text` displayed within
26/// `distance` fields. The `distance` fields also contain `values` which are
27/// always expressed in meters.
28
29#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
30#[repr(u8)]
31pub enum UnitSystem {
32    /// Specifies that distances in the response should be expressed in imperial
33    /// units, miles and feet.
34    Imperial = 0,
35    /// Specifies that distances in the response should be expressed in metric
36    /// units, using kilometres and metres.
37    #[default]
38    Metric = 1,
39} // enum
40
41// -----------------------------------------------------------------------------
42
43impl<'de> Deserialize<'de> for UnitSystem {
44    /// Manual implementation of `Deserialize` for `serde`. This will take
45    /// advantage of the `phf`-powered `TryFrom` implementation for this type.
46    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
47        let string = String::deserialize(deserializer)?;
48        match Self::try_from(string.as_str()) {
49            Ok(variant) => Ok(variant),
50            Err(error) => Err(serde::de::Error::custom(error.to_string())),
51        } // match
52    } // fn
53} // impl
54
55// -----------------------------------------------------------------------------
56
57impl Serialize for UnitSystem {
58    /// Manual implementation of `Serialize` for `serde`.
59    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
60    where
61        S: Serializer,
62    {
63        serializer.serialize_str(std::convert::Into::<&str>::into(self))
64    } // fn
65} // impl
66
67// -----------------------------------------------------------------------------
68
69impl std::convert::From<&UnitSystem> for &str {
70    /// Converts a `UnitSystem` enum to a `String` that contains a [unit
71    /// system](https://developers.google.com/maps/documentation/directions/intro#UnitSystems)
72    /// code.
73    fn from(units: &UnitSystem) -> Self {
74        match units {
75            UnitSystem::Imperial => "imperial",
76            UnitSystem::Metric => "metric",
77        } // match
78    } // fn
79} // impl
80
81// -----------------------------------------------------------------------------
82
83impl std::fmt::Display for UnitSystem {
84    /// Converts a `UnitSystem` enum to a `String` that contains a [unit
85    /// system](https://developers.google.com/maps/documentation/directions/intro#UnitSystems)
86    /// code.
87    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        write!(f, "{}", std::convert::Into::<&str>::into(self))
89    } // fmt
90} // impl
91
92// -----------------------------------------------------------------------------
93
94impl std::convert::From<&UnitSystem> for String {
95    /// Converts a `UnitSystem` enum to a `String` that contains a [unit
96    /// system](https://developers.google.com/maps/documentation/directions/intro#UnitSystems)
97    /// code.
98    fn from(unit_system: &UnitSystem) -> Self {
99        std::convert::Into::<&str>::into(unit_system).to_string()
100    } // fn
101} // impl
102
103// -----------------------------------------------------------------------------
104
105static UNIT_SYSTEMS_BY_CODE: phf::Map<&'static str, UnitSystem> = phf_map! {
106    "imperial" => UnitSystem::Imperial,
107    "metric" => UnitSystem::Metric,
108};
109
110// -----------------------------------------------------------------------------
111
112impl std::convert::TryFrom<&str> for UnitSystem {
113    // Error definitions are contained in the
114    // `google_maps\src\directions\error.rs` module.
115    type Error = GoogleMapsError;
116    /// Gets a `UnitSystem` enum from a `String` that contains a valid [unit
117    /// system](https://developers.google.com/maps/documentation/directions/intro#UnitSystems)
118    /// code.
119    fn try_from(unit_system_code: &str) -> Result<Self, Self::Error> {
120        Ok(UNIT_SYSTEMS_BY_CODE
121            .get(unit_system_code)
122            .cloned()
123            .ok_or_else(|| DirectionsError::InvalidUnitSystemCode(unit_system_code.to_string()))?)
124    } // fn
125} // impl
126
127// -----------------------------------------------------------------------------
128
129impl std::str::FromStr for UnitSystem {
130    // Error definitions are contained in the
131    // `google_maps\src\directions\error.rs` module.
132    type Err = GoogleMapsError;
133    /// Gets a `UnitSystem` enum from a `String` that contains a valid [unit
134    /// system](https://developers.google.com/maps/documentation/directions/intro#UnitSystems)
135    /// code.
136    fn from_str(unit_system_code: &str) -> Result<Self, Self::Err> {
137        Ok(UNIT_SYSTEMS_BY_CODE
138            .get(unit_system_code)
139            .cloned()
140            .ok_or_else(|| DirectionsError::InvalidUnitSystemCode(unit_system_code.to_string()))?)
141    } // fn
142} // impl
143
144// -----------------------------------------------------------------------------
145
146impl UnitSystem {
147    /// Formats a `UnitSystem` enum into a string that is presentable to the
148    /// end user.
149    #[must_use]
150    pub const fn display(&self) -> &str {
151        match self {
152            Self::Imperial => "Imperial",
153            Self::Metric => "Metric",
154        } // match
155    } // fn
156} // impl