longport/
macros.rs

1macro_rules! impl_default_for_enum_string {
2    ($($ty:ty),*) => {
3        $(
4            impl Default for $ty {
5                fn default() -> Self {
6                    Self::Unknown
7                }
8            }
9        )*
10    };
11}
12
13macro_rules! impl_serde_for_enum_string {
14    ($($ty:ty),*) => {
15        $(
16            impl<'de> ::serde::Deserialize<'de> for $ty {
17                fn deserialize<D: ::serde::Deserializer<'de>>(deserializer: D) -> ::std::result::Result<Self, D::Error> {
18                    use std::str::FromStr;
19                    let value: ::std::string::String = ::serde::Deserialize::deserialize(deserializer)?;
20                    Ok(<$ty>::from_str(&value).unwrap_or_default())
21                }
22            }
23
24            impl ::serde::Serialize for $ty {
25                fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> ::std::result::Result<S::Ok, S::Error> {
26                    use std::string::ToString;
27                    let value = self.to_string();
28                    ::serde::Serialize::serialize(&value, serializer)
29                }
30            }
31        )*
32    };
33}
34
35macro_rules! impl_serialize_for_enum_string {
36    ($($ty:ty),*) => {
37        $(
38            impl ::serde::Serialize for $ty {
39                fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> ::std::result::Result<S::Ok, S::Error> {
40                    use std::string::ToString;
41                    let value = self.to_string();
42                    ::serde::Serialize::serialize(&value, serializer)
43                }
44            }
45        )*
46    };
47}
48
49/// A macro to construct decimal.
50///
51/// # Examples
52///
53/// ```
54/// # use longport::decimal;
55/// # use rust_decimal::Decimal;
56///
57/// assert_eq!(decimal!(1.23), Decimal::try_from(1.23).unwrap());
58/// ```
59///
60/// # Panics
61///
62/// Panic if the input value is invalid.
63#[macro_export]
64macro_rules! decimal {
65    ($value:expr) => {
66        $crate::Decimal::try_from($value).expect("valid decimal")
67    };
68}