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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
use crate::{
    Attributes, Axes, BinaryString, BrickColor, CFrame, Color3, Color3uint8, ColorSequence,
    Content, Enum, Faces, Font, MaterialColors, NumberRange, NumberSequence, PhysicalProperties,
    Ray, Rect, Ref, Region3, Region3int16, SecurityCapabilities, SharedString, Tags, UDim, UDim2,
    UniqueId, Vector2, Vector2int16, Vector3, Vector3int16,
};

/// Reduces boilerplate from listing different values of Variant by wrapping
/// them into a macro.
macro_rules! make_variant {
    (
        $(
            $( #[$attr:meta] )*
            $variant_name:ident ($inner_type:ty),
        )*
    ) => {
        /// Represents any Roblox type. Useful for operating generically on
        /// Roblox instances.
        ///
        /// ## Stability
        ///
        /// New variants may be added to `Variant` in minor releases. As
        /// such, it is marked `#[non_exhaustive]`.
        #[derive(Debug, Clone, PartialEq)]
        #[non_exhaustive]
        #[cfg_attr(
            feature = "serde",
            derive(serde::Serialize, serde::Deserialize),
        )]
        pub enum Variant {
            $(
                $(
                    #[$attr]
                )*
                $variant_name($inner_type),
            )*
        }

        impl Variant {
            pub fn ty(&self) -> VariantType {
                match self {
                    $(
                        Variant::$variant_name(_) => VariantType::$variant_name,
                    )*
                }
            }
        }

        $(
            impl From<$inner_type> for Variant {
                fn from(value: $inner_type) -> Self {
                    Self::$variant_name(value)
                }
            }
        )*

        /// Represents any type that can be held in a `Variant`.
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
        #[non_exhaustive]
        #[cfg_attr(
            feature = "serde",
            derive(serde::Serialize, serde::Deserialize),
        )]
        pub enum VariantType {
            $(
                $variant_name,
            )*
        }

        #[cfg(test)]
        mod generated_test {
            use super::*;

            /// This test makes sure that every type represented in `Variant`
            /// can be converted via `Into` into Variant.
            ///
            /// If we forget to impl From when new types are added to Variant,
            /// this test will start failing.
            #[allow(dead_code)]
            fn conversions_are_exhaustive() {
                fn trait_test<T: Into<Variant>>() {}

                $( trait_test::<$inner_type>(); )*
                trait_test::<SharedString>();
            }
        }
    };
}

// IMPORTANT! The order of this enum is very important in order to preserve the
// discriminant values that Rust assigns for both Variant and VariantType. Any
// newly-added variants MUST be added to the end!
make_variant! {
    Axes(Axes),
    BinaryString(BinaryString),
    Bool(bool),
    BrickColor(BrickColor),
    CFrame(CFrame),
    Color3(Color3),
    Color3uint8(Color3uint8),
    ColorSequence(ColorSequence),
    Content(Content),
    Enum(Enum),
    Faces(Faces),
    Float32(f32),
    Float64(f64),
    Int32(i32),
    Int64(i64),
    NumberRange(NumberRange),
    NumberSequence(NumberSequence),
    PhysicalProperties(PhysicalProperties),
    Ray(Ray),
    Rect(Rect),
    Ref(Ref),
    Region3(Region3),
    Region3int16(Region3int16),
    #[cfg_attr(
        feature = "serde",
        serde(with = "crate::shared_string::variant_serialization"),
    )]
    SharedString(SharedString),
    String(String),
    UDim(UDim),
    UDim2(UDim2),
    Vector2(Vector2),
    Vector2int16(Vector2int16),
    Vector3(Vector3),
    Vector3int16(Vector3int16),
    OptionalCFrame(Option<CFrame>),
    Tags(Tags),
    Attributes(Attributes),
    Font(Font),
    UniqueId(UniqueId),
    MaterialColors(MaterialColors),
    SecurityCapabilities(SecurityCapabilities),
}

impl From<&'_ str> for Variant {
    fn from(value: &str) -> Self {
        Self::String(value.to_owned())
    }
}

#[cfg(all(test, feature = "serde"))]
mod serde_test {
    use super::*;

    #[test]
    fn human() {
        let vec2 = Variant::Vector2(Vector2::new(5.0, 7.0));

        let ser = serde_json::to_string(&vec2).unwrap();
        assert_eq!(ser, r#"{"Vector2":[5.0,7.0]}"#);

        let de: Variant = serde_json::from_str(&ser).unwrap();
        assert_eq!(de, vec2);
    }

    #[test]
    fn non_human() {
        let vec2 = Variant::Vector2(Vector2::new(5.0, 7.0));

        let ser = bincode::serialize(&vec2).unwrap();

        let de: Variant = bincode::deserialize(&ser).unwrap();
        assert_eq!(de, vec2);
    }
}