longport/
macros.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
macro_rules! impl_default_for_enum_string {
    ($($ty:ty),*) => {
        $(
            impl Default for $ty {
                fn default() -> Self {
                    Self::Unknown
                }
            }
        )*
    };
}

macro_rules! impl_serde_for_enum_string {
    ($($ty:ty),*) => {
        $(
            impl<'de> ::serde::Deserialize<'de> for $ty {
                fn deserialize<D: ::serde::Deserializer<'de>>(deserializer: D) -> ::std::result::Result<Self, D::Error> {
                    use std::str::FromStr;
                    let value: ::std::string::String = ::serde::Deserialize::deserialize(deserializer)?;
                    Ok(<$ty>::from_str(&value).unwrap_or_default())
                }
            }

            impl ::serde::Serialize for $ty {
                fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> ::std::result::Result<S::Ok, S::Error> {
                    use std::string::ToString;
                    let value = self.to_string();
                    ::serde::Serialize::serialize(&value, serializer)
                }
            }
        )*
    };
}

macro_rules! impl_serialize_for_enum_string {
    ($($ty:ty),*) => {
        $(
            impl ::serde::Serialize for $ty {
                fn serialize<S: ::serde::Serializer>(&self, serializer: S) -> ::std::result::Result<S::Ok, S::Error> {
                    use std::string::ToString;
                    let value = self.to_string();
                    ::serde::Serialize::serialize(&value, serializer)
                }
            }
        )*
    };
}

/// A macro to construct decimal.
///
/// # Examples
///
/// ```
/// # use longport::decimal;
/// # use rust_decimal::Decimal;
///
/// assert_eq!(decimal!(1.23), Decimal::try_from(1.23).unwrap());
/// ```
///
/// # Panics
///
/// Panic if the input value is invalid.
#[macro_export]
macro_rules! decimal {
    ($value:expr) => {
        $crate::Decimal::try_from($value).expect("valid decimal")
    };
}