Skip to main content

pax_runtime_api/pax_value/
macros.rs

1/// Implements coercion by converting the selected `PaxValue` variant's contents.
2/// The optional third argument opts into `CoercionRules::is_identity_roundtrip`;
3/// omit it unless the type satisfies that method's exact, side-effect-free contract.
4#[macro_export]
5macro_rules! impl_default_coercion_rule {
6    ($Type:ty, $Variant:path) => {
7        $crate::impl_default_coercion_rule!($Type, $Variant, false);
8    };
9    ($Type:ty, $Variant:path, $identity_roundtrip:expr) => {
10        impl CoercionRules for $Type {
11            fn is_identity_roundtrip() -> bool {
12                $identity_roundtrip
13            }
14            fn try_coerce(pax_value: PaxValue) -> Result<Self, String> {
15                if let $Variant(val) = pax_value {
16                    Ok(val.into())
17                } else {
18                    Err(format!(
19                        "couldn't coerce {:?} into {}",
20                        pax_value,
21                        std::any::type_name::<$Type>()
22                    ))
23                }
24            }
25        }
26    };
27}
28
29#[macro_export]
30macro_rules! impl_to_pax_value {
31    // For a single variant path
32    ($Type:ty, $Variant:path) => {
33        impl ToPaxValue for $Type {
34            fn to_pax_value(self) -> PaxValue {
35                $Variant(self)
36            }
37        }
38    };
39    // For nested variant paths like Numeric::U8
40    // looks almost exactly the same as above, just with nested variant
41    ($Type:ty, $OuterVariant:path, $InnerVariant:path) => {
42        impl ToPaxValue for $Type {
43            fn to_pax_value(self) -> PaxValue {
44                $OuterVariant($InnerVariant(self))
45            }
46        }
47    };
48}